path
stringlengths 14
112
| content
stringlengths 0
6.32M
| size
int64 0
6.32M
| max_lines
int64 1
100k
| repo_name
stringclasses 2
values | autogenerated
bool 1
class |
---|---|---|---|---|---|
cosmopolitan/third_party/python/Modules/signalmodule.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:8;coding:utf-8 -*-â
âvi: set net ft=c ts=4 sts=4 sw=4 fenc=utf-8 :viâ
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ¡
â Python 3 â
â https://docs.python.org/3/license.html â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
#include "libc/calls/calls.h"
#include "libc/calls/struct/itimerval.h"
#include "libc/calls/struct/sigset.h"
#include "libc/dce.h"
#include "libc/errno.h"
#include "libc/math.h"
#include "libc/sysv/consts/itimer.h"
#include "libc/sysv/consts/sig.h"
#include "libc/thread/thread.h"
#include "libc/time/time.h"
#include "third_party/python/Include/abstract.h"
#include "third_party/python/Include/ceval.h"
#include "third_party/python/Include/dictobject.h"
#include "third_party/python/Include/fileutils.h"
#include "third_party/python/Include/floatobject.h"
#include "third_party/python/Include/import.h"
#include "third_party/python/Include/intrcheck.h"
#include "third_party/python/Include/longobject.h"
#include "third_party/python/Include/modsupport.h"
#include "third_party/python/Include/pgenheaders.h"
#include "third_party/python/Include/pyatomic.h"
#include "third_party/python/Include/pyerrors.h"
#include "third_party/python/Include/pylifecycle.h"
#include "third_party/python/Include/pymacro.h"
#include "third_party/python/Include/setobject.h"
#include "third_party/python/Include/tupleobject.h"
#include "third_party/python/Include/yoink.h"
#include "third_party/python/Modules/posixmodule.h"
#include "third_party/python/pyconfig.h"
/* clang-format off */
PYTHON_PROVIDE("_signal");
PYTHON_PROVIDE("_signal.ITIMER_PROF");
PYTHON_PROVIDE("_signal.ITIMER_REAL");
PYTHON_PROVIDE("_signal.ITIMER_VIRTUAL");
PYTHON_PROVIDE("_signal.ItimerError");
PYTHON_PROVIDE("_signal.NSIG");
PYTHON_PROVIDE("_signal.SIGABRT");
PYTHON_PROVIDE("_signal.SIGALRM");
PYTHON_PROVIDE("_signal.SIGBUS");
PYTHON_PROVIDE("_signal.SIGCHLD");
PYTHON_PROVIDE("_signal.SIGCONT");
PYTHON_PROVIDE("_signal.SIGFPE");
PYTHON_PROVIDE("_signal.SIGHUP");
PYTHON_PROVIDE("_signal.SIGILL");
PYTHON_PROVIDE("_signal.SIGINT");
PYTHON_PROVIDE("_signal.SIGIO");
PYTHON_PROVIDE("_signal.SIGIOT");
PYTHON_PROVIDE("_signal.SIGKILL");
PYTHON_PROVIDE("_signal.SIGPIPE");
PYTHON_PROVIDE("_signal.SIGPOLL");
PYTHON_PROVIDE("_signal.SIGPROF");
PYTHON_PROVIDE("_signal.SIGPWR");
PYTHON_PROVIDE("_signal.SIGQUIT");
PYTHON_PROVIDE("_signal.SIGRTMAX");
PYTHON_PROVIDE("_signal.SIGRTMIN");
PYTHON_PROVIDE("_signal.SIGSEGV");
PYTHON_PROVIDE("_signal.SIGSTOP");
PYTHON_PROVIDE("_signal.SIGSYS");
PYTHON_PROVIDE("_signal.SIGTERM");
PYTHON_PROVIDE("_signal.SIGTRAP");
PYTHON_PROVIDE("_signal.SIGTSTP");
PYTHON_PROVIDE("_signal.SIGTTIN");
PYTHON_PROVIDE("_signal.SIGTTOU");
PYTHON_PROVIDE("_signal.SIGURG");
PYTHON_PROVIDE("_signal.SIGUSR1");
PYTHON_PROVIDE("_signal.SIGUSR2");
PYTHON_PROVIDE("_signal.SIGVTALRM");
PYTHON_PROVIDE("_signal.SIGWINCH");
PYTHON_PROVIDE("_signal.SIGXCPU");
PYTHON_PROVIDE("_signal.SIGXFSZ");
PYTHON_PROVIDE("_signal.SIG_BLOCK");
PYTHON_PROVIDE("_signal.SIG_DFL");
PYTHON_PROVIDE("_signal.SIG_IGN");
PYTHON_PROVIDE("_signal.SIG_SETMASK");
PYTHON_PROVIDE("_signal.SIG_UNBLOCK");
PYTHON_PROVIDE("_signal.alarm");
PYTHON_PROVIDE("_signal.default_int_handler");
PYTHON_PROVIDE("_signal.getitimer");
PYTHON_PROVIDE("_signal.getsignal");
PYTHON_PROVIDE("_signal.pause");
PYTHON_PROVIDE("_signal.pthread_kill");
PYTHON_PROVIDE("_signal.pthread_sigmask");
PYTHON_PROVIDE("_signal.set_wakeup_fd");
PYTHON_PROVIDE("_signal.setitimer");
PYTHON_PROVIDE("_signal.siginterrupt");
PYTHON_PROVIDE("_signal.signal");
PYTHON_PROVIDE("_signal.sigpending");
PYTHON_PROVIDE("_signal.sigtimedwait");
PYTHON_PROVIDE("_signal.sigwait");
PYTHON_PROVIDE("_signal.sigwaitinfo");
PYTHON_PROVIDE("_signal.struct_siginfo");
/* Signal module -- many thanks to Lance Ellinghaus */
/* XXX Signals should be recorded per thread, now we have thread state. */
#if defined(HAVE_PTHREAD_SIGMASK) && !defined(HAVE_BROKEN_PTHREAD_SIGMASK)
# define PYPTHREAD_SIGMASK
#endif
#include "third_party/python/Modules/clinic/signalmodule.inc"
/*[clinic input]
module signal
[clinic start generated code]*/
/*[clinic end generated code: output=da39a3ee5e6b4b0d input=b0301a3bde5fe9d3]*/
/*
NOTES ON THE INTERACTION BETWEEN SIGNALS AND THREADS
When threads are supported, we want the following semantics:
- only the main thread can set a signal handler
- any thread can get a signal handler
- signals are only delivered to the main thread
I.e. we don't support "synchronous signals" like SIGFPE (catching
this doesn't make much sense in Python anyway) nor do we support
signals as a means of inter-thread communication, since not all
thread implementations support that (at least our thread library
doesn't).
We still have the problem that in some implementations signals
generated by the keyboard (e.g. SIGINT) are delivered to all
threads (e.g. SGI), while in others (e.g. Solaris) such signals are
delivered to one random thread (an intermediate possibility would
be to deliver it to the main thread -- POSIX?). For now, we have
a working implementation that works in all three cases -- the
handler ignores signals if getpid() isn't the same as in the main
thread. XXX This is a hack.
*/
#ifdef WITH_THREAD
#include "third_party/python/Include/pythread.h"
static long main_thread;
static pid_t main_pid;
#endif
static volatile struct {
_Py_atomic_int tripped;
PyObject *func;
} Handlers[Py_NSIG];
#ifdef MS_WINDOWS
#define INVALID_FD ((SOCKET_T)-1)
static volatile struct {
SOCKET_T fd;
int use_send;
int send_err_set;
int send_errno;
int send_win_error;
} wakeup = {INVALID_FD, 0, 0};
#else
#define INVALID_FD (-1)
static volatile sig_atomic_t wakeup_fd = -1;
#endif
/* Speed up sigcheck() when none tripped */
static _Py_atomic_int is_tripped;
static PyObject *DefaultHandler;
static PyObject *IgnoreHandler;
static PyObject *IntHandler;
#ifdef MS_WINDOWS
static HANDLE sigint_event = NULL;
#endif
#ifdef HAVE_GETITIMER
static PyObject *ItimerError;
/* auxiliary functions for setitimer/getitimer */
static void
timeval_from_double(double d, struct timeval *tv)
{
tv->tv_sec = floor(d);
tv->tv_usec = fmod(d, 1.0) * 1000000.0;
/* Don't disable the timer if the computation above rounds down to zero. */
if (d > 0.0 && tv->tv_sec == 0 && tv->tv_usec == 0) {
tv->tv_usec = 1;
}
}
Py_LOCAL_INLINE(double)
double_from_timeval(struct timeval *tv)
{
return tv->tv_sec + (double)(tv->tv_usec / 1000000.0);
}
static PyObject *
itimer_retval(struct itimerval *iv)
{
PyObject *r, *v;
r = PyTuple_New(2);
if (r == NULL)
return NULL;
if(!(v = PyFloat_FromDouble(double_from_timeval(&iv->it_value)))) {
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;
}
PyTuple_SET_ITEM(r, 1, v);
return r;
}
#endif
static PyObject *
signal_default_int_handler(PyObject *self, PyObject *args)
{
PyErr_SetNone(PyExc_KeyboardInterrupt);
return NULL;
}
PyDoc_STRVAR(default_int_handler_doc,
"default_int_handler(...)\n\
\n\
The default handler for SIGINT installed by Python.\n\
It raises KeyboardInterrupt.");
static int
report_wakeup_write_error(void *data)
{
int save_errno = errno;
errno = (int) (intptr_t) data;
PyErr_SetFromErrno(PyExc_OSError);
PySys_WriteStderr("Exception ignored when trying to write to the "
"signal wakeup fd:\n");
PyErr_WriteUnraisable(NULL);
errno = save_errno;
return 0;
}
#ifdef MS_WINDOWS
static int
report_wakeup_send_error(void* Py_UNUSED(data))
{
PyObject *res;
if (wakeup.send_win_error) {
/* PyErr_SetExcFromWindowsErr() invokes FormatMessage() which
recognizes the error codes used by both GetLastError() and
WSAGetLastError */
res = PyErr_SetExcFromWindowsErr(PyExc_OSError, wakeup.send_win_error);
}
else {
errno = wakeup.send_errno;
res = PyErr_SetFromErrno(PyExc_OSError);
}
assert(res == NULL);
wakeup.send_err_set = 0;
PySys_WriteStderr("Exception ignored when trying to send to the "
"signal wakeup fd:\n");
PyErr_WriteUnraisable(NULL);
return 0;
}
#endif /* MS_WINDOWS */
static void
trip_signal(int sig_num)
{
unsigned char byte;
int fd;
Py_ssize_t rc;
_Py_atomic_store_relaxed(&Handlers[sig_num].tripped, 1);
/* Set is_tripped after setting .tripped, as it gets
cleared in PyErr_CheckSignals() before .tripped. */
_Py_atomic_store(&is_tripped, 1);
/* Notify ceval.c */
_PyEval_SignalReceived();
/* And then write to the wakeup fd *after* setting all the globals and
doing the _PyEval_SignalReceived. We used to write to the wakeup fd
and then set the flag, but this allowed the following sequence of events
(especially on windows, where trip_signal may run in a new thread):
- main thread blocks on select([wakeup_fd], ...)
- signal arrives
- trip_signal writes to the wakeup fd
- the main thread wakes up
- the main thread checks the signal flags, sees that they're unset
- the main thread empties the wakeup fd
- the main thread goes back to sleep
- trip_signal sets the flags to request the Python-level signal handler
be run
- the main thread doesn't notice, because it's asleep
See bpo-30038 for more details.
*/
#ifdef MS_WINDOWS
fd = Py_SAFE_DOWNCAST(wakeup.fd, SOCKET_T, int);
#else
fd = wakeup_fd;
#endif
if (fd != INVALID_FD) {
byte = (unsigned char)sig_num;
#ifdef MS_WINDOWS
if (wakeup.use_send) {
do {
rc = send(fd, &byte, 1, 0);
} while (rc < 0 && errno == EINTR);
/* we only have a storage for one error in the wakeup structure */
if (rc < 0 && !wakeup.send_err_set) {
wakeup.send_err_set = 1;
wakeup.send_errno = errno;
wakeup.send_win_error = GetLastError();
/* Py_AddPendingCall() isn't signal-safe, but we
still use it for this exceptional case. */
Py_AddPendingCall(report_wakeup_send_error, NULL);
}
}
else
#endif
{
byte = (unsigned char)sig_num;
/* _Py_write_noraise() retries write() if write() is interrupted by
a signal (fails with EINTR). */
rc = _Py_write_noraise(fd, &byte, 1);
if (rc < 0) {
/* Py_AddPendingCall() isn't signal-safe, but we
still use it for this exceptional case. */
Py_AddPendingCall(report_wakeup_write_error,
(void *)(intptr_t)errno);
}
}
}
}
static void
signal_handler(int sig_num)
{
int save_errno = errno;
#ifdef WITH_THREAD
/* See NOTES section above */
if (getpid() == main_pid)
#endif
{
trip_signal(sig_num);
}
#ifndef HAVE_SIGACTION
#ifdef 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... */
if (sig_num != SIGCHLD)
#endif
/* If the handler was not set up with sigaction, reinstall it. See
* Python/pylifecycle.c for the implementation of PyOS_setsig which
* makes this true. See also issue8354. */
PyOS_setsig(sig_num, signal_handler);
#endif
/* Issue #10311: asynchronously executing signal handlers should not
mutate errno under the feet of unsuspecting C code. */
errno = save_errno;
#ifdef MS_WINDOWS
if (sig_num == SIGINT)
SetEvent(sigint_event);
#endif
}
#ifdef HAVE_ALARM
/*[clinic input]
signal.alarm -> long
seconds: int
/
Arrange for SIGALRM to arrive after the given number of seconds.
[clinic start generated code]*/
static long
signal_alarm_impl(PyObject *module, int seconds)
/*[clinic end generated code: output=144232290814c298 input=0d5e97e0e6f39e86]*/
{
/* alarm() returns the number of seconds remaining */
return (long)alarm(seconds);
}
#endif
#ifdef HAVE_PAUSE
/*[clinic input]
signal.pause
Wait until a signal arrives.
[clinic start generated code]*/
static PyObject *
signal_pause_impl(PyObject *module)
/*[clinic end generated code: output=391656788b3c3929 input=f03de0f875752062]*/
{
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_RETURN_NONE;
}
#endif
/*[clinic input]
signal.signal
signalnum: int
handler: object
/
Set the action for the given signal.
The action can be SIG_DFL, SIG_IGN, or a callable Python object.
The previous action is returned. See getsignal() for possible return values.
*** IMPORTANT NOTICE ***
A signal handler function is called with two arguments:
the first is the signal number, the second is the interrupted stack frame.
[clinic start generated code]*/
static PyObject *
signal_signal_impl(PyObject *module, int signalnum, PyObject *handler)
/*[clinic end generated code: output=b44cfda43780f3a1 input=deee84af5fa0432c]*/
{
PyObject *old_handler;
void (*func)(int);
#ifdef MS_WINDOWS
/* Validate that signalnum is one of the allowable signals */
switch (signalnum) {
case SIGABRT: break;
#ifdef SIGBREAK
/* Issue #10003: SIGBREAK is not documented as permitted, but works
and corresponds to CTRL_BREAK_EVENT. */
case SIGBREAK: break;
#endif
case SIGFPE: break;
case SIGILL: break;
case SIGINT: break;
case SIGSEGV: break;
case SIGTERM: break;
default:
PyErr_SetString(PyExc_ValueError, "invalid signal value");
return NULL;
}
#endif
#ifdef WITH_THREAD
if (PyThread_get_thread_ident() != main_thread) {
PyErr_SetString(PyExc_ValueError,
"signal only works in main thread");
return NULL;
}
#endif
if (signalnum < 1 || signalnum >= Py_NSIG) {
PyErr_SetString(PyExc_ValueError,
"signal number out of range");
return NULL;
}
if (handler == IgnoreHandler)
func = SIG_IGN;
else if (handler == DefaultHandler)
func = SIG_DFL;
else if (!PyCallable_Check(handler)) {
PyErr_SetString(PyExc_TypeError,
"signal handler must be signal.SIG_IGN, signal.SIG_DFL, or a callable object");
return NULL;
}
else
func = signal_handler;
/* Check for pending signals before changing signal handler */
if (PyErr_CheckSignals()) {
return NULL;
}
if (PyOS_setsig(signalnum, func) == SIG_ERR) {
PyErr_SetFromErrno(PyExc_OSError);
return NULL;
}
old_handler = Handlers[signalnum].func;
Py_INCREF(handler);
Handlers[signalnum].func = handler;
if (old_handler != NULL)
return old_handler;
else
Py_RETURN_NONE;
}
/*[clinic input]
signal.getsignal
signalnum: int
/
Return the current action for the given signal.
The return value can be:
SIG_IGN -- if the signal is being ignored
SIG_DFL -- if the default action for the signal is in effect
None -- if an unknown handler is in effect
anything else -- the callable Python object used as a handler
[clinic start generated code]*/
static PyObject *
signal_getsignal_impl(PyObject *module, int signalnum)
/*[clinic end generated code: output=35b3e0e796fd555e input=ac23a00f19dfa509]*/
{
PyObject *old_handler;
if (signalnum < 1 || signalnum >= Py_NSIG) {
PyErr_SetString(PyExc_ValueError,
"signal number out of range");
return NULL;
}
old_handler = Handlers[signalnum].func;
if (old_handler != NULL) {
Py_INCREF(old_handler);
return old_handler;
}
else {
Py_RETURN_NONE;
}
}
#ifdef HAVE_SIGINTERRUPT
/*[clinic input]
signal.siginterrupt
signalnum: int
flag: int
/
Change system call restart behaviour.
If flag is False, system calls will be restarted when interrupted by
signal sig, else system calls will be interrupted.
[clinic start generated code]*/
static PyObject *
signal_siginterrupt_impl(PyObject *module, int signalnum, int flag)
/*[clinic end generated code: output=063816243d85dd19 input=4160acacca3e2099]*/
{
if (signalnum < 1 || signalnum >= Py_NSIG) {
PyErr_SetString(PyExc_ValueError,
"signal number out of range");
return NULL;
}
if (siginterrupt(signalnum, flag)<0) {
PyErr_SetFromErrno(PyExc_OSError);
return NULL;
}
Py_RETURN_NONE;
}
#endif
static PyObject*
signal_set_wakeup_fd(PyObject *self, PyObject *args)
{
struct _Py_stat_struct status;
#ifdef MS_WINDOWS
PyObject *fdobj;
SOCKET_T sockfd, old_sockfd;
int res;
int res_size = sizeof res;
PyObject *mod;
int is_socket;
if (!PyArg_ParseTuple(args, "O:set_wakeup_fd", &fdobj))
return NULL;
sockfd = PyLong_AsSocket_t(fdobj);
if (sockfd == (SOCKET_T)(-1) && PyErr_Occurred())
return NULL;
#else
int fd, old_fd;
if (!PyArg_ParseTuple(args, "i:set_wakeup_fd", &fd))
return NULL;
#endif
#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
#ifdef MS_WINDOWS
is_socket = 0;
if (sockfd != INVALID_FD) {
/* Import the _socket module to call WSAStartup() */
mod = PyImport_ImportModuleNoBlock("_socket");
if (mod == NULL)
return NULL;
Py_DECREF(mod);
/* test the socket */
if (getsockopt(sockfd, SOL_SOCKET, SO_ERROR,
(char *)&res, &res_size) != 0) {
int fd, err;
err = WSAGetLastError();
if (err != WSAENOTSOCK) {
PyErr_SetExcFromWindowsErr(PyExc_OSError, err);
return NULL;
}
fd = (int)sockfd;
if ((SOCKET_T)fd != sockfd) {
PyErr_SetString(PyExc_ValueError, "invalid fd");
return NULL;
}
if (_Py_fstat(fd, &status) != 0)
return NULL;
/* on Windows, a file cannot be set to non-blocking mode */
}
else {
is_socket = 1;
/* Windows does not provide a function to test if a socket
is in non-blocking mode */
}
}
old_sockfd = wakeup.fd;
wakeup.fd = sockfd;
wakeup.use_send = is_socket;
if (old_sockfd != INVALID_FD)
return PyLong_FromSocket_t(old_sockfd);
else
return PyLong_FromLong(-1);
#else
if (fd != -1) {
int blocking;
if (_Py_fstat(fd, &status) != 0)
return NULL;
blocking = _Py_get_blocking(fd);
if (blocking < 0)
return NULL;
if (blocking) {
PyErr_Format(PyExc_ValueError,
"the fd %i must be in non-blocking mode",
fd);
return NULL;
}
}
old_fd = wakeup_fd;
wakeup_fd = fd;
return PyLong_FromLong(old_fd);
#endif
}
PyDoc_STRVAR(set_wakeup_fd_doc,
"set_wakeup_fd(fd) -> fd\n\
\n\
Sets the fd to be written to (with the signal number) when a signal\n\
comes in. A library can use this to wakeup select or poll.\n\
The previous fd or -1 is returned.\n\
\n\
The fd must be non-blocking.");
/* C API for the same, without all the error checking */
int
PySignal_SetWakeupFd(int fd)
{
int old_fd;
if (fd < 0)
fd = -1;
#ifdef MS_WINDOWS
old_fd = Py_SAFE_DOWNCAST(wakeup.fd, SOCKET_T, int);
wakeup.fd = fd;
#else
old_fd = wakeup_fd;
wakeup_fd = fd;
#endif
return old_fd;
}
#ifdef HAVE_SETITIMER
/*[clinic input]
signal.setitimer
which: int
seconds: double
interval: double = 0.0
/
Sets given itimer (one of ITIMER_REAL, ITIMER_VIRTUAL or ITIMER_PROF).
The timer will fire after value seconds and after that every interval seconds.
The itimer can be cleared by setting seconds to zero.
Returns old values as a tuple: (delay, interval).
[clinic start generated code]*/
static PyObject *
signal_setitimer_impl(PyObject *module, int which, double seconds,
double interval)
/*[clinic end generated code: output=6f51da0fe0787f2c input=0d27d417cfcbd51a]*/
{
struct itimerval new, old;
timeval_from_double(seconds, &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;
}
return itimer_retval(&old);
}
#endif
#ifdef HAVE_GETITIMER
/*[clinic input]
signal.getitimer
which: int
/
Returns current value of given itimer.
[clinic start generated code]*/
static PyObject *
signal_getitimer_impl(PyObject *module, int which)
/*[clinic end generated code: output=9e053175d517db40 input=f7d21d38f3490627]*/
{
struct itimerval old;
if (getitimer(which, &old) != 0) {
PyErr_SetFromErrno(ItimerError);
return NULL;
}
return itimer_retval(&old);
}
#endif
#if defined(PYPTHREAD_SIGMASK) || defined(HAVE_SIGWAIT) || \
defined(HAVE_SIGWAITINFO) || defined(HAVE_SIGTIMEDWAIT)
/* Convert an iterable to a sigset.
Return 0 on success, return -1 and raise an exception on error. */
static int
iterable_to_sigset(PyObject *iterable, sigset_t *mask)
{
int result = -1;
PyObject *iterator, *item;
long signum;
sigemptyset(mask);
iterator = PyObject_GetIter(iterable);
if (iterator == NULL)
goto error;
while (1)
{
item = PyIter_Next(iterator);
if (item == NULL) {
if (PyErr_Occurred())
goto error;
else
break;
}
signum = PyLong_AsLong(item);
Py_DECREF(item);
if (signum == -1 && PyErr_Occurred())
goto error;
if (0 < signum && signum < Py_NSIG) {
/* bpo-33329: ignore sigaddset() return value as it can fail
* for some reserved signals, but we want the `range(1, NSIG)`
* idiom to allow selecting all valid signals.
*/
(void) sigaddset(mask, (int)signum);
}
else {
PyErr_Format(PyExc_ValueError,
"signal number %ld out of range", signum);
goto error;
}
}
result = 0;
error:
Py_XDECREF(iterator);
return result;
}
#endif
#if defined(PYPTHREAD_SIGMASK) || defined(HAVE_SIGPENDING)
static PyObject*
sigset_to_set(sigset_t mask)
{
PyObject *signum, *result;
int sig;
result = PySet_New(0);
if (result == NULL)
return NULL;
for (sig = 1; sig < Py_NSIG; sig++) {
if (sigismember(&mask, sig) != 1)
continue;
/* Handle the case where it is a member by adding the signal to
the result list. Ignore the other cases because they mean the
signal isn't a member of the mask or the signal was invalid,
and an invalid signal must have been our fault in constructing
the loop boundaries. */
signum = PyLong_FromLong(sig);
if (signum == NULL) {
Py_DECREF(result);
return NULL;
}
if (PySet_Add(result, signum) == -1) {
Py_DECREF(signum);
Py_DECREF(result);
return NULL;
}
Py_DECREF(signum);
}
return result;
}
#endif
#ifdef PYPTHREAD_SIGMASK
/*[clinic input]
signal.pthread_sigmask
how: int
mask: object
/
Fetch and/or change the signal mask of the calling thread.
[clinic start generated code]*/
static PyObject *
signal_pthread_sigmask_impl(PyObject *module, int how, PyObject *mask)
/*[clinic end generated code: output=ff640fe092bc9181 input=f3b7d7a61b7b8283]*/
{
sigset_t newmask, previous;
int err;
if (iterable_to_sigset(mask, &newmask))
return NULL;
err = pthread_sigmask(how, &newmask, &previous);
if (err != 0) {
errno = err;
PyErr_SetFromErrno(PyExc_OSError);
return NULL;
}
/* if signals was unblocked, signal handlers have been called */
if (PyErr_CheckSignals())
return NULL;
return sigset_to_set(previous);
}
#endif /* #ifdef PYPTHREAD_SIGMASK */
#ifdef HAVE_SIGPENDING
/*[clinic input]
signal.sigpending
Examine pending signals.
Returns a set of signal numbers that are pending for delivery to
the calling thread.
[clinic start generated code]*/
static PyObject *
signal_sigpending_impl(PyObject *module)
/*[clinic end generated code: output=53375ffe89325022 input=e0036c016f874e29]*/
{
int err;
sigset_t mask;
err = sigpending(&mask);
if (err)
return PyErr_SetFromErrno(PyExc_OSError);
return sigset_to_set(mask);
}
#endif /* #ifdef HAVE_SIGPENDING */
#ifdef HAVE_SIGWAIT
/*[clinic input]
signal.sigwait
sigset: object
/
Wait for a signal.
Suspend execution of the calling thread until the delivery of one of the
signals specified in the signal set sigset. The function accepts the signal
and returns the signal number.
[clinic start generated code]*/
static PyObject *
signal_sigwait(PyObject *module, PyObject *sigset)
/*[clinic end generated code: output=557173647424f6e4 input=11af2d82d83c2e94]*/
{
sigset_t set;
int err, signum;
if (iterable_to_sigset(sigset, &set))
return NULL;
Py_BEGIN_ALLOW_THREADS
err = sigwait(&set, &signum);
Py_END_ALLOW_THREADS
if (err) {
errno = err;
return PyErr_SetFromErrno(PyExc_OSError);
}
return PyLong_FromLong(signum);
}
#endif /* #ifdef HAVE_SIGWAIT */
#if defined(HAVE_SIGWAITINFO) || defined(HAVE_SIGTIMEDWAIT)
static int initialized;
static PyStructSequence_Field struct_siginfo_fields[] = {
{"si_signo", PyDoc_STR("signal number")},
{"si_code", PyDoc_STR("signal code")},
{"si_errno", PyDoc_STR("errno associated with this signal")},
{"si_pid", PyDoc_STR("sending process ID")},
{"si_uid", PyDoc_STR("real user ID of sending process")},
{"si_status", PyDoc_STR("exit value or signal")},
{"si_band", PyDoc_STR("band event for SIGPOLL")},
{0}
};
PyDoc_STRVAR(struct_siginfo__doc__,
"struct_siginfo: Result from sigwaitinfo or sigtimedwait.\n\n\
This object may be accessed either as a tuple of\n\
(si_signo, si_code, si_errno, si_pid, si_uid, si_status, si_band),\n\
or via the attributes si_signo, si_code, and so on.");
static PyStructSequence_Desc struct_siginfo_desc = {
"signal.struct_siginfo", /* name */
struct_siginfo__doc__, /* doc */
struct_siginfo_fields, /* fields */
7 /* n_in_sequence */
};
static PyTypeObject SiginfoType;
static PyObject *
fill_siginfo(siginfo_t *si)
{
PyObject *result = PyStructSequence_New(&SiginfoType);
if (!result)
return NULL;
PyStructSequence_SET_ITEM(result, 0, PyLong_FromLong((long)(si->si_signo)));
PyStructSequence_SET_ITEM(result, 1, PyLong_FromLong((long)(si->si_code)));
PyStructSequence_SET_ITEM(result, 2, PyLong_FromLong((long)(si->si_errno)));
PyStructSequence_SET_ITEM(result, 3, PyLong_FromPid(si->si_pid));
PyStructSequence_SET_ITEM(result, 4, _PyLong_FromUid(si->si_uid));
PyStructSequence_SET_ITEM(result, 5,
PyLong_FromLong((long)(si->si_status)));
PyStructSequence_SET_ITEM(result, 6, PyLong_FromLong(si->si_band));
if (PyErr_Occurred()) {
Py_DECREF(result);
return NULL;
}
return result;
}
#endif
#ifdef HAVE_SIGWAITINFO
/*[clinic input]
signal.sigwaitinfo
sigset: object
/
Wait synchronously until one of the signals in *sigset* is delivered.
Returns a struct_siginfo containing information about the signal.
[clinic start generated code]*/
static PyObject *
signal_sigwaitinfo(PyObject *module, PyObject *sigset)
/*[clinic end generated code: output=c40f27b269cd2309 input=f3779a74a991e171]*/
{
sigset_t set;
siginfo_t si;
int err;
int async_err = 0;
if (iterable_to_sigset(sigset, &set))
return NULL;
do {
Py_BEGIN_ALLOW_THREADS
err = sigwaitinfo(&set, &si);
Py_END_ALLOW_THREADS
} while (err == -1
&& errno == EINTR && !(async_err = PyErr_CheckSignals()));
if (err == -1)
return (!async_err) ? PyErr_SetFromErrno(PyExc_OSError) : NULL;
return fill_siginfo(&si);
}
#endif /* #ifdef HAVE_SIGWAITINFO */
#ifdef HAVE_SIGTIMEDWAIT
/*[clinic input]
signal.sigtimedwait
sigset: object
timeout as timeout_obj: object
/
Like sigwaitinfo(), but with a timeout.
The timeout is specified in seconds, with floating point numbers allowed.
[clinic start generated code]*/
static PyObject *
signal_sigtimedwait_impl(PyObject *module, PyObject *sigset,
PyObject *timeout_obj)
/*[clinic end generated code: output=f7eff31e679f4312 input=53fd4ea3e3724eb8]*/
{
struct timespec ts;
sigset_t set;
siginfo_t si;
int res;
_PyTime_t timeout, deadline, monotonic;
if (_PyTime_FromSecondsObject(&timeout,
timeout_obj, _PyTime_ROUND_CEILING) < 0)
return NULL;
if (timeout < 0) {
PyErr_SetString(PyExc_ValueError, "timeout must be non-negative");
return NULL;
}
if (iterable_to_sigset(sigset, &set))
return NULL;
deadline = _PyTime_GetMonotonicClock() + timeout;
do {
if (_PyTime_AsTimespec(timeout, &ts) < 0)
return NULL;
Py_BEGIN_ALLOW_THREADS
res = sigtimedwait(&set, &si, &ts);
Py_END_ALLOW_THREADS
if (res != -1)
break;
if (errno != EINTR) {
if (errno == EAGAIN)
Py_RETURN_NONE;
else
return PyErr_SetFromErrno(PyExc_OSError);
}
/* sigtimedwait() was interrupted by a signal (EINTR) */
if (PyErr_CheckSignals())
return NULL;
monotonic = _PyTime_GetMonotonicClock();
timeout = deadline - monotonic;
if (timeout < 0)
break;
} while (1);
return fill_siginfo(&si);
}
#endif /* #ifdef HAVE_SIGTIMEDWAIT */
#if defined(HAVE_PTHREAD_KILL) && defined(WITH_THREAD)
/*[clinic input]
signal.pthread_kill
thread_id: long
signalnum: int
/
Send a signal to a thread.
[clinic start generated code]*/
static PyObject *
signal_pthread_kill_impl(PyObject *module, long thread_id, int signalnum)
/*[clinic end generated code: output=2a09ce41f1c4228a input=77ed6a3b6f2a8122]*/
{
int err;
err = pthread_kill((pthread_t)thread_id, signalnum);
if (err != 0) {
errno = err;
PyErr_SetFromErrno(PyExc_OSError);
return NULL;
}
/* the signal may have been send to the current thread */
if (PyErr_CheckSignals())
return NULL;
Py_RETURN_NONE;
}
#endif /* #if defined(HAVE_PTHREAD_KILL) && defined(WITH_THREAD) */
/* List of functions defined in the module -- some of the methoddefs are
defined to nothing if the corresponding C function is not available. */
static PyMethodDef signal_methods[] = {
{"default_int_handler", signal_default_int_handler, METH_VARARGS, default_int_handler_doc},
SIGNAL_ALARM_METHODDEF
SIGNAL_SETITIMER_METHODDEF
SIGNAL_GETITIMER_METHODDEF
SIGNAL_SIGNAL_METHODDEF
SIGNAL_GETSIGNAL_METHODDEF
{"set_wakeup_fd", signal_set_wakeup_fd, METH_VARARGS, set_wakeup_fd_doc},
SIGNAL_SIGINTERRUPT_METHODDEF
SIGNAL_PAUSE_METHODDEF
SIGNAL_PTHREAD_KILL_METHODDEF
SIGNAL_PTHREAD_SIGMASK_METHODDEF
SIGNAL_SIGPENDING_METHODDEF
SIGNAL_SIGWAIT_METHODDEF
SIGNAL_SIGWAITINFO_METHODDEF
SIGNAL_SIGTIMEDWAIT_METHODDEF
{NULL, NULL} /* sentinel */
};
PyDoc_STRVAR(module_doc,
"This module provides mechanisms to use signal handlers in Python.\n\
\n\
Functions:\n\
\n\
alarm() -- cause SIGALRM after a specified time [Unix only]\n\
setitimer() -- cause a signal (described below) after a specified\n\
float time and the timer may restart then [Unix only]\n\
getitimer() -- get current value of timer [Unix only]\n\
signal() -- set the action for a given signal\n\
getsignal() -- get the signal action for a given signal\n\
pause() -- wait until a signal arrives [Unix only]\n\
default_int_handler() -- default SIGINT handler\n\
\n\
signal constants:\n\
SIG_DFL -- used to refer to the system default handler\n\
SIG_IGN -- used to ignore the signal\n\
Py_NSIG -- number of defined signals\n\
SIGINT, SIGTERM, etc. -- signal numbers\n\
\n\
itimer constants:\n\
ITIMER_REAL -- decrements in real time, and delivers SIGALRM upon\n\
expiration\n\
ITIMER_VIRTUAL -- decrements only when the process is executing,\n\
and delivers SIGVTALRM upon expiration\n\
ITIMER_PROF -- decrements both when the process is executing and\n\
when the system is executing on behalf of the process.\n\
Coupled with ITIMER_VIRTUAL, this timer is usually\n\
used to profile the time spent by the application\n\
in user and kernel space. SIGPROF is delivered upon\n\
expiration.\n\
\n\n\
*** IMPORTANT NOTICE ***\n\
A signal handler function is called with two arguments:\n\
the first is the signal number, the second is the interrupted stack frame.");
static struct PyModuleDef signalmodule = {
PyModuleDef_HEAD_INIT,
"_signal",
module_doc,
-1,
signal_methods,
NULL,
NULL,
NULL,
NULL
};
PyMODINIT_FUNC
PyInit__signal(void)
{
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 = PyModule_Create(&signalmodule);
if (m == NULL)
return NULL;
#if defined(HAVE_SIGWAITINFO) || defined(HAVE_SIGTIMEDWAIT)
if (!initialized) {
if (PyStructSequence_InitType2(&SiginfoType, &struct_siginfo_desc) < 0)
return NULL;
}
Py_INCREF((PyObject*) &SiginfoType);
PyModule_AddObject(m, "struct_siginfo", (PyObject*) &SiginfoType);
initialized = 1;
#endif
/* 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 = PyLong_FromLong((long)Py_NSIG);
if (!x || PyDict_SetItemString(d, "NSIG", x) < 0)
goto finally;
Py_DECREF(x);
if (PyModule_AddIntMacro(m, SIG_BLOCK)) goto finally;
if (PyModule_AddIntMacro(m, SIG_UNBLOCK)) goto finally;
if (PyModule_AddIntMacro(m, SIG_SETMASK)) goto finally;
x = IntHandler = PyDict_GetItemString(d, "default_int_handler");
if (!x)
goto finally;
Py_INCREF(IntHandler);
_Py_atomic_store_relaxed(&Handlers[0].tripped, 0);
for (i = 1; i < Py_NSIG; i++) {
void (*t)(int);
t = PyOS_getsig(i);
_Py_atomic_store_relaxed(&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_SETREF(Handlers[SIGINT].func, IntHandler);
PyOS_setsig(SIGINT, signal_handler);
}
if (PyModule_AddIntMacro(m, SIGHUP)) goto finally;
if (PyModule_AddIntMacro(m, SIGINT)) goto finally;
if (PyModule_AddIntMacro(m, SIGQUIT)) goto finally;
if (PyModule_AddIntMacro(m, SIGILL)) goto finally;
if (PyModule_AddIntMacro(m, SIGTRAP)) goto finally;
if (PyModule_AddIntMacro(m, SIGIOT)) goto finally;
if (PyModule_AddIntMacro(m, SIGABRT)) goto finally;
if (PyModule_AddIntMacro(m, SIGFPE)) goto finally;
if (PyModule_AddIntMacro(m, SIGKILL)) goto finally;
if (PyModule_AddIntMacro(m, SIGBUS)) goto finally;
if (PyModule_AddIntMacro(m, SIGSEGV)) goto finally;
if (PyModule_AddIntMacro(m, SIGSYS)) goto finally;
if (PyModule_AddIntMacro(m, SIGPIPE)) goto finally;
if (PyModule_AddIntMacro(m, SIGALRM)) goto finally;
if (PyModule_AddIntMacro(m, SIGTERM)) goto finally;
if (PyModule_AddIntMacro(m, SIGUSR1)) goto finally;
if (PyModule_AddIntMacro(m, SIGUSR2)) goto finally;
if (PyModule_AddIntMacro(m, SIGCHLD)) goto finally;
if (PyModule_AddIntMacro(m, SIGPWR)) goto finally;
if (PyModule_AddIntMacro(m, SIGIO)) goto finally;
if (PyModule_AddIntMacro(m, SIGURG)) goto finally;
if (PyModule_AddIntMacro(m, SIGWINCH)) goto finally;
if (PyModule_AddIntMacro(m, SIGPOLL)) goto finally;
if (PyModule_AddIntMacro(m, SIGSTOP)) goto finally;
if (PyModule_AddIntMacro(m, SIGTSTP)) goto finally;
if (PyModule_AddIntMacro(m, SIGCONT)) goto finally;
if (PyModule_AddIntMacro(m, SIGTTIN)) goto finally;
if (PyModule_AddIntMacro(m, SIGTTOU)) goto finally;
if (PyModule_AddIntMacro(m, SIGVTALRM)) goto finally;
if (PyModule_AddIntMacro(m, SIGPROF)) goto finally;
if (PyModule_AddIntMacro(m, SIGXCPU)) goto finally;
if (PyModule_AddIntMacro(m, SIGXFSZ)) goto finally;
if (SIGEMT && PyModule_AddIntMacro(m, SIGEMT)) goto finally;
if (SIGINFO && PyModule_AddIntMacro(m, SIGINFO)) goto finally;
if (SIGRTMIN && PyModule_AddIntMacro(m, SIGRTMIN)) goto finally;
if (SIGRTMAX && PyModule_AddIntMacro(m, SIGRTMAX)) goto finally;
#if defined (HAVE_SETITIMER) || defined (HAVE_GETITIMER)
if (PyModule_AddIntMacro(m, ITIMER_REAL)) goto finally;
if (PyModule_AddIntMacro(m, ITIMER_VIRTUAL)) goto finally;
if (PyModule_AddIntMacro(m, ITIMER_PROF)) goto finally;
ItimerError = PyErr_NewException("signal.ItimerError",
PyExc_IOError, NULL);
if (ItimerError != NULL)
PyDict_SetItemString(d, "ItimerError", ItimerError);
#endif
#ifdef CTRL_C_EVENT
if (PyModule_AddIntMacro(m, CTRL_C_EVENT))
goto finally;
#endif
#ifdef CTRL_BREAK_EVENT
if (PyModule_AddIntMacro(m, CTRL_BREAK_EVENT))
goto finally;
#endif
#ifdef MS_WINDOWS
/* Create manual-reset event, initially unset */
sigint_event = CreateEvent(NULL, TRUE, FALSE, FALSE);
#endif
if (PyErr_Occurred()) {
Py_DECREF(m);
m = NULL;
}
finally:
return m;
}
static void
finisignal(void)
{
int i;
PyObject *func;
for (i = 1; i < Py_NSIG; i++) {
func = Handlers[i].func;
_Py_atomic_store_relaxed(&Handlers[i].tripped, 0);
Handlers[i].func = NULL;
if (func != NULL && func != Py_None &&
func != DefaultHandler && func != IgnoreHandler)
PyOS_setsig(i, SIG_DFL);
Py_XDECREF(func);
}
Py_CLEAR(IntHandler);
Py_CLEAR(DefaultHandler);
Py_CLEAR(IgnoreHandler);
}
/* Declared in pyerrors.h */
int
PyErr_CheckSignals(void)
{
int i;
PyObject *f;
if (!_Py_atomic_load(&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.
*/
_Py_atomic_store(&is_tripped, 0);
if (!(f = (PyObject *)PyEval_GetFrame()))
f = Py_None;
for (i = 1; i < Py_NSIG; i++) {
if (_Py_atomic_load_relaxed(&Handlers[i].tripped)) {
PyObject *result = NULL;
PyObject *arglist = Py_BuildValue("(iO)", i, f);
_Py_atomic_store_relaxed(&Handlers[i].tripped, 0);
if (arglist) {
result = PyEval_CallObject(Handlers[i].func,
arglist);
Py_DECREF(arglist);
}
if (!result) {
_Py_atomic_store(&is_tripped, 1);
return -1;
}
Py_DECREF(result);
}
}
return 0;
}
/* Replacements for intrcheck.c functionality
* Declared in pyerrors.h
*/
void
PyErr_SetInterrupt(void)
{
trip_signal(SIGINT);
}
void
PyOS_InitInterrupts(void)
{
PyObject *m = PyImport_ImportModule("_signal");
if (m) {
Py_DECREF(m);
}
}
void
PyOS_FiniInterrupts(void)
{
finisignal();
}
int
PyOS_InterruptOccurred(void)
{
if (_Py_atomic_load_relaxed(&Handlers[SIGINT].tripped)) {
#ifdef WITH_THREAD
if (PyThread_get_thread_ident() != main_thread)
return 0;
#endif
_Py_atomic_store_relaxed(&Handlers[SIGINT].tripped, 0);
return 1;
}
return 0;
}
static void
_clear_pending_signals(void)
{
int i;
if (!_Py_atomic_load(&is_tripped))
return;
_Py_atomic_store(&is_tripped, 0);
for (i = 1; i < Py_NSIG; ++i) {
_Py_atomic_store_relaxed(&Handlers[i].tripped, 0);
}
}
void
PyOS_AfterFork(void)
{
/* Clear the signal flags after forking so that they aren't handled
* in both processes if they came in just before the fork() but before
* the interpreter had an opportunity to call the handlers. issue9535. */
_clear_pending_signals();
#ifdef WITH_THREAD
/* PyThread_ReInitTLS() must be called early, to make sure that the TLS API
* can be called safely. */
PyThread_ReInitTLS();
_PyGILState_Reinit();
PyEval_ReInitThreads();
main_thread = PyThread_get_thread_ident();
main_pid = getpid();
_PyImport_ReInitLock();
#endif
}
int
_PyOS_IsMainThread(void)
{
#ifdef WITH_THREAD
return PyThread_get_thread_ident() == main_thread;
#else
return 1;
#endif
}
#ifdef MS_WINDOWS
void *_PyOS_SigintEvent(void)
{
/* Returns a manual-reset event which gets tripped whenever
SIGINT is received.
Python.h does not include windows.h so we do cannot use HANDLE
as the return type of this function. We use void* instead. */
return sigint_event;
}
#endif
_Section(".rodata.pytab.1") const struct _inittab _PyImport_Inittab__signal = {
"_signal",
PyInit__signal,
};
| 44,226 | 1,576 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Modules/unicodedata_eastasianwidthnames.c | #include "libc/nexgen32e/kompressor.h"
#include "third_party/python/Modules/unicodedata.h"
/* clang-format off */
/* GENERATED BY third_party/python/Tools/unicode/makeunicodedata.py 3.2 */
const char _PyUnicode_EastAsianWidthNames[6][3] = {
"F",
"H",
"W",
"Na",
"A",
"N",
};
| 300 | 14 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Modules/testcapi_long.inc | /*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:8;coding:utf-8 -*-â
âvi: set net ft=c ts=4 sts=4 sw=4 fenc=utf-8 :viâ
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ¡
â Python 3 â
â https://docs.python.org/3/license.html â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
/* clang-format off */
/* 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*
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 : 0U - 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);
}
/* Test F_PY_TO_{S,U} on non-pylong input. This should raise a TypeError. */
{
TYPENAME out;
unsigned TYPENAME uout;
Py_INCREF(Py_None);
out = F_PY_TO_S(Py_None);
if (out != (TYPENAME)-1 || !PyErr_Occurred())
return error("PyLong_AsXXX(None) didn't complain");
if (!PyErr_ExceptionMatches(PyExc_TypeError))
return error("PyLong_AsXXX(None) raised "
"something other than TypeError");
PyErr_Clear();
uout = F_PY_TO_U(Py_None);
if (uout != (unsigned TYPENAME)-1 || !PyErr_Occurred())
return error("PyLong_AsXXX(None) didn't complain");
if (!PyErr_ExceptionMatches(PyExc_TypeError))
return error("PyLong_AsXXX(None) raised "
"something other than TypeError");
PyErr_Clear();
Py_DECREF(Py_None);
}
Py_INCREF(Py_None);
return Py_None;
}
| 7,773 | 216 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Modules/winreparse.h | #ifndef COSMOPOLITAN_THIRD_PARTY_PYTHON_MODULES_WINREPARSE_H_
#define COSMOPOLITAN_THIRD_PARTY_PYTHON_MODULES_WINREPARSE_H_
#include "libc/nt/struct/reparsedatabuffer.h"
#if !(__ASSEMBLER__ + __LINKER__ + 0)
#define _Py_REPARSE_DATA_BUFFER struct NtReparseDataBuffer
#define _Py_PREPARSE_DATA_BUFFER struct NtReparseDataBuffer*
#define _Py_REPARSE_DATA_BUFFER_HEADER_SIZE \
offsetof(_Py_REPARSE_DATA_BUFFER, GenericReparseBuffer)
#define _Py_MAXIMUM_REPARSE_DATA_BUFFER_SIZE (16 * 1024)
#endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */
#endif /* COSMOPOLITAN_THIRD_PARTY_PYTHON_MODULES_WINREPARSE_H_ */
| 607 | 15 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Modules/_gdbmmodule.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:8;coding:utf-8 -*-â
âvi: set net ft=c ts=4 sts=4 sw=4 fenc=utf-8 :viâ
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ¡
â Python 3 â
â https://docs.python.org/3/license.html â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
#include "third_party/python/Include/yoink.h"
/* clang-format off */
PYTHON_PROVIDE("_gdbm");
/* DBM module using dictionary interface */
/* Author: Anthony Baxter, after dbmmodule.c */
/* Doc strings: Mitch Chapman */
#include "gdbm.h"
#if defined(WIN32) && !defined(__CYGWIN__)
#include "third_party/python/Include/gdbmerrno.h"
extern const char * gdbm_strerror(gdbm_error);
#endif
/*[clinic input]
module _gdbm
class _gdbm.gdbm "dbmobject *" "&Dbmtype"
[clinic start generated code]*/
/*[clinic end generated code: output=da39a3ee5e6b4b0d input=113927c6170729b2]*/
PyDoc_STRVAR(gdbmmodule__doc__,
"This module provides an interface to the GNU DBM (GDBM) library.\n\
\n\
This module is quite similar to the dbm module, but uses GDBM instead to\n\
provide some additional functionality. Please note that the file formats\n\
created by GDBM and dbm are incompatible.\n\
\n\
GDBM objects behave like mappings (dictionaries), except that keys and\n\
values are always immutable bytes-like objects or strings. Printing\n\
a GDBM object doesn't print the keys and values, and the items() and\n\
values() methods are not supported.");
typedef struct {
PyObject_HEAD
int di_size; /* -1 means recompute */
GDBM_FILE di_dbm;
} dbmobject;
static PyTypeObject Dbmtype;
#include "third_party/python/Modules/clinic/_gdbmmodule.inc"
#define is_dbmobject(v) (Py_TYPE(v) == &Dbmtype)
#define check_dbmobject_open(v) if ((v)->di_dbm == NULL) \
{ PyErr_SetString(DbmError, "GDBM object has already been closed"); \
return NULL; }
static PyObject *DbmError;
PyDoc_STRVAR(gdbm_object__doc__,
"This object represents a GDBM database.\n\
GDBM objects behave like mappings (dictionaries), except that keys and\n\
values are always immutable bytes-like objects or strings. Printing\n\
a GDBM object doesn't print the keys and values, and the items() and\n\
values() methods are not supported.\n\
\n\
GDBM objects also support additional operations such as firstkey,\n\
nextkey, reorganize, and sync.");
static PyObject *
newdbmobject(const char *file, int flags, int mode)
{
dbmobject *dp;
dp = PyObject_New(dbmobject, &Dbmtype);
if (dp == NULL)
return NULL;
dp->di_size = -1;
errno = 0;
if ((dp->di_dbm = gdbm_open((char *)file, 0, flags, mode, NULL)) == 0) {
if (errno != 0)
PyErr_SetFromErrno(DbmError);
else
PyErr_SetString(DbmError, gdbm_strerror(gdbm_errno));
Py_DECREF(dp);
return NULL;
}
return (PyObject *)dp;
}
/* Methods */
static void
dbm_dealloc(dbmobject *dp)
{
if (dp->di_dbm)
gdbm_close(dp->di_dbm);
PyObject_Del(dp);
}
static Py_ssize_t
dbm_length(dbmobject *dp)
{
if (dp->di_dbm == NULL) {
PyErr_SetString(DbmError, "GDBM object has already been closed");
return -1;
}
if (dp->di_size < 0) {
datum key,okey;
int size;
okey.dsize=0;
okey.dptr=NULL;
size = 0;
for (key=gdbm_firstkey(dp->di_dbm); key.dptr;
key = gdbm_nextkey(dp->di_dbm,okey)) {
size++;
if(okey.dsize) free(okey.dptr);
okey=key;
}
dp->di_size = size;
}
return dp->di_size;
}
static PyObject *
dbm_subscript(dbmobject *dp, PyObject *key)
{
PyObject *v;
datum drec, krec;
if (!PyArg_Parse(key, "s#", &krec.dptr, &krec.dsize) )
return NULL;
if (dp->di_dbm == NULL) {
PyErr_SetString(DbmError,
"GDBM object has already been closed");
return NULL;
}
drec = gdbm_fetch(dp->di_dbm, krec);
if (drec.dptr == 0) {
PyErr_SetObject(PyExc_KeyError, key);
return NULL;
}
v = PyBytes_FromStringAndSize(drec.dptr, drec.dsize);
free(drec.dptr);
return v;
}
/*[clinic input]
_gdbm.gdbm.get
key: object
default: object = None
/
Get the value for key, or default if not present.
[clinic start generated code]*/
static PyObject *
_gdbm_gdbm_get_impl(dbmobject *self, PyObject *key, PyObject *default_value)
/*[clinic end generated code: output=19b7c585ad4f554a input=a9c20423f34c17b6]*/
{
PyObject *res;
res = dbm_subscript(self, key);
if (res == NULL && PyErr_ExceptionMatches(PyExc_KeyError)) {
PyErr_Clear();
Py_INCREF(default_value);
return default_value;
}
return res;
}
static int
dbm_ass_sub(dbmobject *dp, PyObject *v, PyObject *w)
{
datum krec, drec;
if (!PyArg_Parse(v, "s#", &krec.dptr, &krec.dsize) ) {
PyErr_SetString(PyExc_TypeError,
"gdbm mappings have bytes or string indices only");
return -1;
}
if (dp->di_dbm == NULL) {
PyErr_SetString(DbmError,
"GDBM object has already been closed");
return -1;
}
dp->di_size = -1;
if (w == NULL) {
if (gdbm_delete(dp->di_dbm, krec) < 0) {
PyErr_SetObject(PyExc_KeyError, v);
return -1;
}
}
else {
if (!PyArg_Parse(w, "s#", &drec.dptr, &drec.dsize)) {
PyErr_SetString(PyExc_TypeError,
"gdbm mappings have byte or string elements only");
return -1;
}
errno = 0;
if (gdbm_store(dp->di_dbm, krec, drec, GDBM_REPLACE) < 0) {
if (errno != 0)
PyErr_SetFromErrno(DbmError);
else
PyErr_SetString(DbmError,
gdbm_strerror(gdbm_errno));
return -1;
}
}
return 0;
}
/*[clinic input]
_gdbm.gdbm.setdefault
key: object
default: object = None
/
Get value for key, or set it to default and return default if not present.
[clinic start generated code]*/
static PyObject *
_gdbm_gdbm_setdefault_impl(dbmobject *self, PyObject *key,
PyObject *default_value)
/*[clinic end generated code: output=88760ee520329012 input=0db46b69e9680171]*/
{
PyObject *res;
res = dbm_subscript(self, key);
if (res == NULL && PyErr_ExceptionMatches(PyExc_KeyError)) {
PyErr_Clear();
if (dbm_ass_sub(self, key, default_value) < 0)
return NULL;
return dbm_subscript(self, key);
}
return res;
}
static PyMappingMethods dbm_as_mapping = {
(lenfunc)dbm_length, /*mp_length*/
(binaryfunc)dbm_subscript, /*mp_subscript*/
(objobjargproc)dbm_ass_sub, /*mp_ass_subscript*/
};
/*[clinic input]
_gdbm.gdbm.close
Close the database.
[clinic start generated code]*/
static PyObject *
_gdbm_gdbm_close_impl(dbmobject *self)
/*[clinic end generated code: output=23512a594598b563 input=0a203447379b45fd]*/
{
if (self->di_dbm)
gdbm_close(self->di_dbm);
self->di_dbm = NULL;
Py_INCREF(Py_None);
return Py_None;
}
/* XXX Should return a set or a set view */
/*[clinic input]
_gdbm.gdbm.keys
Get a list of all keys in the database.
[clinic start generated code]*/
static PyObject *
_gdbm_gdbm_keys_impl(dbmobject *self)
/*[clinic end generated code: output=cb4b1776c3645dcc input=1832ee0a3132cfaf]*/
{
PyObject *v, *item;
datum key, nextkey;
int err;
if (self == NULL || !is_dbmobject(self)) {
PyErr_BadInternalCall();
return NULL;
}
check_dbmobject_open(self);
v = PyList_New(0);
if (v == NULL)
return NULL;
key = gdbm_firstkey(self->di_dbm);
while (key.dptr) {
item = PyBytes_FromStringAndSize(key.dptr, key.dsize);
if (item == NULL) {
free(key.dptr);
Py_DECREF(v);
return NULL;
}
err = PyList_Append(v, item);
Py_DECREF(item);
if (err != 0) {
free(key.dptr);
Py_DECREF(v);
return NULL;
}
nextkey = gdbm_nextkey(self->di_dbm, key);
free(key.dptr);
key = nextkey;
}
return v;
}
static int
dbm_contains(PyObject *self, PyObject *arg)
{
dbmobject *dp = (dbmobject *)self;
datum key;
Py_ssize_t size;
if ((dp)->di_dbm == NULL) {
PyErr_SetString(DbmError,
"GDBM object has already been closed");
return -1;
}
if (PyUnicode_Check(arg)) {
key.dptr = PyUnicode_AsUTF8AndSize(arg, &size);
key.dsize = size;
if (key.dptr == NULL)
return -1;
}
else if (!PyBytes_Check(arg)) {
PyErr_Format(PyExc_TypeError,
"gdbm key must be bytes or string, not %.100s",
arg->ob_type->tp_name);
return -1;
}
else {
key.dptr = PyBytes_AS_STRING(arg);
key.dsize = PyBytes_GET_SIZE(arg);
}
return gdbm_exists(dp->di_dbm, key);
}
static PySequenceMethods dbm_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 */
dbm_contains, /* sq_contains */
0, /* sq_inplace_concat */
0, /* sq_inplace_repeat */
};
/*[clinic input]
_gdbm.gdbm.firstkey
Return the starting key for the traversal.
It's possible to loop over every key in the database using this method
and the nextkey() method. The traversal is ordered by GDBM's internal
hash values, and won't be sorted by the key values.
[clinic start generated code]*/
static PyObject *
_gdbm_gdbm_firstkey_impl(dbmobject *self)
/*[clinic end generated code: output=9ff85628d84b65d2 input=0dbd6a335d69bba0]*/
{
PyObject *v;
datum key;
check_dbmobject_open(self);
key = gdbm_firstkey(self->di_dbm);
if (key.dptr) {
v = PyBytes_FromStringAndSize(key.dptr, key.dsize);
free(key.dptr);
return v;
}
else {
Py_INCREF(Py_None);
return Py_None;
}
}
/*[clinic input]
_gdbm.gdbm.nextkey
key: str(accept={str, robuffer}, zeroes=True)
/
Returns the key that follows key in the traversal.
The following code prints every key in the database db, without having
to create a list in memory that contains them all:
k = db.firstkey()
while k != None:
print(k)
k = db.nextkey(k)
[clinic start generated code]*/
static PyObject *
_gdbm_gdbm_nextkey_impl(dbmobject *self, const char *key,
Py_ssize_clean_t key_length)
/*[clinic end generated code: output=192ab892de6eb2f6 input=1f1606943614e36f]*/
{
PyObject *v;
datum dbm_key, nextkey;
dbm_key.dptr = (char *)key;
dbm_key.dsize = key_length;
check_dbmobject_open(self);
nextkey = gdbm_nextkey(self->di_dbm, dbm_key);
if (nextkey.dptr) {
v = PyBytes_FromStringAndSize(nextkey.dptr, nextkey.dsize);
free(nextkey.dptr);
return v;
}
else {
Py_INCREF(Py_None);
return Py_None;
}
}
/*[clinic input]
_gdbm.gdbm.reorganize
Reorganize the database.
If you have carried out a lot of deletions and would like to shrink
the space used by the GDBM file, this routine will reorganize the
database. GDBM will not shorten the length of a database file except
by using this reorganization; otherwise, deleted file space will be
kept and reused as new (key,value) pairs are added.
[clinic start generated code]*/
static PyObject *
_gdbm_gdbm_reorganize_impl(dbmobject *self)
/*[clinic end generated code: output=38d9624df92e961d input=f6bea85bcfd40dd2]*/
{
check_dbmobject_open(self);
errno = 0;
if (gdbm_reorganize(self->di_dbm) < 0) {
if (errno != 0)
PyErr_SetFromErrno(DbmError);
else
PyErr_SetString(DbmError, gdbm_strerror(gdbm_errno));
return NULL;
}
Py_INCREF(Py_None);
return Py_None;
}
/*[clinic input]
_gdbm.gdbm.sync
Flush the database to the disk file.
When the database has been opened in fast mode, this method forces
any unwritten data to be written to the disk.
[clinic start generated code]*/
static PyObject *
_gdbm_gdbm_sync_impl(dbmobject *self)
/*[clinic end generated code: output=488b15f47028f125 input=2a47d2c9e153ab8a]*/
{
check_dbmobject_open(self);
gdbm_sync(self->di_dbm);
Py_INCREF(Py_None);
return Py_None;
}
static PyObject *
dbm__enter__(PyObject *self, PyObject *args)
{
Py_INCREF(self);
return self;
}
static PyObject *
dbm__exit__(PyObject *self, PyObject *args)
{
_Py_IDENTIFIER(close);
return _PyObject_CallMethodId(self, &PyId_close, NULL);
}
static PyMethodDef dbm_methods[] = {
_GDBM_GDBM_CLOSE_METHODDEF
_GDBM_GDBM_KEYS_METHODDEF
_GDBM_GDBM_FIRSTKEY_METHODDEF
_GDBM_GDBM_NEXTKEY_METHODDEF
_GDBM_GDBM_REORGANIZE_METHODDEF
_GDBM_GDBM_SYNC_METHODDEF
_GDBM_GDBM_GET_METHODDEF
_GDBM_GDBM_GET_METHODDEF
_GDBM_GDBM_SETDEFAULT_METHODDEF
{"__enter__", dbm__enter__, METH_NOARGS, NULL},
{"__exit__", dbm__exit__, METH_VARARGS, NULL},
{NULL, NULL} /* sentinel */
};
static PyTypeObject Dbmtype = {
PyVarObject_HEAD_INIT(0, 0)
"_gdbm.gdbm",
sizeof(dbmobject),
0,
(destructor)dbm_dealloc, /*tp_dealloc*/
0, /*tp_print*/
0, /*tp_getattr*/
0, /*tp_setattr*/
0, /*tp_reserved*/
0, /*tp_repr*/
0, /*tp_as_number*/
&dbm_as_sequence, /*tp_as_sequence*/
&dbm_as_mapping, /*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_xxx4*/
gdbm_object__doc__, /*tp_doc*/
0, /*tp_traverse*/
0, /*tp_clear*/
0, /*tp_richcompare*/
0, /*tp_weaklistoffset*/
0, /*tp_iter*/
0, /*tp_iternext*/
dbm_methods, /*tp_methods*/
};
/* ----------------------------------------------------------------- */
/*[clinic input]
_gdbm.open as dbmopen
filename: unicode
flags: str="r"
mode: int(py_default="0o666") = 0o666
/
Open a dbm database and return a dbm object.
The filename argument is the name of the database file.
The optional flags argument can be 'r' (to open an existing database
for reading only -- default), 'w' (to open an existing database for
reading and writing), 'c' (which creates the database if it doesn't
exist), or 'n' (which always creates a new empty database).
Some versions of gdbm support additional flags which must be
appended to one of the flags described above. The module constant
'open_flags' is a string of valid additional flags. The 'f' flag
opens the database in fast mode; altered data will not automatically
be written to the disk after every change. This results in faster
writes to the database, but may result in an inconsistent database
if the program crashes while the database is still open. Use the
sync() method to force any unwritten data to be written to the disk.
The 's' flag causes all database operations to be synchronized to
disk. The 'u' flag disables locking of the database file.
The optional mode argument is the Unix mode of the file, used only
when the database has to be created. It defaults to octal 0o666.
[clinic start generated code]*/
static PyObject *
dbmopen_impl(PyObject *module, PyObject *filename, const char *flags,
int mode)
/*[clinic end generated code: output=9527750f5df90764 input=3be0b0875974b928]*/
{
int iflags;
switch (flags[0]) {
case 'r':
iflags = GDBM_READER;
break;
case 'w':
iflags = GDBM_WRITER;
break;
case 'c':
iflags = GDBM_WRCREAT;
break;
case 'n':
iflags = GDBM_NEWDB;
break;
default:
PyErr_SetString(DbmError,
"First flag must be one of 'r', 'w', 'c' or 'n'");
return NULL;
}
for (flags++; *flags != '\0'; flags++) {
char buf[40];
switch (*flags) {
#ifdef GDBM_FAST
case 'f':
iflags |= GDBM_FAST;
break;
#endif
#ifdef GDBM_SYNC
case 's':
iflags |= GDBM_SYNC;
break;
#endif
#ifdef GDBM_NOLOCK
case 'u':
iflags |= GDBM_NOLOCK;
break;
#endif
default:
PyOS_snprintf(buf, sizeof(buf), "Flag '%c' is not supported.",
*flags);
PyErr_SetString(DbmError, buf);
return NULL;
}
}
PyObject *filenamebytes = PyUnicode_EncodeFSDefault(filename);
if (filenamebytes == NULL) {
return NULL;
}
const char *name = PyBytes_AS_STRING(filenamebytes);
if (strlen(name) != (size_t)PyBytes_GET_SIZE(filenamebytes)) {
Py_DECREF(filenamebytes);
PyErr_SetString(PyExc_ValueError, "embedded null character");
return NULL;
}
PyObject *self = newdbmobject(name, iflags, mode);
Py_DECREF(filenamebytes);
return self;
}
static const char dbmmodule_open_flags[] = "rwcn"
#ifdef GDBM_FAST
"f"
#endif
#ifdef GDBM_SYNC
"s"
#endif
#ifdef GDBM_NOLOCK
"u"
#endif
;
static PyMethodDef dbmmodule_methods[] = {
DBMOPEN_METHODDEF
{ 0, 0 },
};
static struct PyModuleDef _gdbmmodule = {
PyModuleDef_HEAD_INIT,
"_gdbm",
gdbmmodule__doc__,
-1,
dbmmodule_methods,
NULL,
NULL,
NULL,
NULL
};
PyMODINIT_FUNC
PyInit__gdbm(void) {
PyObject *m, *d, *s;
if (PyType_Ready(&Dbmtype) < 0)
return NULL;
m = PyModule_Create(&_gdbmmodule);
if (m == NULL)
return NULL;
d = PyModule_GetDict(m);
DbmError = PyErr_NewException("_gdbm.error", PyExc_IOError, NULL);
if (DbmError != NULL) {
PyDict_SetItemString(d, "error", DbmError);
s = PyUnicode_FromString(dbmmodule_open_flags);
PyDict_SetItemString(d, "open_flags", s);
Py_DECREF(s);
}
return m;
}
| 19,706 | 683 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Modules/mathmodule.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:8;coding:utf-8 -*-â
âvi: set net ft=c ts=4 sts=4 sw=4 fenc=utf-8 :viâ
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ¡
â Python 3 â
â https://docs.python.org/3/license.html â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
#include "libc/assert.h"
#include "libc/errno.h"
#include "libc/math.h"
#include "third_party/python/Include/abstract.h"
#include "third_party/python/Include/boolobject.h"
#include "third_party/python/Include/dtoa.h"
#include "third_party/python/Include/floatobject.h"
#include "third_party/python/Include/import.h"
#include "third_party/python/Include/longobject.h"
#include "third_party/python/Include/modsupport.h"
#include "third_party/python/Include/pyerrors.h"
#include "third_party/python/Include/pyfpe.h"
#include "third_party/python/Include/pymacro.h"
#include "third_party/python/Include/pymath.h"
#include "third_party/python/Include/pymem.h"
#include "third_party/python/Include/pyport.h"
#include "third_party/python/Include/yoink.h"
#include "third_party/python/Modules/_math.h"
#include "third_party/python/pyconfig.h"
/* clang-format off */
PYTHON_PROVIDE("math");
PYTHON_PROVIDE("math.acos");
PYTHON_PROVIDE("math.acosh");
PYTHON_PROVIDE("math.asin");
PYTHON_PROVIDE("math.asinh");
PYTHON_PROVIDE("math.atan");
PYTHON_PROVIDE("math.atan2");
PYTHON_PROVIDE("math.atanh");
PYTHON_PROVIDE("math.ceil");
PYTHON_PROVIDE("math.copysign");
PYTHON_PROVIDE("math.cos");
PYTHON_PROVIDE("math.cosh");
PYTHON_PROVIDE("math.degrees");
PYTHON_PROVIDE("math.e");
PYTHON_PROVIDE("math.erf");
PYTHON_PROVIDE("math.erfc");
PYTHON_PROVIDE("math.exp");
PYTHON_PROVIDE("math.expm1");
PYTHON_PROVIDE("math.fabs");
PYTHON_PROVIDE("math.factorial");
PYTHON_PROVIDE("math.floor");
PYTHON_PROVIDE("math.fmod");
PYTHON_PROVIDE("math.frexp");
PYTHON_PROVIDE("math.fsum");
PYTHON_PROVIDE("math.gamma");
PYTHON_PROVIDE("math.gcd");
PYTHON_PROVIDE("math.hypot");
PYTHON_PROVIDE("math.inf");
PYTHON_PROVIDE("math.isclose");
PYTHON_PROVIDE("math.isfinite");
PYTHON_PROVIDE("math.isinf");
PYTHON_PROVIDE("math.isnan");
PYTHON_PROVIDE("math.ldexp");
PYTHON_PROVIDE("math.lgamma");
PYTHON_PROVIDE("math.log");
PYTHON_PROVIDE("math.log10");
PYTHON_PROVIDE("math.log1p");
PYTHON_PROVIDE("math.log2");
PYTHON_PROVIDE("math.modf");
PYTHON_PROVIDE("math.nan");
PYTHON_PROVIDE("math.pi");
PYTHON_PROVIDE("math.pow");
PYTHON_PROVIDE("math.radians");
PYTHON_PROVIDE("math.sin");
PYTHON_PROVIDE("math.sinh");
PYTHON_PROVIDE("math.sqrt");
PYTHON_PROVIDE("math.tan");
PYTHON_PROVIDE("math.tanh");
PYTHON_PROVIDE("math.tau");
PYTHON_PROVIDE("math.trunc");
/* Math module -- standard C math library functions, pi and e */
/* Here are some comments from Tim Peters, extracted from the
discussion attached to http://bugs.python.org/issue1640. They
describe the general aims of the math module with respect to
special values, IEEE-754 floating-point exceptions, and Python
exceptions.
These are the "spirit of 754" rules:
1. If the mathematical result is a real number, but of magnitude too
large to approximate by a machine float, overflow is signaled and the
result is an infinity (with the appropriate sign).
2. If the mathematical result is a real number, but of magnitude too
small to approximate by a machine float, underflow is signaled and the
result is a zero (with the appropriate sign).
3. At a singularity (a value x such that the limit of f(y) as y
approaches x exists and is an infinity), "divide by zero" is signaled
and the result is an infinity (with the appropriate sign). This is
complicated a little by that the left-side and right-side limits may
not be the same; e.g., 1/x approaches +inf or -inf as x approaches 0
from the positive or negative directions. In that specific case, the
sign of the zero determines the result of 1/0.
4. At a point where a function has no defined result in the extended
reals (i.e., the reals plus an infinity or two), invalid operation is
signaled and a NaN is returned.
And these are what Python has historically /tried/ to do (but not
always successfully, as platform libm behavior varies a lot):
For #1, raise OverflowError.
For #2, return a zero (with the appropriate sign if that happens by
accident ;-)).
For #3 and #4, raise ValueError. It may have made sense to raise
Python's ZeroDivisionError in #3, but historically that's only been
raised for division by zero and mod by zero.
*/
/*
In general, on an IEEE-754 platform the aim is to follow the C99
standard, including Annex 'F', whenever possible. Where the
standard recommends raising the 'divide-by-zero' or 'invalid'
floating-point exceptions, Python should raise a ValueError. Where
the standard recommends raising 'overflow', Python should raise an
OverflowError. In all other circumstances a value should be
returned.
*/
/*
sin(pi*x), giving accurate results for all finite x (especially x
integral or close to an integer). This is here for use in the
reflection formula for the gamma function. It conforms to IEEE
754-2008 for finite arguments, but not for infinities or nans.
*/
static const double pi = 3.141592653589793238462643383279502884197;
static const double sqrtpi = 1.772453850905516027298167483341145182798;
static const double logpi = 1.144729885849400174143427351353058711647;
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;
}
/* Implementation of the real gamma function. In extensive but non-exhaustive
random tests, this function proved accurate to within <= 10 ulps across the
entire float domain. Note that accuracy may depend on the quality of the
system math functions, the pow function in particular. Special cases
follow C99 annex F. The parameters and method are tailored to platforms
whose double format is the IEEE 754 binary64 format.
Method: for x > 0.0 we use the Lanczos approximation with parameters N=13
and g=6.024680040776729583740234375; these parameters are amongst those
used by the Boost library. Following Boost (again), we re-express the
Lanczos sum as a rational function, and compute it that way. The
coefficients below were computed independently using MPFR, and have been
double-checked against the coefficients in the Boost source code.
For x < 0.0 we use the reflection formula.
There's one minor tweak that deserves explanation: Lanczos' formula for
Gamma(x) involves computing pow(x+g-0.5, x-0.5) / exp(x+g-0.5). For many x
values, x+g-0.5 can be represented exactly. However, in cases where it
can't be represented exactly the small error in x+g-0.5 can be magnified
significantly by the pow and exp calls, especially for large x. A cheap
correction is to multiply by (1 + e*g/(x+g-0.5)), where e is the error
involved in the computation of x+g-0.5 (that is, e = computed value of
x+g-0.5 - exact value of x+g-0.5). Here's the proof:
Correction factor
-----------------
Write x+g-0.5 = y-e, where y is exactly representable as an IEEE 754
double, and e is tiny. Then:
pow(x+g-0.5,x-0.5)/exp(x+g-0.5) = pow(y-e, x-0.5)/exp(y-e)
= pow(y, x-0.5)/exp(y) * C,
where the correction_factor C is given by
C = pow(1-e/y, x-0.5) * exp(e)
Since e is tiny, pow(1-e/y, x-0.5) ~ 1-(x-0.5)*e/y, and exp(x) ~ 1+e, so:
C ~ (1-(x-0.5)*e/y) * (1+e) ~ 1 + e*(y-(x-0.5))/y
But y-(x-0.5) = g+e, and g+e ~ g. So we get C ~ 1 + e*g/y, and
pow(x+g-0.5,x-0.5)/exp(x+g-0.5) ~ pow(y, x-0.5)/exp(y) * (1 + e*g/y),
Note that for accuracy, when computing r*C it's better to do
r + e*g/y*r;
than
r * (1 + e*g/y);
since the addition in the latter throws away most of the bits of
information in e*g/y.
*/
#define LANCZOS_N 13
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
};
/* 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};
/* 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,
};
/* Lanczos' sum L_g(x), for positive x */
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;
}
/* Constant for +infinity, generated in the same way as float('inf'). */
static double
m_inf(void)
{
#ifndef PY_NO_SHORT_FLOAT_REPR
return _Py_dg_infinity(0);
#else
return Py_HUGE_VAL;
#endif
}
/* Constant nan value, generated in the same way as float('nan'). */
/* We don't currently assume that Py_NAN is defined everywhere. */
#if !defined(PY_NO_SHORT_FLOAT_REPR) || defined(Py_NAN)
static double
m_nan(void)
{
#ifndef PY_NO_SHORT_FLOAT_REPR
return _Py_dg_stdnan(0);
#else
return Py_NAN;
#endif
}
#endif
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;
/* tgamma(+-0.0) = +-inf, divide-by-zero */
return copysign(Py_HUGE_VAL, x);
}
/* 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;
}
/*
lgamma: natural log of the absolute value of the Gamma function.
For large arguments, Lanczos' formula works extremely well here.
*/
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. 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(absx)) - lanczos_g;
r += (absx - 0.5) * (log(absx + lanczos_g - 0.5) - 1);
if (x < 0.0)
/* Use reflection formula to get value for negative x. */
r = logpi - log(fabs(sinpi(absx))) - log(absx) - r;
if (Py_IS_INFINITY(r))
errno = ERANGE;
return r;
}
/*
Implementations of the error function erf(x) and the complementary error
function erfc(x).
Method: we use a series approximation for erf for small x, and a continued
fraction approximation for erfc(x) for larger x;
combined with the relations erf(-x) = -erf(x) and erfc(x) = 1.0 - erf(x),
this gives us erf(x) and erfc(x) for all x.
The series expansion used is:
erf(x) = x*exp(-x*x)/sqrt(pi) * [
2/1 + 4/3 x**2 + 8/15 x**4 + 16/105 x**6 + ...]
The coefficient of x**(2k-2) here is 4**k*factorial(k)/factorial(2*k).
This series converges well for smallish x, but slowly for larger x.
The continued fraction expansion used is:
erfc(x) = x*exp(-x*x)/sqrt(pi) * [1/(0.5 + x**2 -) 0.5/(2.5 + x**2 - )
3.0/(4.5 + x**2 - ) 7.5/(6.5 + x**2 - ) ...]
after the first term, the general term has the form:
k*(k-0.5)/(2*k+0.5 + x**2 - ...).
This expansion converges fast for larger x, but convergence becomes
infinitely slow as x approaches 0.0. The (somewhat naive) continued
fraction evaluation algorithm used below also risks overflow for large x;
but for large x, erfc(x) == 0.0 to within machine precision. (For
example, erfc(30.0) is approximately 2.56e-393).
Parameters: use series expansion for abs(x) < ERF_SERIES_CUTOFF and
continued fraction expansion for ERF_SERIES_CUTOFF <= abs(x) <
ERFC_CONTFRAC_CUTOFF. ERFC_SERIES_TERMS and ERFC_CONTFRAC_TERMS are the
numbers of terms to use for the relevant expansions. */
#define ERF_SERIES_CUTOFF 1.5
#define ERF_SERIES_TERMS 25
#define ERFC_CONTFRAC_CUTOFF 30.0
#define ERFC_CONTFRAC_TERMS 50
/*
Error function, via power series.
Given a finite float x, return an approximation to erf(x).
Converges reasonably fast for small x.
*/
static double
m_erf_series(double x)
{
double x2, acc, fk, result;
int i, saved_errno;
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;
}
/* Make sure the exp call doesn't affect errno;
see m_erfc_contfrac for more. */
saved_errno = errno;
result = acc * x * exp(-x2) / sqrtpi;
errno = saved_errno;
return result;
}
/*
Complementary error function, via continued fraction expansion.
Given a positive float x, return an approximation to erfc(x). Converges
reasonably fast for x large (say, x > 2.0), and should be safe from
overflow if x and nterms are not too large. On an IEEE 754 machine, with x
<= 30.0, we're safe up to nterms = 100. For x >= 30.0, erfc(x) is smaller
than the smallest representable nonzero float. */
static double
m_erfc_contfrac(double x)
{
double x2, a, da, p, p_last, q, q_last, b, result;
int i, saved_errno;
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;
}
/* Issue #8986: On some platforms, exp sets errno on underflow to zero;
save the current errno value so that we can restore it later. */
saved_errno = errno;
result = p / q * x * exp(-x2) / sqrtpi;
errno = saved_errno;
return result;
}
/* Error function erf(x), for general 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;
}
}
/* Complementary error function erfc(x), for general 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;
}
}
/*
wrapper for atan2 that deals directly with special cases before
delegating to the platform libm for the remaining cases. This
is necessary to get consistent behaviour across platforms.
Windows, FreeBSD and alpha Tru64 are amongst platforms that don't
always follow C99.
*/
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);
}
/*
Various platforms (Solaris, OpenBSD) do nonstandard things for log(0),
log(-ve), log(NaN). Here are wrappers for log and log10 that deal with
special values directly, passing positive non-special values through to
the system log/log10.
*/
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 */
}
}
/*
log2: log to base 2.
Uses an algorithm that should:
(a) produce exact results for powers of 2, and
(b) give a monotonic log2 (for positive finite floats),
assuming that the system log is monotonic.
*/
static double
m_log2(double x)
{
if (!Py_IS_FINITE(x)) {
if (Py_IS_NAN(x))
return x; /* log2(nan) = nan */
else if (x > 0.0)
return x; /* log2(+inf) = +inf */
else {
errno = EDOM;
return Py_NAN; /* log2(-inf) = nan, invalid-operation */
}
}
if (x > 0.0) {
#ifdef HAVE_LOG2
return log2(x);
#else
double m;
int e;
m = frexp(x, &e);
/* We want log2(m * 2**e) == log(m) / log(2) + e. Care is needed when
* x is just greater than 1.0: in that case e is 1, log(m) is negative,
* and we get significant cancellation error from the addition of
* log(m) / log(2) to e. The slight rewrite of the expression below
* avoids this problem.
*/
if (x >= 1.0) {
return log(2.0 * m) / log(2.0) + (e - 1);
}
else {
return log(m) / log(2.0) + e;
}
#endif
}
else if (x == 0.0) {
errno = EDOM;
return -Py_HUGE_VAL; /* log2(0) = -inf, divide-by-zero */
}
else {
errno = EDOM;
return Py_NAN; /* log2(-inf) = nan, invalid-operation */
}
}
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 */
}
}
static PyObject *
math_gcd(PyObject *self, PyObject *args)
{
PyObject *a, *b, *g;
if (!PyArg_ParseTuple(args, "OO:gcd", &a, &b))
return NULL;
a = PyNumber_Index(a);
if (a == NULL)
return NULL;
b = PyNumber_Index(b);
if (b == NULL) {
Py_DECREF(a);
return NULL;
}
g = _PyLong_GCD(a, b);
Py_DECREF(a);
Py_DECREF(b);
return g;
}
PyDoc_STRVAR(math_gcd_doc,
"gcd(x, y) -> int\n\
greatest common divisor of x and y");
/* Call is_error when errno != 0, and where x is the result libm
* returned. is_error will usually set up an exception and return
* true (1), but may return false (0) without setting up an exception.
*/
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;
}
/*
math_1 is used to wrap a libm function f that takes a double
arguments and returns a double.
The error reporting follows these rules, which are designed to do
the right thing on C89/C99 platforms and IEEE 754/non IEEE 754
platforms.
- a NaN result from non-NaN inputs causes ValueError to be raised
- an infinite result from finite inputs causes OverflowError to be
raised if can_overflow is 1, or raises ValueError if can_overflow
is 0.
- if the result is finite and errno == EDOM then ValueError is
raised
- if the result is finite and nonzero and errno == ERANGE then
OverflowError is raised
The last rule is used to catch overflow on platforms which follow
C89 but for which HUGE_VAL is not an infinity.
For the majority of one-argument functions these rules are enough
to ensure that Python's functions behave as specified in 'Annex F'
of the C99 standard, with the 'invalid' and 'divide-by-zero'
floating-point exceptions mapping to Python's ValueError and the
'overflow' floating-point exception mapping to OverflowError.
math_1 only works for functions that don't have singularities *and*
the possibility of overflow; fortunately, that covers everything we
care about right now.
*/
static PyObject *
math_1_to_whatever(PyObject *arg, double (*func) (double),
PyObject *(*from_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) && !Py_IS_NAN(x)) {
PyErr_SetString(PyExc_ValueError,
"math domain error"); /* invalid arg */
return NULL;
}
if (Py_IS_INFINITY(r) && Py_IS_FINITE(x)) {
if (can_overflow)
PyErr_SetString(PyExc_OverflowError,
"math range error"); /* overflow */
else
PyErr_SetString(PyExc_ValueError,
"math domain error"); /* singularity */
return NULL;
}
if (Py_IS_FINITE(r) && errno && is_error(r))
/* this branch unnecessary on most platforms */
return NULL;
return (*from_double_func)(r);
}
/* variant of math_1, to be used when the function being wrapped is known to
set errno properly (that is, errno = EDOM for invalid or divide-by-zero,
errno = ERANGE for 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);
}
/*
math_2 is used to wrap a libm function f that takes two double
arguments and returns a double.
The error reporting follows these rules, which are designed to do
the right thing on C89/C99 platforms and IEEE 754/non IEEE 754
platforms.
- a NaN result from non-NaN inputs causes ValueError to be raised
- an infinite result from finite inputs causes OverflowError to be
raised.
- if the result is finite and errno == EDOM then ValueError is
raised
- if the result is finite and nonzero and errno == ERANGE then
OverflowError is raised
The last rule is used to catch overflow on platforms which follow
C89 but for which HUGE_VAL is not an infinity.
For most two-argument functions (copysign, fmod, hypot, atan2)
these rules are enough to ensure that Python's functions behave as
specified in 'Annex F' of the C99 standard, with the 'invalid' and
'divide-by-zero' floating-point exceptions mapping to Python's
ValueError and the 'overflow' floating-point exception mapping to
OverflowError.
*/
static PyObject *
math_1(PyObject *arg, double (*func) (double), int can_overflow)
{
return math_1_to_whatever(arg, func, PyFloat_FromDouble, can_overflow);
}
static PyObject *
math_1_to_int(PyObject *arg, double (*func) (double), int can_overflow)
{
return math_1_to_whatever(arg, func, PyLong_FromDouble, can_overflow);
}
static PyObject *
math_2(PyObject *args, double (*func) (double, double), const 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);
}
#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 FUNC2(funcname, func, 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.")
FUNC1(acosh, m_acosh, 0,
"acosh(x)\n\nReturn the inverse hyperbolic cosine of x.")
FUNC1(asin, asin, 0,
"asin(x)\n\nReturn the arc sine (measured in radians) of x.")
FUNC1(asinh, m_asinh, 0,
"asinh(x)\n\nReturn the inverse hyperbolic sine of x.")
FUNC1(atan, atan, 0,
"atan(x)\n\nReturn the arc tangent (measured in radians) of x.")
FUNC2(atan2, m_atan2,
"atan2(y, x)\n\nReturn the arc tangent (measured in radians) of y/x.\n"
"Unlike atan(y/x), the signs of both x and y are considered.")
FUNC1(atanh, m_atanh, 0,
"atanh(x)\n\nReturn the inverse hyperbolic tangent of x.")
static PyObject * math_ceil(PyObject *self, PyObject *number) {
_Py_IDENTIFIER(__ceil__);
PyObject *method, *result;
method = _PyObject_LookupSpecial(number, &PyId___ceil__);
if (method == NULL) {
if (PyErr_Occurred())
return NULL;
return math_1_to_int(number, ceil, 0);
}
result = PyObject_CallFunctionObjArgs(method, NULL);
Py_DECREF(method);
return result;
}
PyDoc_STRVAR(math_ceil_doc,
"ceil(x)\n\nReturn the ceiling of x as an Integral.\n"
"This is the smallest integer >= x.");
FUNC2(copysign, copysign,
"copysign(x, y)\n\nReturn a float with the magnitude (absolute value) "
"of x but the sign \nof y. On platforms that support signed zeros, "
"copysign(1.0, -0.0) \nreturns -1.0.\n")
FUNC1(cos, cos, 0,
"cos(x)\n\nReturn the cosine of x (measured in radians).")
FUNC1(cosh, cosh, 1,
"cosh(x)\n\nReturn the hyperbolic cosine of x.")
FUNC1A(erf, m_erf,
"erf(x)\n\nError function at x.")
FUNC1A(erfc, m_erfc,
"erfc(x)\n\nComplementary error function at x.")
FUNC1(exp, exp, 1,
"exp(x)\n\nReturn e raised to the power of x.")
FUNC1(expm1, m_expm1, 1,
"expm1(x)\n\nReturn exp(x)-1.\n"
"This function avoids the loss of precision involved in the direct "
"evaluation of exp(x)-1 for small x.")
FUNC1(fabs, fabs, 0,
"fabs(x)\n\nReturn the absolute value of the float x.")
static PyObject * math_floor(PyObject *self, PyObject *number) {
_Py_IDENTIFIER(__floor__);
PyObject *method, *result;
method = _PyObject_LookupSpecial(number, &PyId___floor__);
if (method == NULL) {
if (PyErr_Occurred())
return NULL;
return math_1_to_int(number, floor, 0);
}
result = PyObject_CallFunctionObjArgs(method, NULL);
Py_DECREF(method);
return result;
}
PyDoc_STRVAR(math_floor_doc,
"floor(x)\n\nReturn the floor of x as an Integral.\n"
"This is the largest integer <= x.");
FUNC1A(gamma, m_tgamma,
"gamma(x)\n\nGamma function at x.")
FUNC1A(lgamma, m_lgamma,
"lgamma(x)\n\nNatural logarithm of absolute value of Gamma function at x.")
FUNC1(log1p, m_log1p, 0,
"log1p(x)\n\nReturn the natural logarithm of 1+x (base e).\n"
"The result is computed in a way which is accurate for x near zero.")
FUNC1(sin, sin, 0,
"sin(x)\n\nReturn the sine of x (measured in radians).")
FUNC1(sinh, sinh, 1,
"sinh(x)\n\nReturn the hyperbolic sine of x.")
FUNC1(sqrt, sqrt, 0,
"sqrt(x)\n\nReturn the square root of x.")
FUNC1(tan, tan, 0,
"tan(x)\n\nReturn the tangent of x (measured in radians).")
FUNC1(tanh, tanh, 0,
"tanh(x)\n\nReturn the hyperbolic tangent of x.")
/* Precision summation function as msum() by Raymond Hettinger in
<http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/393090>,
enhanced with the exact partials sum and roundoff from Mark
Dickinson's post at <http://bugs.python.org/file10357/msum4.py>.
See those links for more details, proofs and other references.
Note 1: IEEE 754R floating point semantics are assumed,
but the current implementation does not re-establish special
value semantics across iterations (i.e. handling -Inf + Inf).
Note 2: No provision is made for intermediate overflow handling;
therefore, sum([1e+308, 1e-308, 1e+308]) returns 1e+308 while
sum([1e+308, 1e+308, 1e-308]) raises an OverflowError due to the
overflow of the first partial sum.
Note 3: The intermediate values lo, yr, and hi are declared volatile so
aggressive compilers won't algebraically reduce lo to always be exactly 0.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
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,
thereby preventing double rounding.
Note 4: A similar implementation is in Modules/cmathmodule.c.
Be sure to update both when making changes.
Note 5: The signature of math.fsum() differs from builtins.sum()
because the start argument doesn't make sense in the context of
accurate summation. Since the partials table is collapsed before
returning a result, sum(seq2, start=sum(seq1)) may not equal the
accurate result returned by sum(itertools.chain(seq1, seq2)).
*/
#define NUM_PARTIALS 32 /* initial partials array size, on stack */
/* Extend the partials array p[] by doubling its size. */
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 && (size_t)m < ((size_t)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.
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]
return sum_exact(partials)
Rounded x+y stored in hi with the roundoff stored in lo. Together hi+lo
are exactly equal to x+y. The inner loop applies hi/lo summation to each
partial so that the list of partial sums remains exact.
Sum_exact() adds the partial sums exactly and correctly rounds the final
result (using the round-half-to-even rule). The items in partials remain
non-zero, non-special, non-overlapping and strictly increasing in
magnitude, but possibly not all having the same sign.
Depends on IEEE 754 arithmetic guarantees and half-even rounding.
*/
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);
_fsum_error:
PyFPE_END_PROTECT(hi)
Py_DECREF(iter);
if (p != ps)
PyMem_Free(p);
return sum;
}
#undef NUM_PARTIALS
PyDoc_STRVAR(math_fsum_doc,
"fsum(iterable)\n\n\
Return an accurate floating point sum of values in the iterable.\n\
Assumes IEEE-754 floating point arithmetic.");
/* Return the smallest integer k such that n < 2**k, or 0 if n == 0.
* Equivalent to floor(lg(x))+1. Also equivalent to: bitwidth_of_type -
* count_leading_zero_bits(x)
*/
/* XXX: This routine does more or less the same thing as
* bits_in_digit() in Objects/longobject.c. Someday it would be nice to
* consolidate them. On BSD, there's a library function called fls()
* that we could use, and GCC provides __builtin_clz().
*/
static unsigned long
bit_length(unsigned long n)
{
unsigned long len = 0;
while (n != 0) {
++len;
n >>= 1;
}
return len;
}
static unsigned long
count_set_bits(unsigned long n)
{
unsigned long count = 0;
while (n != 0) {
++count;
n &= n - 1; /* clear least significant bit */
}
return count;
}
/* Divide-and-conquer factorial algorithm
*
* Based on the formula and pseudo-code provided at:
* http://www.luschny.de/math/factorial/binarysplitfact.html
*
* Faster algorithms exist, but they're more complicated and depend on
* a fast prime factorization algorithm.
*
* Notes on the algorithm
* ----------------------
*
* factorial(n) is written in the form 2**k * m, with m odd. k and m are
* computed separately, and then combined using a left shift.
*
* The function factorial_odd_part computes the odd part m (i.e., the greatest
* odd divisor) of factorial(n), using the formula:
*
* factorial_odd_part(n) =
*
* product_{i >= 0} product_{0 < j <= n / 2**i, j odd} j
*
* Example: factorial_odd_part(20) =
*
* (1) *
* (1) *
* (1 * 3 * 5) *
* (1 * 3 * 5 * 7 * 9)
* (1 * 3 * 5 * 7 * 9 * 11 * 13 * 15 * 17 * 19)
*
* Here i goes from large to small: the first term corresponds to i=4 (any
* larger i gives an empty product), and the last term corresponds to i=0.
* Each term can be computed from the last by multiplying by the extra odd
* numbers required: e.g., to get from the penultimate term to the last one,
* we multiply by (11 * 13 * 15 * 17 * 19).
*
* To see a hint of why this formula works, here are the same numbers as above
* but with the even parts (i.e., the appropriate powers of 2) included. For
* each subterm in the product for i, we multiply that subterm by 2**i:
*
* factorial(20) =
*
* (16) *
* (8) *
* (4 * 12 * 20) *
* (2 * 6 * 10 * 14 * 18) *
* (1 * 3 * 5 * 7 * 9 * 11 * 13 * 15 * 17 * 19)
*
* The factorial_partial_product function computes the product of all odd j in
* range(start, stop) for given start and stop. It's used to compute the
* partial products like (11 * 13 * 15 * 17 * 19) in the example above. It
* operates recursively, repeatedly splitting the range into two roughly equal
* pieces until the subranges are small enough to be computed using only C
* integer arithmetic.
*
* The two-valuation k (i.e., the exponent of the largest power of 2 dividing
* the factorial) is computed independently in the main math_factorial
* function. By standard results, its value is:
*
* two_valuation = n//2 + n//4 + n//8 + ....
*
* It can be shown (e.g., by complete induction on n) that two_valuation is
* equal to n - count_set_bits(n), where count_set_bits(n) gives the number of
* '1'-bits in the binary expansion of n.
*/
/* factorial_partial_product: Compute product(range(start, stop, 2)) using
* divide and conquer. Assumes start and stop are odd and stop > start.
* max_bits must be >= bit_length(stop - 2). */
static PyObject *
factorial_partial_product(unsigned long start, unsigned long stop,
unsigned long max_bits)
{
unsigned long midpoint, num_operands;
PyObject *left = NULL, *right = NULL, *result = NULL;
/* If the return value will fit an unsigned long, then we can
* multiply in a tight, fast loop where each multiply is O(1).
* Compute an upper bound on the number of bits required to store
* the answer.
*
* Storing some integer z requires floor(lg(z))+1 bits, which is
* conveniently the value returned by bit_length(z). The
* product x*y will require at most
* bit_length(x) + bit_length(y) bits to store, based
* on the idea that lg product = lg x + lg y.
*
* We know that stop - 2 is the largest number to be multiplied. From
* there, we have: bit_length(answer) <= num_operands *
* bit_length(stop - 2)
*/
num_operands = (stop - start) / 2;
/* The "num_operands <= 8 * SIZEOF_LONG" check guards against the
* unlikely case of an overflow in num_operands * max_bits. */
if (num_operands <= 8 * SIZEOF_LONG &&
num_operands * max_bits <= 8 * SIZEOF_LONG) {
unsigned long j, total;
for (total = start, j = start + 2; j < stop; j += 2)
total *= j;
return PyLong_FromUnsignedLong(total);
}
/* find midpoint of range(start, stop), rounded up to next odd number. */
midpoint = (start + num_operands) | 1;
left = factorial_partial_product(start, midpoint,
bit_length(midpoint - 2));
if (left == NULL)
goto error;
right = factorial_partial_product(midpoint, stop, max_bits);
if (right == NULL)
goto error;
result = PyNumber_Multiply(left, right);
error:
Py_XDECREF(left);
Py_XDECREF(right);
return result;
}
/* factorial_odd_part: compute the odd part of factorial(n). */
static PyObject *
factorial_odd_part(unsigned long n)
{
long i;
unsigned long v, lower, upper;
PyObject *partial, *tmp, *inner, *outer;
inner = PyLong_FromLong(1);
if (inner == NULL)
return NULL;
outer = inner;
Py_INCREF(outer);
upper = 3;
for (i = bit_length(n) - 2; i >= 0; i--) {
v = n >> i;
if (v <= 2)
continue;
lower = upper;
/* (v + 1) | 1 = least odd integer strictly larger than n / 2**i */
upper = (v + 1) | 1;
/* Here inner is the product of all odd integers j in the range (0,
n/2**(i+1)]. The factorial_partial_product call below gives the
product of all odd integers j in the range (n/2**(i+1), n/2**i]. */
partial = factorial_partial_product(lower, upper, bit_length(upper-2));
/* inner *= partial */
if (partial == NULL)
goto error;
tmp = PyNumber_Multiply(inner, partial);
Py_DECREF(partial);
if (tmp == NULL)
goto error;
Py_DECREF(inner);
inner = tmp;
/* Now inner is the product of all odd integers j in the range (0,
n/2**i], giving the inner product in the formula above. */
/* outer *= inner; */
tmp = PyNumber_Multiply(outer, inner);
if (tmp == NULL)
goto error;
Py_DECREF(outer);
outer = tmp;
}
Py_DECREF(inner);
return outer;
error:
Py_DECREF(outer);
Py_DECREF(inner);
return NULL;
}
/* Lookup table for small factorial values */
static const unsigned long SmallFactorials[] = {
1, 1, 2, 6, 24, 120, 720, 5040, 40320,
362880, 3628800, 39916800, 479001600,
#if SIZEOF_LONG >= 8
6227020800, 87178291200, 1307674368000,
20922789888000, 355687428096000, 6402373705728000,
121645100408832000, 2432902008176640000
#endif
};
static PyObject *
math_factorial(PyObject *self, PyObject *arg)
{
long x;
int overflow;
PyObject *result, *odd_part, *two_valuation;
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_AsLongAndOverflow(lx, &overflow);
Py_DECREF(lx);
}
else
x = PyLong_AsLongAndOverflow(arg, &overflow);
if (x == -1 && PyErr_Occurred()) {
return NULL;
}
else if (overflow == 1) {
PyErr_Format(PyExc_OverflowError,
"factorial() argument should not exceed %ld",
LONG_MAX);
return NULL;
}
else if (overflow == -1 || x < 0) {
PyErr_SetString(PyExc_ValueError,
"factorial() not defined for negative values");
return NULL;
}
/* use lookup table if x is small */
if (x < (long)Py_ARRAY_LENGTH(SmallFactorials))
return PyLong_FromUnsignedLong(SmallFactorials[x]);
/* else express in the form odd_part * 2**two_valuation, and compute as
odd_part << two_valuation. */
odd_part = factorial_odd_part(x);
if (odd_part == NULL)
return NULL;
two_valuation = PyLong_FromLong(x - count_set_bits(x));
if (two_valuation == NULL) {
Py_DECREF(odd_part);
return NULL;
}
result = PyNumber_Lshift(odd_part, two_valuation);
Py_DECREF(two_valuation);
Py_DECREF(odd_part);
return result;
}
PyDoc_STRVAR(math_factorial_doc,
"factorial(x) -> Integral\n"
"\n"
"Find x!. Raise a ValueError if x is negative or non-integral.");
static PyObject *
math_trunc(PyObject *self, PyObject *number)
{
_Py_IDENTIFIER(__trunc__);
PyObject *trunc, *result;
if (Py_TYPE(number)->tp_dict == NULL) {
if (PyType_Ready(Py_TYPE(number)) < 0)
return NULL;
}
trunc = _PyObject_LookupSpecial(number, &PyId___trunc__);
if (trunc == NULL) {
if (!PyErr_Occurred())
PyErr_Format(PyExc_TypeError,
"type %.100s doesn't define __trunc__ method",
Py_TYPE(number)->tp_name);
return NULL;
}
result = PyObject_CallFunctionObjArgs(trunc, NULL);
Py_DECREF(trunc);
return result;
}
PyDoc_STRVAR(math_trunc_doc,
"trunc(x:Real) -> Integral\n"
"\n"
"Truncates x to the nearest Integral toward 0. Uses the __trunc__ magic method.");
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);
}
PyDoc_STRVAR(math_frexp_doc,
"frexp(x)\n"
"\n"
"Return the mantissa and exponent of x, as pair (m, e).\n"
"m is a float and e is an int, such that x = m * 2.**e.\n"
"If x is 0, m and e are both 0. Else 0.5 <= abs(m) < 1.0.");
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)) {
/* 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 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,
"ldexp(x, i)\n\n\
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);
}
PyDoc_STRVAR(math_modf_doc,
"modf(x)\n"
"\n"
"Return the fractional and integer parts of x. Both results carry the sign\n"
"of x and are floats.");
/* A decent logarithm is easy to compute even for huge ints, but libm can't
do that by itself -- loghelper can. func is log or log10, and name is
"log" or "log10". Note that overflow of the result isn't possible: an int
can contain no more than INT_MAX * SHIFT bits, so has value certainly less
than 2**(2**64 * 2**16) == 2**2**80, and log2 of that is 2**80, which is
small enough to fit in an IEEE single. log and log10 are even smaller.
However, intermediate overflow is possible for an int if the number of bits
in that int is larger than PY_SSIZE_T_MAX. */
static PyObject*
loghelper(PyObject* arg, double (*func)(double), const char *funcname)
{
/* If it is int, do it ourselves. */
if (PyLong_Check(arg)) {
double x, result;
Py_ssize_t e;
/* Negative or zero inputs give a ValueError. */
if (Py_SIZE(arg) <= 0) {
PyErr_SetString(PyExc_ValueError,
"math domain error");
return NULL;
}
x = PyLong_AsDouble(arg);
if (x == -1.0 && PyErr_Occurred()) {
if (!PyErr_ExceptionMatches(PyExc_OverflowError))
return NULL;
/* Here the conversion to double overflowed, but it's possible
to compute the log anyway. Clear the exception and continue. */
PyErr_Clear();
x = _PyLong_Frexp((PyLongObject *)arg, &e);
if (x == -1.0 && PyErr_Occurred())
return NULL;
/* Value is ~= x * 2**e, so the log ~= log(x) + log(2) * e. */
result = func(x) + func(2.0) * e;
}
else
/* Successfully converted x to a double. */
result = func(x);
return PyFloat_FromDouble(result);
}
/* 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_TrueDivide(num, den);
Py_DECREF(num);
Py_DECREF(den);
return ans;
}
PyDoc_STRVAR(math_log_doc,
"log(x[, base])\n\n\
Return the logarithm of x to the given base.\n\
If the base not specified, returns the natural logarithm (base e) of x.");
static PyObject *
math_log2(PyObject *self, PyObject *arg)
{
return loghelper(arg, m_log2, "log2");
}
PyDoc_STRVAR(math_log2_doc,
"log2(x)\n\nReturn the base 2 logarithm of x.");
static PyObject *
math_log10(PyObject *self, PyObject *arg)
{
return loghelper(arg, m_log10, "log10");
}
PyDoc_STRVAR(math_log10_doc,
"log10(x)\n\nReturn the base 10 logarithm of x.");
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);
}
PyDoc_STRVAR(math_fmod_doc,
"fmod(x, y)\n\nReturn fmod(x, y), according to platform C."
" x % y may differ.");
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);
}
PyDoc_STRVAR(math_hypot_doc,
"hypot(x, y)\n\nReturn the Euclidean distance, sqrt(x*x + y*y).");
/* pow can't use math_2, but needs its own wrapper: the problem is
that an infinite result can arise either as a result of overflow
(in which case OverflowError should be raised) or as a result of
e.g. 0.**-5. (for which ValueError needs to be raised.)
*/
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);
}
PyDoc_STRVAR(math_pow_doc,
"pow(x, y)\n\nReturn x**y (x to the power of y).");
static const double degToRad = Py_MATH_PI / 180.0;
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);
}
PyDoc_STRVAR(math_degrees_doc,
"degrees(x)\n\n\
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);
}
PyDoc_STRVAR(math_radians_doc,
"radians(x)\n\n\
Convert angle x from degrees to radians.");
static PyObject *
math_isfinite(PyObject *self, PyObject *arg)
{
double x = PyFloat_AsDouble(arg);
if (x == -1.0 && PyErr_Occurred())
return NULL;
return PyBool_FromLong((long)Py_IS_FINITE(x));
}
PyDoc_STRVAR(math_isfinite_doc,
"isfinite(x) -> bool\n\n\
Return True if x is neither an infinity nor a NaN, and False otherwise.");
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));
}
PyDoc_STRVAR(math_isnan_doc,
"isnan(x) -> bool\n\n\
Return True if x is a NaN (not a number), and False otherwise.");
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));
}
PyDoc_STRVAR(math_isinf_doc,
"isinf(x) -> bool\n\n\
Return True if x is a positive or negative infinity, and False otherwise.");
static PyObject *
math_isclose(PyObject *self, PyObject *args, PyObject *kwargs)
{
double a, b;
double rel_tol = 1e-9;
double abs_tol = 0.0;
double diff = 0.0;
long result = 0;
static char *keywords[] = {"a", "b", "rel_tol", "abs_tol", NULL};
if (!PyArg_ParseTupleAndKeywords(args, kwargs, "dd|$dd:isclose",
keywords,
&a, &b, &rel_tol, &abs_tol
))
return NULL;
/* sanity check on the inputs */
if (rel_tol < 0.0 || abs_tol < 0.0 ) {
PyErr_SetString(PyExc_ValueError,
"tolerances must be non-negative");
return NULL;
}
if ( a == b ) {
/* short circuit exact equality -- needed to catch two infinities of
the same sign. And perhaps speeds things up a bit sometimes.
*/
Py_RETURN_TRUE;
}
/* This catches the case of two infinities of opposite sign, or
one infinity and one finite number. Two infinities of opposite
sign would otherwise have an infinite relative tolerance.
Two infinities of the same sign are caught by the equality check
above.
*/
if (Py_IS_INFINITY(a) || Py_IS_INFINITY(b)) {
Py_RETURN_FALSE;
}
/* now do the regular computation
this is essentially the "weak" test from the Boost library
*/
diff = fabs(b - a);
result = (((diff <= fabs(rel_tol * b)) ||
(diff <= fabs(rel_tol * a))) ||
(diff <= abs_tol));
return PyBool_FromLong(result);
}
PyDoc_STRVAR(math_isclose_doc,
"isclose(a, b, *, rel_tol=1e-09, abs_tol=0.0) -> bool\n"
"\n"
"Determine whether two floating point numbers are close in value.\n"
"\n"
" rel_tol\n"
" maximum difference for being considered \"close\", relative to the\n"
" magnitude of the input values\n"
" abs_tol\n"
" maximum difference for being considered \"close\", regardless of the\n"
" magnitude of the input values\n"
"\n"
"Return True if a is close in value to b, and False otherwise.\n"
"\n"
"For the values to be considered close, the difference between them\n"
"must be smaller than at least one of the tolerances.\n"
"\n"
"-inf, inf and NaN behave similarly to the IEEE 754 Standard. That\n"
"is, NaN is not close to anything, even itself. inf and -inf are\n"
"only close to themselves.");
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},
{"gcd", math_gcd, METH_VARARGS, math_gcd_doc},
{"hypot", math_hypot, METH_VARARGS, math_hypot_doc},
{"isclose", (PyCFunction) math_isclose, METH_VARARGS | METH_KEYWORDS,
math_isclose_doc},
{"isfinite", math_isfinite, METH_O, math_isfinite_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},
{"log2", math_log2, METH_O, math_log2_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 */
};
PyDoc_STRVAR(module_doc,
"This module is always available. It provides access to the\n"
"mathematical functions defined by the C standard.");
static struct PyModuleDef mathmodule = {
PyModuleDef_HEAD_INIT,
"math",
module_doc,
-1,
math_methods,
NULL,
NULL,
NULL,
NULL
};
PyMODINIT_FUNC
PyInit_math(void)
{
PyObject *m;
m = PyModule_Create(&mathmodule);
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, "tau", PyFloat_FromDouble(Py_MATH_TAU)); /* 2pi */
PyModule_AddObject(m, "inf", PyFloat_FromDouble(m_inf()));
#if !defined(PY_NO_SHORT_FLOAT_REPR) || defined(Py_NAN)
PyModule_AddObject(m, "nan", PyFloat_FromDouble(m_nan()));
#endif
finally:
return m;
}
_Section(".rodata.pytab.1") const struct _inittab _PyImport_Inittab_math = {
"math",
PyInit_math,
};
| 72,571 | 2,236 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Modules/_testmultiphase.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:8;coding:utf-8 -*-â
âvi: set net ft=c ts=4 sts=4 sw=4 fenc=utf-8 :viâ
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ¡
â Python 3 â
â https://docs.python.org/3/license.html â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
#include "third_party/python/Include/dictobject.h"
#include "third_party/python/Include/longobject.h"
#include "third_party/python/Include/methodobject.h"
#include "third_party/python/Include/modsupport.h"
#include "third_party/python/Include/namespaceobject.h"
#include "third_party/python/Include/object.h"
#include "third_party/python/Include/objimpl.h"
#include "third_party/python/Include/pystate.h"
#include "third_party/python/Include/typeslots.h"
#include "third_party/python/Include/yoink.h"
/* clang-format off */
PYTHON_PROVIDE("_testmultiphase");
PYTHON_PROVIDE("_testmultiphase.Example");
PYTHON_PROVIDE("_testmultiphase.Str");
PYTHON_PROVIDE("_testmultiphase.call_state_registration_func");
PYTHON_PROVIDE("_testmultiphase.error");
PYTHON_PROVIDE("_testmultiphase.foo");
PYTHON_PROVIDE("_testmultiphase.int_const");
PYTHON_PROVIDE("_testmultiphase.str_const");
/* Testing module for multi-phase initialization of extension modules (PEP 489)
*/
/* Example objects */
typedef struct {
PyObject_HEAD
PyObject *x_attr; /* Attributes dictionary */
} ExampleObject;
typedef struct {
PyObject *integer;
} testmultiphase_state;
/* Example methods */
static int
Example_traverse(ExampleObject *self, visitproc visit, void *arg)
{
Py_VISIT(self->x_attr);
return 0;
}
static void
Example_finalize(ExampleObject *self)
{
Py_CLEAR(self->x_attr);
}
static PyObject *
Example_demo(ExampleObject *self, PyObject *args)
{
PyObject *o = NULL;
if (!PyArg_ParseTuple(args, "|O:demo", &o))
return NULL;
if (o != NULL && PyUnicode_Check(o)) {
Py_INCREF(o);
return o;
}
Py_INCREF(Py_None);
return Py_None;
}
static PyMethodDef Example_methods[] = {
{"demo", (PyCFunction)Example_demo, METH_VARARGS,
PyDoc_STR("demo() -> None")},
{NULL, NULL} /* sentinel */
};
static PyObject *
Example_getattro(ExampleObject *self, PyObject *name)
{
if (self->x_attr != NULL) {
PyObject *v = PyDict_GetItem(self->x_attr, name);
if (v != NULL) {
Py_INCREF(v);
return v;
}
}
return PyObject_GenericGetAttr((PyObject *)self, name);
}
static int
Example_setattr(ExampleObject *self, const 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 Example attribute");
return rv;
}
else
return PyDict_SetItemString(self->x_attr, name, v);
}
static PyType_Slot Example_Type_slots[] = {
{Py_tp_doc, "The Example type"},
{Py_tp_finalize, Example_finalize},
{Py_tp_traverse, Example_traverse},
{Py_tp_getattro, Example_getattro},
{Py_tp_setattr, Example_setattr},
{Py_tp_methods, Example_methods},
{0, 0},
};
static PyType_Spec Example_Type_spec = {
"_testimportexec.Example",
sizeof(ExampleObject),
0,
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC | Py_TPFLAGS_HAVE_FINALIZE,
Example_Type_slots
};
/* Function of two integers returning integer */
PyDoc_STRVAR(testexport_foo_doc,
"foo(i,j)\n\
\n\
Return the sum of i and j.");
static PyObject *
testexport_foo(PyObject *self, PyObject *args)
{
long i, j;
long res;
if (!PyArg_ParseTuple(args, "ll:foo", &i, &j))
return NULL;
res = i + j;
return PyLong_FromLong(res);
}
/* Test that PyState registration fails */
PyDoc_STRVAR(call_state_registration_func_doc,
"register_state(0): call PyState_FindModule()\n\
register_state(1): call PyState_AddModule()\n\
register_state(2): call PyState_RemoveModule()");
static PyObject *
call_state_registration_func(PyObject *mod, PyObject *args)
{
int i, ret;
PyModuleDef *def = PyModule_GetDef(mod);
if (def == NULL) {
return NULL;
}
if (!PyArg_ParseTuple(args, "i:call_state_registration_func", &i))
return NULL;
switch (i) {
case 0:
mod = PyState_FindModule(def);
if (mod == NULL) {
Py_RETURN_NONE;
}
return mod;
case 1:
ret = PyState_AddModule(mod, def);
if (ret != 0) {
return NULL;
}
break;
case 2:
ret = PyState_RemoveModule(def);
if (ret != 0) {
return NULL;
}
break;
}
Py_RETURN_NONE;
}
static PyType_Slot Str_Type_slots[] = {
{Py_tp_base, NULL}, /* filled out in module exec function */
{0, 0},
};
static PyType_Spec Str_Type_spec = {
"_testimportexec.Str",
0,
0,
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
Str_Type_slots
};
static PyMethodDef testexport_methods[] = {
{"foo", testexport_foo, METH_VARARGS,
testexport_foo_doc},
{"call_state_registration_func", call_state_registration_func,
METH_VARARGS, call_state_registration_func_doc},
{NULL, NULL} /* sentinel */
};
static int execfunc(PyObject *m)
{
PyObject *temp = NULL;
/* Due to cross platform compiler issues the slots must be filled
* here. It's required for portability to Windows without requiring
* C++. */
Str_Type_slots[0].pfunc = &PyUnicode_Type;
/* Add a custom type */
temp = PyType_FromSpec(&Example_Type_spec);
if (temp == NULL)
goto fail;
if (PyModule_AddObject(m, "Example", temp) != 0)
goto fail;
/* Add an exception type */
temp = PyErr_NewException("_testimportexec.error", NULL, NULL);
if (temp == NULL)
goto fail;
if (PyModule_AddObject(m, "error", temp) != 0)
goto fail;
/* Add Str */
temp = PyType_FromSpec(&Str_Type_spec);
if (temp == NULL)
goto fail;
if (PyModule_AddObject(m, "Str", temp) != 0)
goto fail;
if (PyModule_AddIntConstant(m, "int_const", 1969) != 0)
goto fail;
if (PyModule_AddStringConstant(m, "str_const", "something different") != 0)
goto fail;
return 0;
fail:
return -1;
}
/* Helper for module definitions; there'll be a lot of them */
#define TEST_MODULE_DEF_EX(name, slots, methods, statesize, traversefunc) { \
PyModuleDef_HEAD_INIT, /* m_base */ \
name, /* m_name */ \
PyDoc_STR("Test module " name), /* m_doc */ \
statesize, /* m_size */ \
methods, /* m_methods */ \
slots, /* m_slots */ \
traversefunc, /* m_traverse */ \
NULL, /* m_clear */ \
NULL, /* m_free */ \
}
#define TEST_MODULE_DEF(name, slots, methods) TEST_MODULE_DEF_EX(name, slots, methods, 0, NULL)
static PyModuleDef_Slot main_slots[] = {
{Py_mod_exec, execfunc},
{0, NULL},
};
static PyModuleDef main_def = TEST_MODULE_DEF("main", main_slots, testexport_methods);
PyMODINIT_FUNC
PyInit__testmultiphase(PyObject *spec)
{
return PyModuleDef_Init(&main_def);
}
/**** Importing a non-module object ****/
static PyModuleDef def_nonmodule;
static PyModuleDef def_nonmodule_with_methods;
/* Create a SimpleNamespace(three=3) */
static PyObject*
createfunc_nonmodule(PyObject *spec, PyModuleDef *def)
{
PyObject *dct, *ns, *three;
if (def != &def_nonmodule && def != &def_nonmodule_with_methods) {
PyErr_SetString(PyExc_SystemError, "def does not match");
return NULL;
}
dct = PyDict_New();
if (dct == NULL)
return NULL;
three = PyLong_FromLong(3);
if (three == NULL) {
Py_DECREF(dct);
return NULL;
}
PyDict_SetItemString(dct, "three", three);
Py_DECREF(three);
ns = _PyNamespace_New(dct);
Py_DECREF(dct);
return ns;
}
static PyModuleDef_Slot slots_create_nonmodule[] = {
{Py_mod_create, createfunc_nonmodule},
{0, NULL},
};
static PyModuleDef def_nonmodule = TEST_MODULE_DEF(
"_testmultiphase_nonmodule", slots_create_nonmodule, NULL);
PyMODINIT_FUNC
PyInit__testmultiphase_nonmodule(PyObject *spec)
{
return PyModuleDef_Init(&def_nonmodule);
}
PyDoc_STRVAR(nonmodule_bar_doc,
"bar(i,j)\n\
\n\
Return the difference of i - j.");
static PyObject *
nonmodule_bar(PyObject *self, PyObject *args)
{
long i, j;
long res;
if (!PyArg_ParseTuple(args, "ll:bar", &i, &j))
return NULL;
res = i - j;
return PyLong_FromLong(res);
}
static PyMethodDef nonmodule_methods[] = {
{"bar", nonmodule_bar, METH_VARARGS, nonmodule_bar_doc},
{NULL, NULL} /* sentinel */
};
static PyModuleDef def_nonmodule_with_methods = TEST_MODULE_DEF(
"_testmultiphase_nonmodule_with_methods", slots_create_nonmodule, nonmodule_methods);
PyMODINIT_FUNC
PyInit__testmultiphase_nonmodule_with_methods(PyObject *spec)
{
return PyModuleDef_Init(&def_nonmodule_with_methods);
}
/**** Non-ASCII-named modules ****/
static PyModuleDef def_nonascii_latin = { \
PyModuleDef_HEAD_INIT, /* m_base */
"_testmultiphase_nonascii_latin", /* m_name */
PyDoc_STR("Module named in Czech"), /* m_doc */
0, /* m_size */
NULL, /* m_methods */
NULL, /* m_slots */
NULL, /* m_traverse */
NULL, /* m_clear */
NULL, /* m_free */
};
PyMODINIT_FUNC
PyInitU__testmultiphase_zkouka_naten_evc07gi8e(PyObject *spec)
{
return PyModuleDef_Init(&def_nonascii_latin);
}
static PyModuleDef def_nonascii_kana = { \
PyModuleDef_HEAD_INIT, /* m_base */
"_testmultiphase_nonascii_kana", /* m_name */
PyDoc_STR("Module named in Japanese"), /* m_doc */
0, /* m_size */
NULL, /* m_methods */
NULL, /* m_slots */
NULL, /* m_traverse */
NULL, /* m_clear */
NULL, /* m_free */
};
PyMODINIT_FUNC
PyInitU_eckzbwbhc6jpgzcx415x(PyObject *spec)
{
return PyModuleDef_Init(&def_nonascii_kana);
}
/*** Module with a single-character name ***/
PyMODINIT_FUNC
PyInit_x(PyObject *spec)
{
return PyModuleDef_Init(&main_def);
}
/**** Testing NULL slots ****/
static PyModuleDef null_slots_def = TEST_MODULE_DEF(
"_testmultiphase_null_slots", NULL, NULL);
PyMODINIT_FUNC
PyInit__testmultiphase_null_slots(PyObject *spec)
{
return PyModuleDef_Init(&null_slots_def);
}
/**** Problematic modules ****/
static PyModuleDef_Slot slots_bad_large[] = {
{_Py_mod_LAST_SLOT + 1, NULL},
{0, NULL},
};
static PyModuleDef def_bad_large = TEST_MODULE_DEF(
"_testmultiphase_bad_slot_large", slots_bad_large, NULL);
PyMODINIT_FUNC
PyInit__testmultiphase_bad_slot_large(PyObject *spec)
{
return PyModuleDef_Init(&def_bad_large);
}
static PyModuleDef_Slot slots_bad_negative[] = {
{-1, NULL},
{0, NULL},
};
static PyModuleDef def_bad_negative = TEST_MODULE_DEF(
"_testmultiphase_bad_slot_negative", slots_bad_negative, NULL);
PyMODINIT_FUNC
PyInit__testmultiphase_bad_slot_negative(PyObject *spec)
{
return PyModuleDef_Init(&def_bad_negative);
}
static PyModuleDef def_create_int_with_state = { \
PyModuleDef_HEAD_INIT, /* m_base */
"create_with_state", /* m_name */
PyDoc_STR("Not a PyModuleObject object, but requests per-module state"),
10, /* m_size */
NULL, /* m_methods */
slots_create_nonmodule, /* m_slots */
NULL, /* m_traverse */
NULL, /* m_clear */
NULL, /* m_free */
};
PyMODINIT_FUNC
PyInit__testmultiphase_create_int_with_state(PyObject *spec)
{
return PyModuleDef_Init(&def_create_int_with_state);
}
static PyModuleDef def_negative_size = { \
PyModuleDef_HEAD_INIT, /* m_base */
"negative_size", /* m_name */
PyDoc_STR("PyModuleDef with negative m_size"),
-1, /* m_size */
NULL, /* m_methods */
slots_create_nonmodule, /* m_slots */
NULL, /* m_traverse */
NULL, /* m_clear */
NULL, /* m_free */
};
PyMODINIT_FUNC
PyInit__testmultiphase_negative_size(PyObject *spec)
{
return PyModuleDef_Init(&def_negative_size);
}
static PyModuleDef uninitialized_def = TEST_MODULE_DEF("main", main_slots, testexport_methods);
PyMODINIT_FUNC
PyInit__testmultiphase_export_uninitialized(PyObject *spec)
{
return (PyObject*) &uninitialized_def;
}
PyMODINIT_FUNC
PyInit__testmultiphase_export_null(PyObject *spec)
{
return NULL;
}
PyMODINIT_FUNC
PyInit__testmultiphase_export_raise(PyObject *spec)
{
PyErr_SetString(PyExc_SystemError, "bad export function");
return NULL;
}
PyMODINIT_FUNC
PyInit__testmultiphase_export_unreported_exception(PyObject *spec)
{
PyErr_SetString(PyExc_SystemError, "bad export function");
return PyModuleDef_Init(&main_def);
}
static PyObject*
createfunc_null(PyObject *spec, PyModuleDef *def)
{
return NULL;
}
static PyModuleDef_Slot slots_create_null[] = {
{Py_mod_create, createfunc_null},
{0, NULL},
};
static PyModuleDef def_create_null = TEST_MODULE_DEF(
"_testmultiphase_create_null", slots_create_null, NULL);
PyMODINIT_FUNC
PyInit__testmultiphase_create_null(PyObject *spec)
{
return PyModuleDef_Init(&def_create_null);
}
static PyObject*
createfunc_raise(PyObject *spec, PyModuleDef *def)
{
PyErr_SetString(PyExc_SystemError, "bad create function");
return NULL;
}
static PyModuleDef_Slot slots_create_raise[] = {
{Py_mod_create, createfunc_raise},
{0, NULL},
};
static PyModuleDef def_create_raise = TEST_MODULE_DEF(
"_testmultiphase_create_null", slots_create_raise, NULL);
PyMODINIT_FUNC
PyInit__testmultiphase_create_raise(PyObject *spec)
{
return PyModuleDef_Init(&def_create_raise);
}
static PyObject*
createfunc_unreported_exception(PyObject *spec, PyModuleDef *def)
{
PyErr_SetString(PyExc_SystemError, "bad create function");
return PyModule_New("foo");
}
static PyModuleDef_Slot slots_create_unreported_exception[] = {
{Py_mod_create, createfunc_unreported_exception},
{0, NULL},
};
static PyModuleDef def_create_unreported_exception = TEST_MODULE_DEF(
"_testmultiphase_create_unreported_exception", slots_create_unreported_exception, NULL);
PyMODINIT_FUNC
PyInit__testmultiphase_create_unreported_exception(PyObject *spec)
{
return PyModuleDef_Init(&def_create_unreported_exception);
}
static PyModuleDef_Slot slots_nonmodule_with_exec_slots[] = {
{Py_mod_create, createfunc_nonmodule},
{Py_mod_exec, execfunc},
{0, NULL},
};
static PyModuleDef def_nonmodule_with_exec_slots = TEST_MODULE_DEF(
"_testmultiphase_nonmodule_with_exec_slots", slots_nonmodule_with_exec_slots, NULL);
PyMODINIT_FUNC
PyInit__testmultiphase_nonmodule_with_exec_slots(PyObject *spec)
{
return PyModuleDef_Init(&def_nonmodule_with_exec_slots);
}
static int
execfunc_err(PyObject *mod)
{
return -1;
}
static PyModuleDef_Slot slots_exec_err[] = {
{Py_mod_exec, execfunc_err},
{0, NULL},
};
static PyModuleDef def_exec_err = TEST_MODULE_DEF(
"_testmultiphase_exec_err", slots_exec_err, NULL);
PyMODINIT_FUNC
PyInit__testmultiphase_exec_err(PyObject *spec)
{
return PyModuleDef_Init(&def_exec_err);
}
static int
execfunc_raise(PyObject *spec)
{
PyErr_SetString(PyExc_SystemError, "bad exec function");
return -1;
}
static PyModuleDef_Slot slots_exec_raise[] = {
{Py_mod_exec, execfunc_raise},
{0, NULL},
};
static PyModuleDef def_exec_raise = TEST_MODULE_DEF(
"_testmultiphase_exec_raise", slots_exec_raise, NULL);
PyMODINIT_FUNC
PyInit__testmultiphase_exec_raise(PyObject *mod)
{
return PyModuleDef_Init(&def_exec_raise);
}
static int
execfunc_unreported_exception(PyObject *mod)
{
PyErr_SetString(PyExc_SystemError, "bad exec function");
return 0;
}
static PyModuleDef_Slot slots_exec_unreported_exception[] = {
{Py_mod_exec, execfunc_unreported_exception},
{0, NULL},
};
static PyModuleDef def_exec_unreported_exception = TEST_MODULE_DEF(
"_testmultiphase_exec_unreported_exception", slots_exec_unreported_exception, NULL);
PyMODINIT_FUNC
PyInit__testmultiphase_exec_unreported_exception(PyObject *spec)
{
return PyModuleDef_Init(&def_exec_unreported_exception);
}
static int
bad_traverse(PyObject *self, visitproc visit, void *arg) {
testmultiphase_state *m_state;
m_state = PyModule_GetState(self);
Py_VISIT(m_state->integer);
return 0;
}
static int
execfunc_with_bad_traverse(PyObject *mod) {
testmultiphase_state *m_state;
m_state = PyModule_GetState(mod);
if (m_state == NULL) {
return -1;
}
m_state->integer = PyLong_FromLong(0x7fffffff);
Py_INCREF(m_state->integer);
return 0;
}
static PyModuleDef_Slot slots_with_bad_traverse[] = {
{Py_mod_exec, execfunc_with_bad_traverse},
{0, NULL}
};
static PyModuleDef def_with_bad_traverse = TEST_MODULE_DEF_EX(
"_testmultiphase_with_bad_traverse", slots_with_bad_traverse, NULL,
sizeof(testmultiphase_state), bad_traverse);
PyMODINIT_FUNC
PyInit__testmultiphase_with_bad_traverse(PyObject *spec) {
return PyModuleDef_Init(&def_with_bad_traverse);
}
/*** Helper for imp test ***/
static PyModuleDef imp_dummy_def = TEST_MODULE_DEF("imp_dummy", main_slots, testexport_methods);
PyMODINIT_FUNC
PyInit_imp_dummy(PyObject *spec)
{
return PyModuleDef_Init(&imp_dummy_def);
}
| 19,299 | 695 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Modules/_bisectmodule.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:8;coding:utf-8 -*-â
âvi: set net ft=c ts=4 sts=4 sw=4 fenc=utf-8 :viâ
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ¡
â Python 3 â
â https://docs.python.org/3/license.html â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
#define PY_SSIZE_T_CLEAN
#include "third_party/python/Include/abstract.h"
#include "third_party/python/Include/import.h"
#include "third_party/python/Include/longobject.h"
#include "third_party/python/Include/modsupport.h"
#include "third_party/python/Include/object.h"
#include "third_party/python/Include/pyerrors.h"
#include "third_party/python/Include/pymacro.h"
#include "third_party/python/Include/yoink.h"
/* clang-format off */
PYTHON_PROVIDE("_bisect");
PYTHON_PROVIDE("_bisect.bisect");
PYTHON_PROVIDE("_bisect.bisect_left");
PYTHON_PROVIDE("_bisect.bisect_right");
PYTHON_PROVIDE("_bisect.insort");
PYTHON_PROVIDE("_bisect.insort_left");
PYTHON_PROVIDE("_bisect.insort_right");
/* Bisection algorithms. Drop in replacement for bisect.py
Converted to C by Dmitry Vasiliev (dima at hlabs.spb.ru).
*/
_Py_IDENTIFIER(insert);
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;
int 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) {
/* The (size_t)cast ensures that the addition and subsequent division
are performed as unsigned operations, avoiding difficulties from
signed overflow. (See issue 13496.) */
mid = ((size_t)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 PyLong_FromSsize_t(index);
}
PyDoc_STRVAR(bisect_right_doc,
"bisect_right(a, x[, lo[, hi]]) -> index\n\
\n\
Return the index where to insert item x in list a, assuming a is sorted.\n\
\n\
The return value i is such that all e in a[:i] have e <= x, and all e in\n\
a[i:] have e > x. So if x already appears in the list, i points just\n\
beyond the rightmost x already there\n\
\n\
Optional args lo (default 0) and hi (default len(a)) bound the\n\
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_CallMethodId(list, &PyId_insert, "nO", index, item);
if (result == NULL)
return NULL;
Py_DECREF(result);
}
Py_RETURN_NONE;
}
PyDoc_STRVAR(insort_right_doc,
"insort_right(a, x[, lo[, hi]])\n\
\n\
Insert item x in list a, and keep it sorted assuming a is sorted.\n\
\n\
If x is already in a, insert it to the right of the rightmost x.\n\
\n\
Optional args lo (default 0) and hi (default len(a)) bound the\n\
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;
int 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) {
/* The (size_t)cast ensures that the addition and subsequent division
are performed as unsigned operations, avoiding difficulties from
signed overflow. (See issue 13496.) */
mid = ((size_t)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 PyLong_FromSsize_t(index);
}
PyDoc_STRVAR(bisect_left_doc,
"bisect_left(a, x[, lo[, hi]]) -> index\n\
\n\
Return the index where to insert item x in list a, assuming a is sorted.\n\
\n\
The return value i is such that all e in a[:i] have e < x, and all e in\n\
a[i:] have e >= x. So if x already appears in the list, i points just\n\
before the leftmost x already there.\n\
\n\
Optional args lo (default 0) and hi (default len(a)) bound the\n\
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_CallMethodId(list, &PyId_insert, "nO", index, item);
if (result == NULL)
return NULL;
Py_DECREF(result);
}
Py_RETURN_NONE;
}
PyDoc_STRVAR(insort_left_doc,
"insort_left(a, x[, lo[, hi]])\n\
\n\
Insert item x in list a, and keep it sorted assuming a is sorted.\n\
\n\
If x is already in a, insert it to the left of the leftmost x.\n\
\n\
Optional args lo (default 0) and hi (default len(a)) bound the\n\
slice of a to be searched.\n");
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 */
};
PyDoc_STRVAR(module_doc,
"Bisection algorithms.\n\
\n\
This module provides support for maintaining a list in sorted order without\n\
having to sort the list after each insertion. For long lists of items with\n\
expensive comparison operations, this can be an improvement over the more\n\
common approach.\n");
static struct PyModuleDef _bisectmodule = {
PyModuleDef_HEAD_INIT,
"_bisect",
module_doc,
-1,
bisect_methods,
NULL,
NULL,
NULL,
NULL
};
PyMODINIT_FUNC
PyInit__bisect(void)
{
return PyModule_Create(&_bisectmodule);
}
_Section(".rodata.pytab.1") const struct _inittab _PyImport_Inittab__bisect = {
"_bisect",
PyInit__bisect,
};
| 9,161 | 291 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Modules/sre.h | #ifndef SRE_INCLUDED
#define SRE_INCLUDED
#include "third_party/python/Include/object.h"
#include "third_party/python/Include/unicodeobject.h"
#include "third_party/python/Modules/sre_constants.h"
/* size of a code word (must be unsigned short or larger, and
large enough to hold a UCS4 character) */
#define SRE_CODE Py_UCS4
#if SIZEOF_SIZE_T > 4
#define SRE_MAXREPEAT (~(SRE_CODE)0)
#define SRE_MAXGROUPS ((~(SRE_CODE)0) / 2)
#else
#define SRE_MAXREPEAT ((SRE_CODE)PY_SSIZE_T_MAX)
#define SRE_MAXGROUPS ((SRE_CODE)PY_SSIZE_T_MAX / SIZEOF_SIZE_T / 2)
#endif
typedef struct {
PyObject_VAR_HEAD Py_ssize_t groups; /* must be first! */
PyObject* groupindex;
PyObject* indexgroup;
/* compatibility */
PyObject* pattern; /* pattern source (or None) */
int flags; /* flags used when compiling pattern source */
PyObject* weakreflist; /* List of weak references */
int isbytes; /* pattern type (1 - bytes, 0 - string, -1 - None) */
/* pattern code */
Py_ssize_t codesize;
SRE_CODE code[1];
} PatternObject;
#define PatternObject_GetCode(o) (((PatternObject*)(o))->code)
typedef struct {
PyObject_VAR_HEAD PyObject*
string; /* link to the target string (must be first) */
PyObject* regs; /* cached list of matching spans */
PatternObject* pattern; /* link to the regex (pattern) object */
Py_ssize_t pos, endpos; /* current target slice */
Py_ssize_t lastindex; /* last index marker seen by the engine (-1 if none) */
Py_ssize_t groups; /* number of groups (start/end marks) */
Py_ssize_t mark[1];
} MatchObject;
typedef unsigned int (*SRE_TOLOWER_HOOK)(unsigned int ch);
typedef struct SRE_REPEAT_T {
Py_ssize_t count;
SRE_CODE* pattern; /* points to REPEAT operator arguments */
void* last_ptr; /* helper to check for infinite loops */
struct SRE_REPEAT_T* prev; /* points to previous repeat context */
} SRE_REPEAT;
typedef struct {
/* string pointers */
void* ptr; /* current position (also end of current slice) */
void* beginning; /* start of original string */
void* start; /* start of current slice */
void* end; /* end of original string */
/* attributes for the match object */
PyObject* string;
Py_ssize_t pos, endpos;
int isbytes;
int charsize; /* character size */
/* registers */
Py_ssize_t lastindex;
Py_ssize_t lastmark;
void** mark;
/* dynamically allocated stuff */
char* data_stack;
size_t data_stack_size;
size_t data_stack_base;
Py_buffer buffer;
/* current repeat context */
SRE_REPEAT* repeat;
/* hooks */
SRE_TOLOWER_HOOK lower, upper;
} SRE_STATE;
typedef struct {
PyObject_HEAD PyObject* pattern;
SRE_STATE state;
} ScannerObject;
#endif /* SRE_INCLUDED */
| 2,772 | 86 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Modules/rotatingtree.h | #ifndef COSMOPOLITAN_THIRD_PARTY_PYTHON_MODULES_ROTATINGTREE_H_
#define COSMOPOLITAN_THIRD_PARTY_PYTHON_MODULES_ROTATINGTREE_H_
#if !(__ASSEMBLER__ + __LINKER__ + 0)
COSMOPOLITAN_C_START_
/* clang-format off */
/* "Rotating trees" (Armin Rigo)
*
* Google "splay trees" for the general idea.
*
* It's a dict-like data structure that works best when accesses are not
* random, but follow a strong pattern. The one implemented here is for
* access patterns where the same small set of keys is looked up over
* and over again, and this set of keys evolves slowly over time.
*/
#define EMPTY_ROTATING_TREE ((rotating_node_t *)NULL)
typedef struct rotating_node_s rotating_node_t;
typedef int (*rotating_tree_enum_fn) (rotating_node_t *node, void *arg);
struct rotating_node_s {
void *key;
rotating_node_t *left;
rotating_node_t *right;
};
void RotatingTree_Add(rotating_node_t **root, rotating_node_t *node);
rotating_node_t* RotatingTree_Get(rotating_node_t **root, void *key);
int RotatingTree_Enum(rotating_node_t *root, rotating_tree_enum_fn enumfn,
void *arg);
COSMOPOLITAN_C_END_
#endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */
#endif /* COSMOPOLITAN_THIRD_PARTY_PYTHON_MODULES_ROTATINGTREE_H_ */
| 1,229 | 36 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Modules/selectmodule.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:8;coding:utf-8 -*-â
âvi: set net ft=c ts=4 sts=4 sw=4 fenc=utf-8 :viâ
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ¡
â Python 3 â
â https://docs.python.org/3/license.html â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
#include "libc/calls/calls.h"
#include "libc/dce.h"
#include "libc/errno.h"
#include "libc/mem/mem.h"
#include "libc/nt/efi.h"
#include "libc/mem/gc.internal.h"
#include "libc/sock/epoll.h"
#include "libc/sock/select.h"
#include "libc/sock/sock.h"
#include "libc/sock/struct/pollfd.h"
#include "libc/sysv/consts/epoll.h"
#include "libc/sysv/consts/poll.h"
#include "third_party/python/Include/abstract.h"
#include "third_party/python/Include/boolobject.h"
#include "third_party/python/Include/ceval.h"
#include "third_party/python/Include/descrobject.h"
#include "third_party/python/Include/dictobject.h"
#include "third_party/python/Include/fileobject.h"
#include "third_party/python/Include/import.h"
#include "third_party/python/Include/longobject.h"
#include "third_party/python/Include/modsupport.h"
#include "third_party/python/Include/objimpl.h"
#include "third_party/python/Include/pyerrors.h"
#include "third_party/python/Include/pymacro.h"
#include "third_party/python/Include/pymem.h"
#include "third_party/python/Include/pytime.h"
#include "third_party/python/Include/structmember.h"
#include "third_party/python/Include/yoink.h"
#include "third_party/python/pyconfig.h"
/* clang-format off */
PYTHON_PROVIDE("select");
PYTHON_PROVIDE("select.EPOLLERR");
PYTHON_PROVIDE("select.EPOLLET");
PYTHON_PROVIDE("select.EPOLLEXCLUSIVE");
PYTHON_PROVIDE("select.EPOLLHUP");
PYTHON_PROVIDE("select.EPOLLIN");
PYTHON_PROVIDE("select.EPOLLMSG");
PYTHON_PROVIDE("select.EPOLLONESHOT");
PYTHON_PROVIDE("select.EPOLLOUT");
PYTHON_PROVIDE("select.EPOLLPRI");
PYTHON_PROVIDE("select.EPOLLRDBAND");
PYTHON_PROVIDE("select.EPOLLRDHUP");
PYTHON_PROVIDE("select.EPOLLRDNORM");
PYTHON_PROVIDE("select.EPOLLWRBAND");
PYTHON_PROVIDE("select.EPOLLWRNORM");
PYTHON_PROVIDE("select.EPOLL_CLOEXEC");
PYTHON_PROVIDE("select.POLLERR");
PYTHON_PROVIDE("select.POLLHUP");
PYTHON_PROVIDE("select.POLLIN");
PYTHON_PROVIDE("select.POLLNVAL");
PYTHON_PROVIDE("select.POLLOUT");
PYTHON_PROVIDE("select.POLLPRI");
PYTHON_PROVIDE("select.POLLRDBAND");
PYTHON_PROVIDE("select.POLLRDHUP");
PYTHON_PROVIDE("select.POLLRDNORM");
PYTHON_PROVIDE("select.POLLWRBAND");
PYTHON_PROVIDE("select.POLLWRNORM");
PYTHON_PROVIDE("select.epoll");
PYTHON_PROVIDE("select.error");
PYTHON_PROVIDE("select.poll");
PYTHON_PROVIDE("select.select");
/* select - Module containing unix select(2) call.
Under Unix, the file descriptors are small integers.
Under Win32, select only exists for sockets, and sockets may
have any value except INVALID_SOCKET.
*/
#define SOCKET int
/* list of Python objects and their file descriptor */
typedef struct {
PyObject *obj; /* owned reference */
SOCKET fd;
int sentinel; /* -1 == sentinel */
} pylist;
static void
reap_obj(pylist fd2obj[FD_SETSIZE + 1])
{
unsigned int i;
for (i = 0; i < (unsigned int)FD_SETSIZE + 1 && fd2obj[i].sentinel >= 0; i++) {
Py_CLEAR(fd2obj[i].obj);
}
fd2obj[0].sentinel = -1;
}
/* returns -1 and sets the Python exception if an error occurred, otherwise
returns a number >= 0
*/
static int
seq2set(PyObject *seq, fd_set *set, pylist fd2obj[FD_SETSIZE + 1])
{
int max = -1;
unsigned int index = 0;
Py_ssize_t i;
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;
for (i = 0; i < PySequence_Fast_GET_SIZE(fast_seq); i++) {
SOCKET v;
/* any intervening fileno() calls could decr this refcnt */
if (!(o = PySequence_Fast_GET_ITEM(fast_seq, i)))
goto finally;
Py_INCREF(o);
v = PyObject_AsFileDescriptor( o );
if (v == -1) goto finally;
#if defined(_MSC_VER)
max = 0; /* not used for Win32 */
#else /* !_MSC_VER */
if (!_PyIsSelectable_fd(v)) {
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 >= (unsigned int)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;
}
/* 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)) {
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;
}
static PyObject *
select_select(PyObject *self, PyObject *args)
{
pylist *rfd2obj, *wfd2obj, *efd2obj;
PyObject *ifdlist, *ofdlist, *efdlist;
PyObject *ret = NULL;
PyObject *timeout_obj = Py_None;
fd_set ifdset, ofdset, efdset;
struct timeval tv, *tvp;
int imax, omax, emax, max;
int n;
_PyTime_t timeout, deadline = 0;
/* convert arguments */
if (!PyArg_UnpackTuple(args, "select", 3, 4,
&ifdlist, &ofdlist, &efdlist, &timeout_obj))
return NULL;
if (timeout_obj == Py_None)
tvp = (struct timeval *)NULL;
else {
if (_PyTime_FromSecondsObject(&timeout, timeout_obj,
_PyTime_ROUND_TIMEOUT) < 0) {
if (PyErr_ExceptionMatches(PyExc_TypeError)) {
PyErr_SetString(PyExc_TypeError,
"timeout must be a float or None");
}
return NULL;
}
if (_PyTime_AsTimeval(timeout, &tv, _PyTime_ROUND_TIMEOUT) == -1)
return NULL;
if (tv.tv_sec < 0) {
PyErr_SetString(PyExc_ValueError, "timeout must be non-negative");
return NULL;
}
tvp = &tv;
}
/* 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();
}
/* 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;
if (tvp)
deadline = _PyTime_GetMonotonicClock() + timeout;
do {
Py_BEGIN_ALLOW_THREADS
errno = 0;
n = select(max, &ifdset, &ofdset, &efdset, tvp);
Py_END_ALLOW_THREADS
if (errno != EINTR)
break;
/* select() was interrupted by a signal */
if (PyErr_CheckSignals())
goto finally;
if (tvp) {
timeout = deadline - _PyTime_GetMonotonicClock();
if (timeout < 0) {
/* bpo-35310: lists were unmodified -- clear them explicitly */
FD_ZERO(&ifdset);
FD_ZERO(&ofdset);
FD_ZERO(&efdset);
n = 0;
break;
}
_PyTime_AsTimeval_noraise(timeout, &tv, _PyTime_ROUND_CEILING);
/* retry select() with the recomputed timeout */
}
} while (1);
#ifdef MS_WINDOWS
if (n == SOCKET_ERROR) {
PyErr_SetExcFromWindowsErr(PyExc_OSError, WSAGetLastError());
}
#else
if (n < 0) {
PyErr_SetFromErrno(PyExc_OSError);
}
#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_XDECREF(ifdlist);
Py_XDECREF(ofdlist);
Py_XDECREF(efdlist);
}
finally:
reap_obj(rfd2obj);
reap_obj(wfd2obj);
reap_obj(efd2obj);
PyMem_DEL(rfd2obj);
PyMem_DEL(wfd2obj);
PyMem_DEL(efd2obj);
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;
int poll_running;
} pollObject;
static PyTypeObject poll_Type;
/* 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)) {
assert(i < self->ufd_len);
/* Never overflow */
self->ufds[i].fd = (int)PyLong_AsLong(key);
self->ufds[i].events = (short)(unsigned short)PyLong_AsLong(value);
i++;
}
assert(i == self->ufd_len);
self->ufd_uptodate = 1;
return 1;
}
static int
ushort_converter(PyObject *obj, void *ptr)
{
unsigned long uval;
uval = PyLong_AsUnsignedLong(obj);
if (uval == (unsigned long)-1 && PyErr_Occurred())
return 0;
if (uval > USHRT_MAX) {
PyErr_SetString(PyExc_OverflowError,
"Python int too large for C unsigned short");
return 0;
}
*(unsigned short *)ptr = Py_SAFE_DOWNCAST(uval, unsigned long, unsigned short);
return 1;
}
PyDoc_STRVAR(poll_register_doc,
"register(fd [, eventmask] ) -> None\n\n\
Register a file descriptor with the polling object.\n\
fd -- either an integer, or an object with a fileno() method returning an\n\
int.\n\
events -- an optional bitmask describing the type of events to check for");
static PyObject *
poll_register(pollObject *self, PyObject *args)
{
PyObject *o, *key, *value;
int fd;
unsigned short events = POLLIN | POLLPRI | POLLOUT;
int err;
if (!PyArg_ParseTuple(args, "O|O&:register", &o, ushort_converter, &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 = PyLong_FromLong(fd);
if (key == NULL)
return NULL;
value = PyLong_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,
"modify(fd, eventmask) -> None\n\n\
Modify an already registered file descriptor.\n\
fd -- either an integer, or an object with a fileno() method returning an\n\
int.\n\
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;
unsigned short events;
int err;
if (!PyArg_ParseTuple(args, "OO&:modify", &o, ushort_converter, &events))
return NULL;
fd = PyObject_AsFileDescriptor(o);
if (fd == -1) return NULL;
/* Modify registered fd */
key = PyLong_FromLong(fd);
if (key == NULL)
return NULL;
if (PyDict_GetItem(self->dict, key) == NULL) {
errno = ENOENT;
PyErr_SetFromErrno(PyExc_OSError);
Py_DECREF(key);
return NULL;
}
value = PyLong_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_unregister_doc,
"unregister(fd) -> None\n\n\
Remove a file descriptor being tracked by the polling object.");
static PyObject *
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 = PyLong_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,
"poll( [timeout] ) -> list of (fd, event) 2-tuples\n\n\
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)
{
PyObject *result_list = NULL, *timeout_obj = NULL;
int poll_result, i, j;
PyObject *value = NULL, *num = NULL;
_PyTime_t timeout = -1, ms = -1, deadline = 0;
int async_err = 0;
if (!PyArg_ParseTuple(args, "|O:poll", &timeout_obj)) {
return NULL;
}
if (timeout_obj != NULL && timeout_obj != Py_None) {
if (_PyTime_FromMillisecondsObject(&timeout, timeout_obj,
_PyTime_ROUND_TIMEOUT) < 0) {
if (PyErr_ExceptionMatches(PyExc_TypeError)) {
PyErr_SetString(PyExc_TypeError,
"timeout must be an integer or None");
}
return NULL;
}
ms = _PyTime_AsMilliseconds(timeout, _PyTime_ROUND_TIMEOUT);
if (ms < INT_MIN || ms > INT_MAX) {
PyErr_SetString(PyExc_OverflowError, "timeout is too large");
return NULL;
}
if (timeout >= 0) {
deadline = _PyTime_GetMonotonicClock() + timeout;
}
}
/* On some OSes, typically BSD-based ones, the timeout parameter of the
poll() syscall, when negative, must be exactly INFTIM, where defined,
or -1. See issue 31334. */
if (ms < 0) {
#ifdef INFTIM
ms = INFTIM;
#else
ms = -1;
#endif
}
/* Avoid concurrent poll() invocation, issue 8865 */
if (self->poll_running) {
PyErr_SetString(PyExc_RuntimeError,
"concurrent poll() invocation");
return NULL;
}
/* Ensure the ufd array is up to date */
if (!self->ufd_uptodate)
if (update_ufd_array(self) == 0)
return NULL;
self->poll_running = 1;
/* call poll() */
async_err = 0;
do {
Py_BEGIN_ALLOW_THREADS
errno = 0;
poll_result = poll(self->ufds, self->ufd_len, (int)ms);
Py_END_ALLOW_THREADS
if (errno != EINTR)
break;
/* poll() was interrupted by a signal */
if (PyErr_CheckSignals()) {
async_err = 1;
break;
}
if (timeout >= 0) {
timeout = deadline - _PyTime_GetMonotonicClock();
if (timeout < 0) {
poll_result = 0;
break;
}
ms = _PyTime_AsMilliseconds(timeout, _PyTime_ROUND_CEILING);
/* retry poll() with the recomputed timeout */
}
} while (1);
self->poll_running = 0;
if (poll_result < 0) {
if (!async_err)
PyErr_SetFromErrno(PyExc_OSError);
return NULL;
}
/* build the result list */
result_list = PyList_New(poll_result);
if (!result_list)
return NULL;
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 = PyLong_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 = PyLong_FromLong(self->ufds[i].revents & 0xffff);
if (num == NULL) {
Py_DECREF(value);
goto error;
}
PyTuple_SET_ITEM(value, 1, num);
PyList_SET_ITEM(result_list, j, value);
i++;
}
return result_list;
error:
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 */
};
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->poll_running = 0;
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);
}
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*/
0, /*tp_getattr*/
0, /*tp_setattr*/
0, /*tp_reserved*/
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*/
poll_methods, /*tp_methods*/
};
#ifdef HAVE_SYS_DEVPOLL_H
typedef struct {
PyObject_HEAD
int fd_devpoll;
int max_n_fds;
int n_fds;
struct pollfd *fds;
} devpollObject;
static PyTypeObject devpoll_Type;
static PyObject *
devpoll_err_closed(void)
{
PyErr_SetString(PyExc_ValueError, "I/O operation on closed devpoll object");
return NULL;
}
static int devpoll_flush(devpollObject *self)
{
int size, n;
if (!self->n_fds) return 0;
size = sizeof(struct pollfd)*self->n_fds;
self->n_fds = 0;
n = _Py_write(self->fd_devpoll, self->fds, size);
if (n == -1)
return -1;
if (n < size) {
/*
** Data writed to /dev/poll is a binary data structure. It is not
** clear what to do if a partial write occurred. For now, raise
** an exception and see if we actually found this problem in
** the wild.
** See http://bugs.python.org/issue6397.
*/
PyErr_Format(PyExc_IOError, "failed to write all pollfds. "
"Please, report at http://bugs.python.org/. "
"Data to report: Size tried: %d, actual size written: %d.",
size, n);
return -1;
}
return 0;
}
static PyObject *
internal_devpoll_register(devpollObject *self, PyObject *args, int remove)
{
PyObject *o;
int fd;
unsigned short events = POLLIN | POLLPRI | POLLOUT;
if (self->fd_devpoll < 0)
return devpoll_err_closed();
if (!PyArg_ParseTuple(args, "O|O&:register", &o, ushort_converter, &events))
return NULL;
fd = PyObject_AsFileDescriptor(o);
if (fd == -1) return NULL;
if (remove) {
self->fds[self->n_fds].fd = fd;
self->fds[self->n_fds].events = POLLREMOVE;
if (++self->n_fds == self->max_n_fds) {
if (devpoll_flush(self))
return NULL;
}
}
self->fds[self->n_fds].fd = fd;
self->fds[self->n_fds].events = (signed short)events;
if (++self->n_fds == self->max_n_fds) {
if (devpoll_flush(self))
return NULL;
}
Py_RETURN_NONE;
}
PyDoc_STRVAR(devpoll_register_doc,
"register(fd [, eventmask] ) -> None\n\n\
Register a file descriptor with the polling object.\n\
fd -- either an integer, or an object with a fileno() method returning an\n\
int.\n\
events -- an optional bitmask describing the type of events to check for");
static PyObject *
devpoll_register(devpollObject *self, PyObject *args)
{
return internal_devpoll_register(self, args, 0);
}
PyDoc_STRVAR(devpoll_modify_doc,
"modify(fd[, eventmask]) -> None\n\n\
Modify a possible already registered file descriptor.\n\
fd -- either an integer, or an object with a fileno() method returning an\n\
int.\n\
events -- an optional bitmask describing the type of events to check for");
static PyObject *
devpoll_modify(devpollObject *self, PyObject *args)
{
return internal_devpoll_register(self, args, 1);
}
PyDoc_STRVAR(devpoll_unregister_doc,
"unregister(fd) -> None\n\n\
Remove a file descriptor being tracked by the polling object.");
static PyObject *
devpoll_unregister(devpollObject *self, PyObject *o)
{
int fd;
if (self->fd_devpoll < 0)
return devpoll_err_closed();
fd = PyObject_AsFileDescriptor( o );
if (fd == -1)
return NULL;
self->fds[self->n_fds].fd = fd;
self->fds[self->n_fds].events = POLLREMOVE;
if (++self->n_fds == self->max_n_fds) {
if (devpoll_flush(self))
return NULL;
}
Py_RETURN_NONE;
}
PyDoc_STRVAR(devpoll_poll_doc,
"poll( [timeout] ) -> list of (fd, event) 2-tuples\n\n\
Polls the set of registered file descriptors, returning a list containing \n\
any descriptors that have events or errors to report.");
static PyObject *
devpoll_poll(devpollObject *self, PyObject *args)
{
struct dvpoll dvp;
PyObject *result_list = NULL, *timeout_obj = NULL;
int poll_result, i;
PyObject *value, *num1, *num2;
_PyTime_t timeout, ms, deadline = 0;
if (self->fd_devpoll < 0)
return devpoll_err_closed();
if (!PyArg_ParseTuple(args, "|O:poll", &timeout_obj)) {
return NULL;
}
/* Check values for timeout */
if (timeout_obj == NULL || timeout_obj == Py_None) {
timeout = -1;
ms = -1;
}
else {
if (_PyTime_FromMillisecondsObject(&timeout, timeout_obj,
_PyTime_ROUND_TIMEOUT) < 0) {
if (PyErr_ExceptionMatches(PyExc_TypeError)) {
PyErr_SetString(PyExc_TypeError,
"timeout must be an integer or None");
}
return NULL;
}
ms = _PyTime_AsMilliseconds(timeout, _PyTime_ROUND_TIMEOUT);
if (ms < -1 || ms > INT_MAX) {
PyErr_SetString(PyExc_OverflowError, "timeout is too large");
return NULL;
}
}
if (devpoll_flush(self))
return NULL;
dvp.dp_fds = self->fds;
dvp.dp_nfds = self->max_n_fds;
dvp.dp_timeout = (int)ms;
if (timeout >= 0)
deadline = _PyTime_GetMonotonicClock() + timeout;
do {
/* call devpoll() */
Py_BEGIN_ALLOW_THREADS
errno = 0;
poll_result = ioctl(self->fd_devpoll, DP_POLL, &dvp);
Py_END_ALLOW_THREADS
if (errno != EINTR)
break;
/* devpoll() was interrupted by a signal */
if (PyErr_CheckSignals())
return NULL;
if (timeout >= 0) {
timeout = deadline - _PyTime_GetMonotonicClock();
if (timeout < 0) {
poll_result = 0;
break;
}
ms = _PyTime_AsMilliseconds(timeout, _PyTime_ROUND_CEILING);
dvp.dp_timeout = (int)ms;
/* retry devpoll() with the recomputed timeout */
}
} while (1);
if (poll_result < 0) {
PyErr_SetFromErrno(PyExc_IOError);
return NULL;
}
/* build the result list */
result_list = PyList_New(poll_result);
if (!result_list)
return NULL;
for (i = 0; i < poll_result; i++) {
num1 = PyLong_FromLong(self->fds[i].fd);
num2 = PyLong_FromLong(self->fds[i].revents);
if ((num1 == NULL) || (num2 == NULL)) {
Py_XDECREF(num1);
Py_XDECREF(num2);
goto error;
}
value = PyTuple_Pack(2, num1, num2);
Py_DECREF(num1);
Py_DECREF(num2);
if (value == NULL)
goto error;
PyList_SET_ITEM(result_list, i, value);
}
return result_list;
error:
Py_DECREF(result_list);
return NULL;
}
static int
devpoll_internal_close(devpollObject *self)
{
int save_errno = 0;
if (self->fd_devpoll >= 0) {
int fd = self->fd_devpoll;
self->fd_devpoll = -1;
Py_BEGIN_ALLOW_THREADS
if (close(fd) < 0)
save_errno = errno;
Py_END_ALLOW_THREADS
}
return save_errno;
}
static PyObject*
devpoll_close(devpollObject *self)
{
errno = devpoll_internal_close(self);
if (errno < 0) {
PyErr_SetFromErrno(PyExc_OSError);
return NULL;
}
Py_RETURN_NONE;
}
PyDoc_STRVAR(devpoll_close_doc,
"close() -> None\n\
\n\
Close the devpoll file descriptor. Further operations on the devpoll\n\
object will raise an exception.");
static PyObject*
devpoll_get_closed(devpollObject *self, void *Py_UNUSED(ignored))
{
if (self->fd_devpoll < 0)
Py_RETURN_TRUE;
else
Py_RETURN_FALSE;
}
static PyObject*
devpoll_fileno(devpollObject *self)
{
if (self->fd_devpoll < 0)
return devpoll_err_closed();
return PyLong_FromLong(self->fd_devpoll);
}
PyDoc_STRVAR(devpoll_fileno_doc,
"fileno() -> int\n\
\n\
Return the file descriptor.");
static PyMethodDef devpoll_methods[] = {
{"register", (PyCFunction)devpoll_register,
METH_VARARGS, devpoll_register_doc},
{"modify", (PyCFunction)devpoll_modify,
METH_VARARGS, devpoll_modify_doc},
{"unregister", (PyCFunction)devpoll_unregister,
METH_O, devpoll_unregister_doc},
{"poll", (PyCFunction)devpoll_poll,
METH_VARARGS, devpoll_poll_doc},
{"close", (PyCFunction)devpoll_close, METH_NOARGS,
devpoll_close_doc},
{"fileno", (PyCFunction)devpoll_fileno, METH_NOARGS,
devpoll_fileno_doc},
{NULL, NULL} /* sentinel */
};
static PyGetSetDef devpoll_getsetlist[] = {
{"closed", (getter)devpoll_get_closed, NULL,
"True if the devpoll object is closed"},
{0},
};
static devpollObject *
newDevPollObject(void)
{
devpollObject *self;
int fd_devpoll, limit_result;
struct pollfd *fds;
struct rlimit limit;
/*
** If we try to process more that getrlimit()
** fds, the kernel will give an error, so
** we set the limit here. It is a dynamic
** value, because we can change rlimit() anytime.
*/
limit_result = getrlimit(RLIMIT_NOFILE, &limit);
if (limit_result == -1) {
PyErr_SetFromErrno(PyExc_OSError);
return NULL;
}
fd_devpoll = _Py_open("/dev/poll", O_RDWR);
if (fd_devpoll == -1)
return NULL;
fds = PyMem_NEW(struct pollfd, limit.rlim_cur);
if (fds == NULL) {
close(fd_devpoll);
PyErr_NoMemory();
return NULL;
}
self = PyObject_New(devpollObject, &devpoll_Type);
if (self == NULL) {
close(fd_devpoll);
PyMem_DEL(fds);
return NULL;
}
self->fd_devpoll = fd_devpoll;
self->max_n_fds = limit.rlim_cur;
self->n_fds = 0;
self->fds = fds;
return self;
}
static void
devpoll_dealloc(devpollObject *self)
{
(void)devpoll_internal_close(self);
PyMem_DEL(self->fds);
PyObject_Del(self);
}
static PyTypeObject devpoll_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.devpoll", /*tp_name*/
sizeof(devpollObject), /*tp_basicsize*/
0, /*tp_itemsize*/
/* methods */
(destructor)devpoll_dealloc, /*tp_dealloc*/
0, /*tp_print*/
0, /*tp_getattr*/
0, /*tp_setattr*/
0, /*tp_reserved*/
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*/
devpoll_methods, /*tp_methods*/
0, /* tp_members */
devpoll_getsetlist, /* tp_getset */
};
#endif /* HAVE_SYS_DEVPOLL_H */
PyDoc_STRVAR(poll_doc,
"Returns a polling object, which supports registering and\n\
unregistering file descriptors, and then polling them for I/O events.");
static PyObject *
select_poll(PyObject *self, PyObject *unused)
{
return (PyObject *)newPollObject();
}
#ifdef HAVE_SYS_DEVPOLL_H
PyDoc_STRVAR(devpoll_doc,
"Returns a polling object, which supports registering and\n\
unregistering file descriptors, and then polling them for I/O events.");
static PyObject *
select_devpoll(PyObject *self, PyObject *unused)
{
return (PyObject *)newDevPollObject();
}
#endif
#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;
}
#endif /* __APPLE__ */
#endif /* HAVE_POLL */
#ifdef HAVE_EPOLL
/* **************************************************************************
* epoll interface for Linux 2.6
*
* Written by Christian Heimes
* Inspired by Twisted's _epoll.pyx and select.poll()
*/
typedef struct {
PyObject_HEAD
SOCKET epfd; /* epoll control file descriptor */
} pyEpoll_Object;
static PyTypeObject pyEpoll_Type;
#define pyepoll_CHECK(op) (PyObject_TypeCheck((op), &pyEpoll_Type))
static PyObject *
pyepoll_err_closed(void)
{
PyErr_SetString(PyExc_ValueError, "I/O operation on closed epoll object");
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;
}
static PyObject *
newPyEpoll_Object(PyTypeObject *type, int sizehint, int flags, SOCKET fd)
{
pyEpoll_Object *self;
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
#ifdef HAVE_EPOLL_CREATE1
flags |= EPOLL_CLOEXEC;
if (flags)
self->epfd = epoll_create1(flags);
else
#endif
self->epfd = epoll_create(sizehint);
Py_END_ALLOW_THREADS
}
else {
self->epfd = fd;
}
if (self->epfd < 0) {
Py_DECREF(self);
PyErr_SetFromErrno(PyExc_OSError);
return NULL;
}
#ifndef HAVE_EPOLL_CREATE1
if (fd == -1 && _Py_set_inheritable(self->epfd, 0, NULL) < 0) {
Py_DECREF(self);
return NULL;
}
#endif
return (PyObject *)self;
}
static PyObject *
pyepoll_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
int flags = 0, sizehint = -1;
static char *kwlist[] = {"sizehint", "flags", NULL};
if (!PyArg_ParseTupleAndKeywords(args, kwds, "|ii:epoll", kwlist,
&sizehint, &flags))
return NULL;
if (sizehint == -1) {
sizehint = FD_SETSIZE - 1;
}
else if (sizehint <= 0) {
PyErr_SetString(PyExc_ValueError, "sizehint must be positive or -1");
return NULL;
}
return newPyEpoll_Object(type, sizehint, flags, -1);
}
static void
pyepoll_dealloc(pyEpoll_Object *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_OSError);
return NULL;
}
Py_RETURN_NONE;
}
PyDoc_STRVAR(pyepoll_close_doc,
"close() -> None\n\
\n\
Close the epoll control file descriptor. Further operations on the epoll\n\
object will raise an exception.");
static PyObject*
pyepoll_get_closed(pyEpoll_Object *self, void *Py_UNUSED(ignored))
{
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 PyLong_FromLong(self->epfd);
}
PyDoc_STRVAR(pyepoll_fileno_doc,
"fileno() -> int\n\
\n\
Return the epoll control file descriptor.");
static PyObject*
pyepoll_fromfd(PyObject *cls, PyObject *args)
{
SOCKET fd;
if (!PyArg_ParseTuple(args, "i:fromfd", &fd))
return NULL;
return newPyEpoll_Object((PyTypeObject*)cls, FD_SETSIZE - 1, 0, fd);
}
PyDoc_STRVAR(pyepoll_fromfd_doc,
"fromfd(fd) -> epoll\n\
\n\
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_OSError);
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};
if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|I:register", kwlist,
&pfd, &events)) {
return NULL;
}
return pyepoll_internal_ctl(self->epfd, EPOLL_CTL_ADD, pfd, events);
}
PyDoc_STRVAR(pyepoll_register_doc,
"register(fd[, eventmask]) -> None\n\
\n\
Registers a new fd or raises an OSError if the fd is already registered.\n\
fd is the target file descriptor of the operation.\n\
events is a bit set composed of the various EPOLL constants; the default\n\
is EPOLLIN | EPOLLOUT | EPOLLPRI.\n\
\n\
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};
if (!PyArg_ParseTupleAndKeywords(args, kwds, "OI:modify", kwlist,
&pfd, &events)) {
return NULL;
}
return pyepoll_internal_ctl(self->epfd, EPOLL_CTL_MOD, pfd, events);
}
PyDoc_STRVAR(pyepoll_modify_doc,
"modify(fd, eventmask) -> None\n\
\n\
fd is the target file descriptor of the operation\n\
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};
if (!PyArg_ParseTupleAndKeywords(args, kwds, "O:unregister", kwlist,
&pfd)) {
return NULL;
}
return pyepoll_internal_ctl(self->epfd, EPOLL_CTL_DEL, pfd, 0);
}
PyDoc_STRVAR(pyepoll_unregister_doc,
"unregister(fd) -> None\n\
\n\
fd is the target file descriptor of the operation.");
static PyObject *
pyepoll_poll(pyEpoll_Object *self, PyObject *args, PyObject *kwds)
{
static char *kwlist[] = {"timeout", "maxevents", NULL};
PyObject *timeout_obj = NULL;
int maxevents = -1;
int nfds, i;
PyObject *elist = NULL, *etuple = NULL;
struct epoll_event *evs = NULL;
_PyTime_t timeout, ms, deadline;
if (self->epfd < 0)
return pyepoll_err_closed();
if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oi:poll", kwlist,
&timeout_obj, &maxevents)) {
return NULL;
}
if (timeout_obj == NULL || timeout_obj == Py_None) {
timeout = -1;
ms = -1;
deadline = 0; /* initialize to prevent gcc warning */
}
else {
/* epoll_wait() has a resolution of 1 millisecond, round towards
infinity to wait at least timeout seconds. */
if (_PyTime_FromSecondsObject(&timeout, timeout_obj,
_PyTime_ROUND_TIMEOUT) < 0) {
if (PyErr_ExceptionMatches(PyExc_TypeError)) {
PyErr_SetString(PyExc_TypeError,
"timeout must be an integer or None");
}
return NULL;
}
ms = _PyTime_AsMilliseconds(timeout, _PyTime_ROUND_CEILING);
if (ms < INT_MIN || ms > INT_MAX) {
PyErr_SetString(PyExc_OverflowError, "timeout is too large");
return NULL;
}
deadline = _PyTime_GetMonotonicClock() + timeout;
}
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) {
PyErr_NoMemory();
return NULL;
}
do {
Py_BEGIN_ALLOW_THREADS
errno = 0;
nfds = epoll_wait(self->epfd, evs, maxevents, (int)ms);
Py_END_ALLOW_THREADS
if (errno != EINTR)
break;
/* poll() was interrupted by a signal */
if (PyErr_CheckSignals())
goto error;
if (timeout >= 0) {
timeout = deadline - _PyTime_GetMonotonicClock();
if (timeout < 0) {
nfds = 0;
break;
}
ms = _PyTime_AsMilliseconds(timeout, _PyTime_ROUND_CEILING);
/* retry epoll_wait() with the recomputed timeout */
}
} while(1);
if (nfds < 0) {
PyErr_SetFromErrno(PyExc_OSError);
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;
}
PyDoc_STRVAR(pyepoll_poll_doc,
"poll([timeout=-1[, maxevents=-1]]) -> [(fd, events), (...)]\n\
\n\
Wait for events on the epoll file descriptor for a maximum time of timeout\n\
in seconds (as float). -1 makes poll wait indefinitely.\n\
Up to maxevents are returned to the caller.");
static PyObject *
pyepoll_enter(pyEpoll_Object *self, PyObject *args)
{
if (self->epfd < 0)
return pyepoll_err_closed();
Py_INCREF(self);
return (PyObject *)self;
}
static PyObject *
pyepoll_exit(PyObject *self, PyObject *args)
{
_Py_IDENTIFIER(close);
return _PyObject_CallMethodId(self, &PyId_close, NULL);
}
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},
{"__enter__", (PyCFunction)pyepoll_enter, METH_NOARGS,
NULL},
{"__exit__", (PyCFunction)pyepoll_exit, METH_VARARGS,
NULL},
{NULL, NULL},
};
static PyGetSetDef pyepoll_getsetlist[] = {
{"closed", (getter)pyepoll_get_closed, NULL,
"True if the epoll handler is closed"},
{0},
};
PyDoc_STRVAR(pyepoll_doc,
"select.epoll(sizehint=-1, flags=0)\n\
\n\
Returns an epolling object\n\
\n\
sizehint must be a positive integer or -1 for the default size. The\n\
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_reserved */
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 */
#ifdef HAVE_KQUEUE
/* **************************************************************************
* kqueue interface for BSD
*
* Copyright (c) 2000 Doug White, 2006 James Knight, 2007 Christian Heimes
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
#ifdef HAVE_SYS_EVENT_H
#include <sys/event.h>
#endif
PyDoc_STRVAR(kqueue_event_doc,
"kevent(ident, filter=KQ_FILTER_READ, flags=KQ_EV_ADD, fflags=0, data=0, udata=0)\n\
\n\
This object is the equivalent of the struct kevent for the C API.\n\
\n\
See the kqueue manpage for more detailed information about the meaning\n\
of the arguments.\n\
\n\
One minor note: while you might hope that udata could store a\n\
reference to a python object, it cannot, because it is impossible to\n\
keep a proper reference count of the object once it's passed into the\n\
kernel. Therefore, I have restricted it to only storing an integer. I\n\
recommend ignoring it and simply using the 'ident' field to key off\n\
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;
} kqueue_event_Object;
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 */
} kqueue_queue_Object;
static PyTypeObject kqueue_queue_Type;
#define kqueue_queue_Check(op) (PyObject_TypeCheck((op), &kqueue_queue_Type))
#if (SIZEOF_UINTPTR_T != SIZEOF_VOID_P)
# error uintptr_t does not match void *!
#elif (SIZEOF_UINTPTR_T == SIZEOF_LONG_LONG)
# define T_UINTPTRT T_ULONGLONG
# define T_INTPTRT T_LONGLONG
# define UINTPTRT_FMT_UNIT "K"
# define INTPTRT_FMT_UNIT "L"
#elif (SIZEOF_UINTPTR_T == SIZEOF_LONG)
# define T_UINTPTRT T_ULONG
# define T_INTPTRT T_LONG
# define UINTPTRT_FMT_UNIT "k"
# define INTPTRT_FMT_UNIT "l"
#elif (SIZEOF_UINTPTR_T == SIZEOF_INT)
# define T_UINTPTRT T_UINT
# define T_INTPTRT T_INT
# define UINTPTRT_FMT_UNIT "I"
# define INTPTRT_FMT_UNIT "i"
#else
# error uintptr_t does not match int, long, or long long!
#endif
#if SIZEOF_LONG_LONG == 8
# define T_INT64 T_LONGLONG
# define INT64_FMT_UNIT "L"
#elif SIZEOF_LONG == 8
# define T_INT64 T_LONG
# define INT64_FMT_UNIT "l"
#elif SIZEOF_INT == 8
# define T_INT64 T_INT
# define INT64_FMT_UNIT "i"
#else
# define INT64_FMT_UNIT "_"
#endif
#if SIZEOF_LONG_LONG == 4
# define T_UINT32 T_ULONGLONG
# define UINT32_FMT_UNIT "K"
#elif SIZEOF_LONG == 4
# define T_UINT32 T_ULONG
# define UINT32_FMT_UNIT "k"
#elif SIZEOF_INT == 4
# define T_UINT32 T_UINT
# define UINT32_FMT_UNIT "I"
#else
# define UINT32_FMT_UNIT "_"
#endif
/*
* kevent is not standard and its members vary across BSDs.
*/
#ifdef __NetBSD__
# define FILTER_TYPE T_UINT32
# define FILTER_FMT_UNIT UINT32_FMT_UNIT
# define FLAGS_TYPE T_UINT32
# define FLAGS_FMT_UNIT UINT32_FMT_UNIT
# define FFLAGS_TYPE T_UINT32
# define FFLAGS_FMT_UNIT UINT32_FMT_UNIT
#else
# define FILTER_TYPE T_SHORT
# define FILTER_FMT_UNIT "h"
# define FLAGS_TYPE T_USHORT
# define FLAGS_FMT_UNIT "H"
# define FFLAGS_TYPE T_UINT
# define FFLAGS_FMT_UNIT "I"
#endif
#if defined(__NetBSD__) || defined(__OpenBSD__)
# define DATA_TYPE T_INT64
# define DATA_FMT_UNIT INT64_FMT_UNIT
#else
# define DATA_TYPE T_INTPTRT
# define DATA_FMT_UNIT INTPTRT_FMT_UNIT
#endif
/* Unfortunately, we can't store python objects in udata, because
* kevents in the kernel can be removed without warning, which would
* forever lose the refcount on the object stored with it.
*/
#define KQ_OFF(x) offsetof(kqueue_event_Object, x)
static struct PyMemberDef kqueue_event_members[] = {
{"ident", T_UINTPTRT, KQ_OFF(e.ident)},
{"filter", FILTER_TYPE, KQ_OFF(e.filter)},
{"flags", FLAGS_TYPE, KQ_OFF(e.flags)},
{"fflags", T_UINT, KQ_OFF(e.fflags)},
{"data", DATA_TYPE, KQ_OFF(e.data)},
{"udata", T_UINTPTRT, KQ_OFF(e.udata)},
{NULL} /* Sentinel */
};
#undef KQ_OFF
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%llx udata=%p>",
(size_t)(s->e.ident), (int)s->e.filter, (unsigned int)s->e.flags,
(unsigned int)s->e.fflags, (long long)(s->e.data), (void *)s->e.udata);
return PyUnicode_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 const char fmt[] = "O|"
FILTER_FMT_UNIT FLAGS_FMT_UNIT FFLAGS_FMT_UNIT DATA_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_AsSize_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 result;
if (!kqueue_event_Check(o)) {
Py_RETURN_NOTIMPLEMENTED;
}
#define CMP(a, b) ((a) != (b)) ? ((a) < (b) ? -1 : 1)
result = CMP(s->e.ident, o->e.ident)
: CMP(s->e.filter, o->e.filter)
: CMP(s->e.flags, o->e.flags)
: CMP(s->e.fflags, o->e.fflags)
: CMP(s->e.data, o->e.data)
: CMP((intptr_t)s->e.udata, (intptr_t)o->e.udata)
: 0;
#undef CMP
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_reserved */
(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 object");
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;
}
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_OSError);
return NULL;
}
if (fd == -1) {
if (_Py_set_inheritable(self->kqfd, 0, NULL) < 0) {
Py_DECREF(self);
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;
}
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);
}
static PyObject*
kqueue_queue_close(kqueue_queue_Object *self)
{
errno = kqueue_queue_internal_close(self);
if (errno < 0) {
PyErr_SetFromErrno(PyExc_OSError);
return NULL;
}
Py_RETURN_NONE;
}
PyDoc_STRVAR(kqueue_queue_close_doc,
"close() -> None\n\
\n\
Close the kqueue control file descriptor. Further operations on the kqueue\n\
object will raise an exception.");
static PyObject*
kqueue_queue_get_closed(kqueue_queue_Object *self, void *Py_UNUSED(ignored))
{
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 PyLong_FromLong(self->kqfd);
}
PyDoc_STRVAR(kqueue_queue_fileno_doc,
"fileno() -> int\n\
\n\
Return the kqueue control file descriptor.");
static PyObject*
kqueue_queue_fromfd(PyObject *cls, PyObject *args)
{
SOCKET fd;
if (!PyArg_ParseTuple(args, "i:fromfd", &fd))
return NULL;
return newKqueue_Object((PyTypeObject*)cls, fd);
}
PyDoc_STRVAR(kqueue_queue_fromfd_doc,
"fromfd(fd) -> kqueue\n\
\n\
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 *seq = NULL, *ei = NULL;
PyObject *result = NULL;
struct kevent *evl = NULL;
struct kevent *chl = NULL;
struct timespec timeoutspec;
struct timespec *ptimeoutspec;
_PyTime_t timeout, deadline = 0;
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 (_PyTime_FromSecondsObject(&timeout,
otimeout, _PyTime_ROUND_TIMEOUT) < 0) {
PyErr_Format(PyExc_TypeError,
"timeout argument must be a number "
"or None, got %.200s",
Py_TYPE(otimeout)->tp_name);
return NULL;
}
if (_PyTime_AsTimespec(timeout, &timeoutspec) == -1)
return NULL;
if (timeoutspec.tv_sec < 0) {
PyErr_SetString(PyExc_ValueError,
"timeout must be positive or None");
return NULL;
}
ptimeoutspec = &timeoutspec;
}
if (ch != NULL && ch != Py_None) {
seq = PySequence_Fast(ch, "changelist is not iterable");
if (seq == NULL) {
return NULL;
}
if (PySequence_Fast_GET_SIZE(seq) > INT_MAX) {
PyErr_SetString(PyExc_OverflowError,
"changelist is too long");
goto error;
}
nchanges = (int)PySequence_Fast_GET_SIZE(seq);
chl = PyMem_New(struct kevent, nchanges);
if (chl == NULL) {
PyErr_NoMemory();
goto error;
}
for (i = 0; i < nchanges; ++i) {
ei = PySequence_Fast_GET_ITEM(seq, i);
if (!kqueue_event_Check(ei)) {
PyErr_SetString(PyExc_TypeError,
"changelist must be an iterable of "
"select.kevent objects");
goto error;
}
chl[i] = ((kqueue_event_Object *)ei)->e;
}
Py_CLEAR(seq);
}
/* event list */
if (nevents) {
evl = PyMem_New(struct kevent, nevents);
if (evl == NULL) {
PyErr_NoMemory();
goto error;
}
}
if (ptimeoutspec)
deadline = _PyTime_GetMonotonicClock() + timeout;
do {
Py_BEGIN_ALLOW_THREADS
errno = 0;
gotevents = kevent(self->kqfd, chl, nchanges,
evl, nevents, ptimeoutspec);
Py_END_ALLOW_THREADS
if (errno != EINTR)
break;
/* kevent() was interrupted by a signal */
if (PyErr_CheckSignals())
goto error;
if (ptimeoutspec) {
timeout = deadline - _PyTime_GetMonotonicClock();
if (timeout < 0) {
gotevents = 0;
break;
}
if (_PyTime_AsTimespec(timeout, &timeoutspec) == -1)
goto error;
/* retry kevent() with the recomputed timeout */
}
} while (1);
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(seq);
return NULL;
}
PyDoc_STRVAR(kqueue_queue_control_doc,
"control(changelist, max_events[, timeout=None]) -> eventlist\n\
\n\
Calls the kernel kevent function.\n\
- changelist must be an iterable of kevent objects describing the changes\n\
to be made to the kernel's watch list or None.\n\
- max_events lets you specify the maximum number of events that the\n\
kernel will return.\n\
- timeout is the maximum time to wait in seconds, or else None,\n\
to wait forever. timeout accepts floats for smaller timeouts, too.");
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},
};
static PyGetSetDef kqueue_queue_getsetlist[] = {
{"closed", (getter)kqueue_queue_get_closed, NULL,
"True if the kqueue handler is closed"},
{0},
};
PyDoc_STRVAR(kqueue_queue_doc,
"Kqueue syscall wrapper.\n\
\n\
For example, to start watching a socket for input:\n\
>>> kq = kqueue()\n\
>>> sock = socket()\n\
>>> sock.connect((host, port))\n\
>>> kq.control([kevent(sock, KQ_FILTER_WRITE, KQ_EV_ADD)], 0)\n\
\n\
To wait one second for it to become writeable:\n\
>>> kq.control(None, 1, 1000)\n\
\n\
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_reserved */
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 */
/* ************************************************************************ */
PyDoc_STRVAR(select_doc,
"select(rlist, wlist, xlist[, timeout]) -> (rlist, wlist, xlist)\n\
\n\
Wait until one or more file descriptors are ready for some kind of I/O.\n\
The first three arguments are sequences of file descriptors to be waited for:\n\
rlist -- wait until ready for reading\n\
wlist -- wait until ready for writing\n\
xlist -- wait for an ``exceptional condition''\n\
If only one kind of condition is required, pass [] for the other lists.\n\
A file descriptor is either a socket or file object, or a small integer\n\
gotten from a fileno() method call on one of those.\n\
\n\
The optional 4th argument specifies a timeout in seconds; it may be\n\
a floating point number to specify fractions of seconds. If it is absent\n\
or None, the call will never time out.\n\
\n\
The return value is a tuple of three lists corresponding to the first three\n\
arguments; each contains the subset of the corresponding file descriptors\n\
that are ready.\n\
\n\
*** IMPORTANT NOTICE ***\n\
On Windows, only sockets are supported; on Unix, all file\n\
descriptors can be used.");
static PyMethodDef select_methods[] = {
{"select", select_select, METH_VARARGS, select_doc},
#if defined(HAVE_POLL) && !defined(HAVE_BROKEN_POLL)
{"poll", select_poll, METH_NOARGS, poll_doc},
#endif /* HAVE_POLL */
#ifdef HAVE_SYS_DEVPOLL_H
{"devpoll", select_devpoll, METH_NOARGS, devpoll_doc},
#endif
{0, 0}, /* sentinel */
};
PyDoc_STRVAR(module_doc,
"This module supports asynchronous I/O on multiple file descriptors.\n\
\n\
*** IMPORTANT NOTICE ***\n\
On Windows, only sockets are supported; on Unix, all file descriptors.");
static struct PyModuleDef selectmodule = {
PyModuleDef_HEAD_INIT,
"select",
module_doc,
-1,
select_methods,
NULL,
NULL,
NULL,
NULL
};
PyMODINIT_FUNC
PyInit_select(void)
{
PyObject *m;
m = PyModule_Create(&selectmodule);
if (m == NULL)
return NULL;
Py_INCREF(PyExc_OSError);
PyModule_AddObject(m, "error", PyExc_OSError);
#ifdef PIPE_BUF
#ifdef HAVE_BROKEN_PIPE_BUF
#undef PIPE_BUF
#define PIPE_BUF 512
#endif
PyModule_AddIntMacro(m, PIPE_BUF);
#endif
#if defined(HAVE_POLL) && !defined(HAVE_BROKEN_POLL)
#ifdef __APPLE__
if (select_have_broken_poll()) {
if (PyObject_DelAttrString(m, "poll") == -1) {
PyErr_Clear();
}
} else {
#else
{
#endif
if (PyType_Ready(&poll_Type) < 0)
return NULL;
PyModule_AddIntMacro(m, POLLIN);
PyModule_AddIntMacro(m, POLLPRI);
PyModule_AddIntMacro(m, POLLOUT);
PyModule_AddIntMacro(m, POLLERR);
PyModule_AddIntMacro(m, POLLHUP);
PyModule_AddIntMacro(m, POLLNVAL);
#ifdef POLLRDNORM
PyModule_AddIntMacro(m, POLLRDNORM);
#endif
#ifdef POLLRDBAND
PyModule_AddIntMacro(m, POLLRDBAND);
#endif
#ifdef POLLWRNORM
PyModule_AddIntMacro(m, POLLWRNORM);
#endif
#ifdef POLLWRBAND
PyModule_AddIntMacro(m, POLLWRBAND);
#endif
#ifdef POLLMSG
PyModule_AddIntMacro(m, POLLMSG);
#endif
#ifdef POLLRDHUP
/* Kernel 2.6.17+ */
PyModule_AddIntMacro(m, POLLRDHUP);
#endif
}
#endif /* HAVE_POLL */
#ifdef HAVE_SYS_DEVPOLL_H
if (PyType_Ready(&devpoll_Type) < 0)
return NULL;
#endif
#ifdef HAVE_EPOLL
if (IsLinux() || IsWindows()) {
Py_TYPE(&pyEpoll_Type) = &PyType_Type;
if (PyType_Ready(&pyEpoll_Type) < 0)
return NULL;
Py_INCREF(&pyEpoll_Type);
PyModule_AddObject(m, "epoll", (PyObject *)&pyEpoll_Type);
PyModule_AddIntMacro(m, EPOLLIN);
PyModule_AddIntMacro(m, EPOLLOUT);
PyModule_AddIntMacro(m, EPOLLPRI);
PyModule_AddIntMacro(m, EPOLLERR);
PyModule_AddIntMacro(m, EPOLLHUP);
PyModule_AddIntMacro(m, EPOLLET);
PyModule_AddIntMacro(m, EPOLLEXCLUSIVE);
PyModule_AddIntMacro(m, EPOLLRDNORM);
PyModule_AddIntMacro(m, EPOLLRDBAND);
PyModule_AddIntMacro(m, EPOLLWRNORM);
PyModule_AddIntMacro(m, EPOLLWRBAND);
PyModule_AddIntMacro(m, EPOLLMSG);
PyModule_AddIntMacro(m, EPOLL_CLOEXEC);
PyModule_AddIntMacro(m, EPOLLONESHOT);
PyModule_AddIntMacro(m, EPOLLRDHUP);
}
#endif
#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 NULL;
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 NULL;
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);
#ifdef EVFILT_AIO
PyModule_AddIntConstant(m, "KQ_FILTER_AIO", EVFILT_AIO);
#endif
#ifdef EVFILT_VNODE
PyModule_AddIntConstant(m, "KQ_FILTER_VNODE", EVFILT_VNODE);
#endif
#ifdef EVFILT_PROC
PyModule_AddIntConstant(m, "KQ_FILTER_PROC", EVFILT_PROC);
#endif
#ifdef EVFILT_NETDEV
PyModule_AddIntConstant(m, "KQ_FILTER_NETDEV", EVFILT_NETDEV);
#endif
#ifdef EVFILT_SIGNAL
PyModule_AddIntConstant(m, "KQ_FILTER_SIGNAL", EVFILT_SIGNAL);
#endif
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);
#ifdef EV_SYSFLAGS
PyModule_AddIntConstant(m, "KQ_EV_SYSFLAGS", EV_SYSFLAGS);
#endif
#ifdef EV_FLAG1
PyModule_AddIntConstant(m, "KQ_EV_FLAG1", EV_FLAG1);
#endif
PyModule_AddIntConstant(m, "KQ_EV_EOF", EV_EOF);
PyModule_AddIntConstant(m, "KQ_EV_ERROR", EV_ERROR);
/* READ WRITE filter flag */
#ifdef NOTE_LOWAT
PyModule_AddIntConstant(m, "KQ_NOTE_LOWAT", NOTE_LOWAT);
#endif
/* VNODE filter flags */
#ifdef EVFILT_VNODE
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);
#endif
/* PROC filter flags */
#ifdef EVFILT_PROC
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);
#endif
/* 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);
#endif
#endif /* HAVE_KQUEUE */
return m;
}
_Section(".rodata.pytab.1") const struct _inittab _PyImport_Inittab_select = {
"select",
PyInit_select,
};
| 79,534 | 2,612 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Modules/errnomodule.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:8;coding:utf-8 -*-â
âvi: set net ft=c ts=4 sts=4 sw=4 fenc=utf-8 :viâ
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ¡
â Python 3 â
â https://docs.python.org/3/license.html â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
#include "libc/dce.h"
#include "libc/errno.h"
#include "libc/nt/errors.h"
#include "third_party/python/Include/dictobject.h"
#include "third_party/python/Include/import.h"
#include "third_party/python/Include/longobject.h"
#include "third_party/python/Include/methodobject.h"
#include "third_party/python/Include/modsupport.h"
#include "third_party/python/Include/moduleobject.h"
#include "third_party/python/Include/object.h"
#include "third_party/python/Include/pymacro.h"
#include "third_party/python/Include/unicodeobject.h"
#include "third_party/python/Include/yoink.h"
/* clang-format off */
PYTHON_PROVIDE("errno");
PYTHON_PROVIDE("errno.E2BIG");
PYTHON_PROVIDE("errno.EACCES");
PYTHON_PROVIDE("errno.EADDRINUSE");
PYTHON_PROVIDE("errno.EADDRNOTAVAIL");
PYTHON_PROVIDE("errno.EADV");
PYTHON_PROVIDE("errno.EAFNOSUPPORT");
PYTHON_PROVIDE("errno.EAGAIN");
PYTHON_PROVIDE("errno.EALREADY");
PYTHON_PROVIDE("errno.EBADE");
PYTHON_PROVIDE("errno.EBADF");
PYTHON_PROVIDE("errno.EBADFD");
PYTHON_PROVIDE("errno.EBADMSG");
PYTHON_PROVIDE("errno.EBADR");
PYTHON_PROVIDE("errno.EBADRQC");
PYTHON_PROVIDE("errno.EBADSLT");
PYTHON_PROVIDE("errno.EBUSY");
PYTHON_PROVIDE("errno.ECANCELED");
PYTHON_PROVIDE("errno.ECHILD");
PYTHON_PROVIDE("errno.ECHRNG");
PYTHON_PROVIDE("errno.ECOMM");
PYTHON_PROVIDE("errno.ECONNABORTED");
PYTHON_PROVIDE("errno.ECONNREFUSED");
PYTHON_PROVIDE("errno.ECONNRESET");
PYTHON_PROVIDE("errno.EDEADLK");
PYTHON_PROVIDE("errno.EDESTADDRREQ");
PYTHON_PROVIDE("errno.EDOM");
PYTHON_PROVIDE("errno.EDOTDOT");
PYTHON_PROVIDE("errno.EDQUOT");
PYTHON_PROVIDE("errno.EEXIST");
PYTHON_PROVIDE("errno.EFAULT");
PYTHON_PROVIDE("errno.EFBIG");
PYTHON_PROVIDE("errno.EHOSTDOWN");
PYTHON_PROVIDE("errno.EHOSTUNREACH");
PYTHON_PROVIDE("errno.EIDRM");
PYTHON_PROVIDE("errno.EILSEQ");
PYTHON_PROVIDE("errno.EINPROGRESS");
PYTHON_PROVIDE("errno.EINTR");
PYTHON_PROVIDE("errno.EINVAL");
PYTHON_PROVIDE("errno.EIO");
PYTHON_PROVIDE("errno.EISCONN");
PYTHON_PROVIDE("errno.EISDIR");
PYTHON_PROVIDE("errno.EISNAM");
PYTHON_PROVIDE("errno.EKEYEXPIRED");
PYTHON_PROVIDE("errno.EKEYREJECTED");
PYTHON_PROVIDE("errno.EKEYREVOKED");
PYTHON_PROVIDE("errno.EL2HLT");
PYTHON_PROVIDE("errno.EL2NSYNC");
PYTHON_PROVIDE("errno.EL3HLT");
PYTHON_PROVIDE("errno.EL3RST");
PYTHON_PROVIDE("errno.ELIBACC");
PYTHON_PROVIDE("errno.ELIBBAD");
PYTHON_PROVIDE("errno.ELIBEXEC");
PYTHON_PROVIDE("errno.ELIBMAX");
PYTHON_PROVIDE("errno.ELIBSCN");
PYTHON_PROVIDE("errno.ELNRNG");
PYTHON_PROVIDE("errno.ELOOP");
PYTHON_PROVIDE("errno.EMEDIUMTYPE");
PYTHON_PROVIDE("errno.EMFILE");
PYTHON_PROVIDE("errno.EMLINK");
PYTHON_PROVIDE("errno.EMSGSIZE");
PYTHON_PROVIDE("errno.EMULTIHOP");
PYTHON_PROVIDE("errno.ENAMETOOLONG");
PYTHON_PROVIDE("errno.ENAVAIL");
PYTHON_PROVIDE("errno.ENETDOWN");
PYTHON_PROVIDE("errno.ENETRESET");
PYTHON_PROVIDE("errno.ENETUNREACH");
PYTHON_PROVIDE("errno.ENFILE");
PYTHON_PROVIDE("errno.ENOANO");
PYTHON_PROVIDE("errno.ENOBUFS");
PYTHON_PROVIDE("errno.ENOCSI");
PYTHON_PROVIDE("errno.ENODATA");
PYTHON_PROVIDE("errno.ENODEV");
PYTHON_PROVIDE("errno.ENOENT");
PYTHON_PROVIDE("errno.ENOEXEC");
PYTHON_PROVIDE("errno.ENOKEY");
PYTHON_PROVIDE("errno.ENOLCK");
PYTHON_PROVIDE("errno.ENOLINK");
PYTHON_PROVIDE("errno.ENOMEDIUM");
PYTHON_PROVIDE("errno.ENOMEM");
PYTHON_PROVIDE("errno.ENOMSG");
PYTHON_PROVIDE("errno.ENONET");
PYTHON_PROVIDE("errno.ENOPKG");
PYTHON_PROVIDE("errno.ENOPROTOOPT");
PYTHON_PROVIDE("errno.ENOSPC");
PYTHON_PROVIDE("errno.ENOSR");
PYTHON_PROVIDE("errno.ENOSTR");
PYTHON_PROVIDE("errno.ENOSYS");
PYTHON_PROVIDE("errno.ENOTBLK");
PYTHON_PROVIDE("errno.ENOTCONN");
PYTHON_PROVIDE("errno.ENOTDIR");
PYTHON_PROVIDE("errno.ENOTEMPTY");
PYTHON_PROVIDE("errno.ENOTNAM");
PYTHON_PROVIDE("errno.ENOTRECOVERABLE");
PYTHON_PROVIDE("errno.ENOTSOCK");
PYTHON_PROVIDE("errno.ENOTSUP");
PYTHON_PROVIDE("errno.ENOTTY");
PYTHON_PROVIDE("errno.ENOTUNIQ");
PYTHON_PROVIDE("errno.ENXIO");
PYTHON_PROVIDE("errno.EOPNOTSUPP");
PYTHON_PROVIDE("errno.EOVERFLOW");
PYTHON_PROVIDE("errno.EOWNERDEAD");
PYTHON_PROVIDE("errno.EPERM");
PYTHON_PROVIDE("errno.EPFNOSUPPORT");
PYTHON_PROVIDE("errno.EPIPE");
PYTHON_PROVIDE("errno.EPROTO");
PYTHON_PROVIDE("errno.EPROTONOSUPPORT");
PYTHON_PROVIDE("errno.EPROTOTYPE");
PYTHON_PROVIDE("errno.ERANGE");
PYTHON_PROVIDE("errno.EREMCHG");
PYTHON_PROVIDE("errno.EREMOTE");
PYTHON_PROVIDE("errno.EREMOTEIO");
PYTHON_PROVIDE("errno.ERESTART");
PYTHON_PROVIDE("errno.ERFKILL");
PYTHON_PROVIDE("errno.EROFS");
PYTHON_PROVIDE("errno.ESHUTDOWN");
PYTHON_PROVIDE("errno.ESOCKTNOSUPPORT");
PYTHON_PROVIDE("errno.ESPIPE");
PYTHON_PROVIDE("errno.ESRCH");
PYTHON_PROVIDE("errno.ESRMNT");
PYTHON_PROVIDE("errno.ESTALE");
PYTHON_PROVIDE("errno.ESTRPIPE");
PYTHON_PROVIDE("errno.ETIME");
PYTHON_PROVIDE("errno.ETIMEDOUT");
PYTHON_PROVIDE("errno.ETOOMANYREFS");
PYTHON_PROVIDE("errno.ETXTBSY");
PYTHON_PROVIDE("errno.EUCLEAN");
PYTHON_PROVIDE("errno.EUNATCH");
PYTHON_PROVIDE("errno.EUSERS");
PYTHON_PROVIDE("errno.EWOULDBLOCK");
PYTHON_PROVIDE("errno.EXDEV");
PYTHON_PROVIDE("errno.EXFULL");
PYTHON_PROVIDE("errno.errorcode");
static PyMethodDef errno_methods[] = {
{NULL, NULL}
};
static void
_inscode(PyObject *d, PyObject *de, const char *name, int code)
{
PyObject *u, *v;
if (!code) return;
u = PyUnicode_FromString(name);
v = PyLong_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);
}
PyDoc_STRVAR(errno__doc__,
"This module makes available standard errno system symbols.\n\
\n\
The value of each symbol is the corresponding integer value,\n\
e.g., on most systems, errno.ENOENT equals the integer 2.\n\
\n\
The dictionary errno.errorcode maps numeric codes to symbol names,\n\
e.g., errno.errorcode[2] could be the string 'ENOENT'.\n\
\n\
Symbols that are not relevant to the underlying system are not defined.\n\
\n\
To map error codes to error messages, use the function os.strerror(),\n\
e.g. os.strerror(2) could return 'No such file or directory'.");
static struct PyModuleDef errnomodule = {
PyModuleDef_HEAD_INIT,
"errno",
errno__doc__,
-1,
errno_methods,
NULL,
NULL,
NULL,
NULL
};
PyMODINIT_FUNC
PyInit_errno(void)
{
PyObject *m, *d, *de;
m = PyModule_Create(&errnomodule);
if (m == NULL)
return NULL;
d = PyModule_GetDict(m);
de = PyDict_New();
if (!d || !de || PyDict_SetItemString(d, "errorcode", de) < 0)
return NULL;
/* 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. However, the Solaris specific
* names and comments are borrowed from sys/errno.h in Solaris.
* MacOSX specific names and comments are borrowed from sys/errno.h in
* MacOSX.
*/
inscode(d, ds, de, "EPIPE", EPIPE, "Broken pipe");
inscode(d, ds, de, "ENODEV", ENODEV, "No such device");
inscode(d, ds, de, "EINVAL", EINVAL, "Invalid argument");
inscode(d, ds, de, "EINTR", EINTR, "Interrupted system call");
inscode(d, ds, de, "ENOTBLK", ENOTBLK, "Block device required");
inscode(d, ds, de, "ENOSYS", ENOSYS, "Function not implemented");
inscode(d, ds, de, "EHOSTUNREACH", EHOSTUNREACH, "No route to host");
inscode(d, ds, de, "ESRCH", ESRCH, "No such process");
inscode(d, ds, de, "EUSERS", EUSERS, "Too many users");
inscode(d, ds, de, "EXDEV", EXDEV, "Cross-device link");
inscode(d, ds, de, "E2BIG", E2BIG, "Arg list too long");
inscode(d, ds, de, "EREMOTE", EREMOTE, "Object is remote");
inscode(d, ds, de, "ECHILD", ECHILD, "No child processes");
inscode(d, ds, de, "EMSGSIZE", EMSGSIZE, "Message too long");
inscode(d, ds, de, "ENOTEMPTY", ENOTEMPTY, "Directory not empty");
inscode(d, ds, de, "ENOBUFS", ENOBUFS, "No buffer space available");
inscode(d, ds, de, "ELOOP", ELOOP, "Too many symbolic links encountered");
inscode(d, ds, de, "EAFNOSUPPORT", EAFNOSUPPORT, "Address family not supported by protocol");
inscode(d, ds, de, "EHOSTDOWN", EHOSTDOWN, "Host is down");
inscode(d, ds, de, "EPFNOSUPPORT", EPFNOSUPPORT, "Protocol family not supported");
inscode(d, ds, de, "ENOPROTOOPT", ENOPROTOOPT, "Protocol not available");
inscode(d, ds, de, "EBUSY", EBUSY, "Device or resource busy");
inscode(d, ds, de, "EWOULDBLOCK", EWOULDBLOCK, "Operation would block");
inscode(d, ds, de, "EBADFD", EBADFD, "File descriptor in bad state");
inscode(d, ds, de, "EISCONN", EISCONN, "Transport endpoint is already connected");
inscode(d, ds, de, "ESHUTDOWN", ESHUTDOWN, "Cannot send after transport endpoint shutdown");
inscode(d, ds, de, "ENONET", ENONET, "Machine is not on the network");
inscode(d, ds, de, "EBADE", EBADE, "Invalid exchange");
inscode(d, ds, de, "EBADF", EBADF, "Bad file number");
inscode(d, ds, de, "EMULTIHOP", EMULTIHOP, "Multihop attempted");
inscode(d, ds, de, "EIO", EIO, "I/O error");
inscode(d, ds, de, "EUNATCH", EUNATCH, "Protocol driver not attached");
inscode(d, ds, de, "EPROTOTYPE", EPROTOTYPE, "Protocol wrong type for socket");
inscode(d, ds, de, "ENOSPC", ENOSPC, "No space left on device");
inscode(d, ds, de, "ENOEXEC", ENOEXEC, "Exec format error");
inscode(d, ds, de, "EALREADY", EALREADY, "Operation already in progress");
inscode(d, ds, de, "ENETDOWN", ENETDOWN, "Network is down");
inscode(d, ds, de, "ENOTNAM", ENOTNAM, "Not a XENIX named type file");
inscode(d, ds, de, "EACCES", EACCES, "Permission denied");
inscode(d, ds, de, "ELNRNG", ELNRNG, "Link number out of range");
inscode(d, ds, de, "EILSEQ", EILSEQ, "Illegal byte sequence");
inscode(d, ds, de, "ENOTDIR", ENOTDIR, "Not a directory");
inscode(d, ds, de, "ENOTUNIQ", ENOTUNIQ, "Name not unique on network");
inscode(d, ds, de, "EPERM", EPERM, "Operation not permitted");
inscode(d, ds, de, "EDOM", EDOM, "Math argument out of domain of func");
inscode(d, ds, de, "EXFULL", EXFULL, "Exchange full");
inscode(d, ds, de, "ECONNREFUSED", ECONNREFUSED, "Connection refused");
inscode(d, ds, de, "EISDIR", EISDIR, "Is a directory");
inscode(d, ds, de, "EPROTONOSUPPORT", EPROTONOSUPPORT, "Protocol not supported");
inscode(d, ds, de, "EROFS", EROFS, "Read-only file system");
inscode(d, ds, de, "EADDRNOTAVAIL", EADDRNOTAVAIL, "Cannot assign requested address");
inscode(d, ds, de, "EIDRM", EIDRM, "Identifier removed");
inscode(d, ds, de, "ECOMM", ECOMM, "Communication error on send");
inscode(d, ds, de, "ESRMNT", ESRMNT, "Srmount error");
inscode(d, ds, de, "EREMOTEIO", EREMOTEIO, "Remote I/O error");
inscode(d, ds, de, "EL3RST", EL3RST, "Level 3 reset");
inscode(d, ds, de, "EBADMSG", EBADMSG, "Not a data message");
inscode(d, ds, de, "ENFILE", ENFILE, "File table overflow");
inscode(d, ds, de, "ELIBMAX", ELIBMAX, "Attempting to link in too many shared libraries");
inscode(d, ds, de, "ESPIPE", ESPIPE, "Illegal seek");
inscode(d, ds, de, "ENOLINK", ENOLINK, "Link has been severed");
inscode(d, ds, de, "ENETRESET", ENETRESET, "Network dropped connection because of reset");
inscode(d, ds, de, "ETIMEDOUT", ETIMEDOUT, "Connection timed out");
inscode(d, ds, de, "ENOENT", ENOENT, "No such file or directory");
inscode(d, ds, de, "EEXIST", EEXIST, "File exists");
inscode(d, ds, de, "EDQUOT", EDQUOT, "Quota exceeded");
inscode(d, ds, de, "ENOSTR", ENOSTR, "Device not a stream");
inscode(d, ds, de, "EBADSLT", EBADSLT, "Invalid slot");
inscode(d, ds, de, "EBADRQC", EBADRQC, "Invalid request code");
inscode(d, ds, de, "ELIBACC", ELIBACC, "Can not access a needed shared library");
inscode(d, ds, de, "EFAULT", EFAULT, "Bad address");
inscode(d, ds, de, "EFBIG", EFBIG, "File too large");
inscode(d, ds, de, "EDEADLK", EDEADLK, "Resource deadlock would occur");
inscode(d, ds, de, "ENOTCONN", ENOTCONN, "Transport endpoint is not connected");
inscode(d, ds, de, "EDESTADDRREQ", EDESTADDRREQ, "Destination address required");
inscode(d, ds, de, "ELIBSCN", ELIBSCN, ".lib section in a.out corrupted");
inscode(d, ds, de, "ENOLCK", ENOLCK, "No record locks available");
inscode(d, ds, de, "EISNAM", EISNAM, "Is a named type file");
inscode(d, ds, de, "ECONNABORTED", ECONNABORTED, "Software caused connection abort");
inscode(d, ds, de, "ENETUNREACH", ENETUNREACH, "Network is unreachable");
inscode(d, ds, de, "ESTALE", ESTALE, "Stale NFS file handle");
inscode(d, ds, de, "ENOSR", ENOSR, "Out of streams resources");
inscode(d, ds, de, "ENOMEM", ENOMEM, "Out of memory");
inscode(d, ds, de, "ENOTSOCK", ENOTSOCK, "Socket operation on non-socket");
inscode(d, ds, de, "ESTRPIPE", ESTRPIPE, "Streams pipe error");
inscode(d, ds, de, "EMLINK", EMLINK, "Too many links");
inscode(d, ds, de, "ERANGE", ERANGE, "Math result not representable");
inscode(d, ds, de, "ELIBEXEC", ELIBEXEC, "Cannot exec a shared library directly");
inscode(d, ds, de, "EL3HLT", EL3HLT, "Level 3 halted");
inscode(d, ds, de, "ECONNRESET", ECONNRESET, "Connection reset by peer");
inscode(d, ds, de, "EADDRINUSE", EADDRINUSE, "Address already in use");
inscode(d, ds, de, "EOPNOTSUPP", EOPNOTSUPP, "Operation not supported on transport endpoint");
inscode(d, ds, de, "EREMCHG", EREMCHG, "Remote address changed");
inscode(d, ds, de, "EAGAIN", EAGAIN, "Try again");
inscode(d, ds, de, "ENAMETOOLONG", ENAMETOOLONG, "File name too long");
inscode(d, ds, de, "ENOTTY", ENOTTY, "Not a typewriter");
inscode(d, ds, de, "ERESTART", ERESTART, "Interrupted system call should be restarted");
inscode(d, ds, de, "ESOCKTNOSUPPORT", ESOCKTNOSUPPORT, "Socket type not supported");
inscode(d, ds, de, "ETIME", ETIME, "Timer expired");
inscode(d, ds, de, "ETOOMANYREFS", ETOOMANYREFS, "Too many references: cannot splice");
inscode(d, ds, de, "EMFILE", EMFILE, "Too many open files");
inscode(d, ds, de, "ETXTBSY", ETXTBSY, "Text file busy");
inscode(d, ds, de, "EINPROGRESS", EINPROGRESS, "Operation now in progress");
inscode(d, ds, de, "ENXIO", ENXIO, "No such device or address");
inscode(d, ds, de, "ENOTSUP", ENOTSUP, "Operation not supported");
/* might not be available */
inscode(d, ds, de, "EPROTO", EPROTO, "Protocol error");
inscode(d, ds, de, "ENOMSG", ENOMSG, "No message of desired type");
inscode(d, ds, de, "ENODATA", ENODATA, "No data available");
inscode(d, ds, de, "EOVERFLOW", EOVERFLOW, "Value too large for defined data type");
inscode(d, ds, de, "ENOMEDIUM", ENOMEDIUM, "No medium found");
inscode(d, ds, de, "EMEDIUMTYPE", EMEDIUMTYPE, "Wrong medium type");
inscode(d, ds, de, "ECANCELED", ECANCELED, "Operation Canceled");
inscode(d, ds, de, "EOWNERDEAD", EOWNERDEAD, "Owner died");
inscode(d, ds, de, "ENOTRECOVERABLE", ENOTRECOVERABLE, "State not recoverable");
inscode(d, ds, de, "EOWNERDEAD", EOWNERDEAD, "Process died with the lock");
inscode(d, ds, de, "ENOTRECOVERABLE", ENOTRECOVERABLE, "Lock is not recoverable");
/* bsd only */
inscode(d, ds, de, "EFTYPE", EFTYPE, "Inappropriate file type or format");
inscode(d, ds, de, "EAUTH", EAUTH, "Authentication error");
inscode(d, ds, de, "EBADRPC", EBADRPC, "RPC struct is bad");
inscode(d, ds, de, "ENEEDAUTH", ENEEDAUTH, "Need authenticator");
inscode(d, ds, de, "ENOATTR", ENOATTR, "Attribute not found");
inscode(d, ds, de, "EPROCUNAVAIL", EPROCUNAVAIL, "Bad procedure for program");
inscode(d, ds, de, "EPROGMISMATCH", EPROGMISMATCH, "Program version wrong");
inscode(d, ds, de, "EPROGUNAVAIL", EPROGUNAVAIL, "RPC prog. not avail");
inscode(d, ds, de, "ERPCMISMATCH", ERPCMISMATCH, "RPC version wrong");
/* bsd and windows literally */
inscode(d, ds, de, "EPROCLIM", EPROCLIM, "Too many processes");
/* xnu only */
inscode(d, ds, de, "EBADARCH", EBADARCH, "Bad CPU type in executable");
inscode(d, ds, de, "EBADEXEC", EBADEXEC, "Bad executable (or shared library)");
inscode(d, ds, de, "EBADMACHO", EBADMACHO, "Malformed Mach-o file");
inscode(d, ds, de, "EDEVERR", EDEVERR, "Device error");
inscode(d, ds, de, "ENOPOLICY", ENOPOLICY, "Policy not found");
inscode(d, ds, de, "EPWROFF", EPWROFF, "Device power is off");
inscode(d, ds, de, "ESHLIBVERS", ESHLIBVERS, "Shared library version mismatch");
/* linux undocumented errnos */
inscode(d, ds, de, "ENOANO", ENOANO, "No anode");
inscode(d, ds, de, "EADV", EADV, "Advertise error");
inscode(d, ds, de, "EL2HLT", EL2HLT, "Level 2 halted");
inscode(d, ds, de, "EDOTDOT", EDOTDOT, "RFS specific error");
inscode(d, ds, de, "ENOPKG", ENOPKG, "Package not installed");
inscode(d, ds, de, "EBADR", EBADR, "Invalid request descriptor");
inscode(d, ds, de, "ENOCSI", ENOCSI, "No CSI structure available");
inscode(d, ds, de, "ENOKEY", ENOKEY, "Required key not available");
inscode(d, ds, de, "EUCLEAN", EUCLEAN, "Structure needs cleaning");
inscode(d, ds, de, "ECHRNG", ECHRNG, "Channel number out of range");
inscode(d, ds, de, "EL2NSYNC", EL2NSYNC, "Level 2 not synchronized");
inscode(d, ds, de, "EKEYEXPIRED", EKEYEXPIRED, "Key has expired");
inscode(d, ds, de, "ENAVAIL", ENAVAIL, "No XENIX semaphores available");
inscode(d, ds, de, "EKEYREVOKED", EKEYREVOKED, "Key has been revoked");
inscode(d, ds, de, "ELIBBAD", ELIBBAD, "Accessing a corrupted shared library");
inscode(d, ds, de, "EKEYREJECTED", EKEYREJECTED, "Key was rejected by service");
inscode(d, ds, de, "ERFKILL", ERFKILL, "Operation not possible due to RF-kill");
/* solaris only */
#ifdef ELOCKUNMAPPED
inscode(d, ds, de, "ELOCKUNMAPPED", ELOCKUNMAPPED, "Locked lock was unmapped");
#endif
#ifdef ENOTACTIVE
inscode(d, ds, de, "ENOTACTIVE", ENOTACTIVE, "Facility is not active");
#endif
Py_DECREF(de);
return m;
}
_Section(".rodata.pytab.1") const struct _inittab _PyImport_Inittab_errno = {
"errno",
PyInit_errno,
};
| 19,250 | 407 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Modules/unicodedata_nfdnfkd.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:8;coding:utf-8 -*-â
âvi: set net ft=c ts=4 sts=4 sw=4 fenc=utf-8 :viâ
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ¡
â Python 3 â
â https://docs.python.org/3/license.html â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
#include "libc/intrin/bits.h"
#include "third_party/python/Include/pyerrors.h"
#include "third_party/python/Include/pymem.h"
#include "third_party/python/Modules/unicodedata.h"
#include "third_party/python/Modules/unicodedata_unidata.h"
/* clang-format off */
PyObject *
_PyUnicode_NfdNfkd(PyObject *self, PyObject *input, int k)
{
PyObject *result;
Py_UCS4 *output;
Py_ssize_t i, o, osize;
int kind;
void *data;
/* Longest decomposition in Unicode 3.2: U+FDFA */
Py_UCS4 stack[20];
Py_ssize_t space, isize;
int index, prefix, count, stackptr;
unsigned char prev, cur;
stackptr = 0;
isize = PyUnicode_GET_LENGTH(input);
space = isize;
/* Overallocate at most 10 characters. */
if (space > 10) {
if (space <= PY_SSIZE_T_MAX - 10)
space += 10;
}
else {
space *= 2;
}
osize = space;
output = PyMem_NEW(Py_UCS4, space);
if (!output) {
PyErr_NoMemory();
return NULL;
}
i = o = 0;
kind = PyUnicode_KIND(input);
data = PyUnicode_DATA(input);
while (i < isize) {
stack[stackptr++] = PyUnicode_READ(kind, data, i++);
while(stackptr) {
Py_UCS4 code = stack[--stackptr];
/* Hangul Decomposition adds three characters in
a single step, so we need at least that much room. */
if (space < 3) {
Py_UCS4 *new_output;
osize += 10;
space += 10;
new_output = PyMem_Realloc(output, osize*sizeof(Py_UCS4));
if (new_output == NULL) {
PyMem_Free(output);
PyErr_NoMemory();
return NULL;
}
output = new_output;
}
/* Hangul Decomposition. */
if (_Hanghoul_SBase <= code && code < (_Hanghoul_SBase + _Hanghoul_SCount)) {
int SIndex = code - _Hanghoul_SBase;
int L = _Hanghoul_LBase + SIndex / _Hanghoul_NCount;
int V = _Hanghoul_VBase + (SIndex % _Hanghoul_NCount) / _Hanghoul_TCount;
int T = _Hanghoul_TBase + SIndex % _Hanghoul_TCount;
output[o++] = L;
output[o++] = V;
space -= 2;
if (T != _Hanghoul_TBase) {
output[o++] = T;
space --;
}
continue;
}
/* normalization changes */
if (self && UCD_Check(self)) {
Py_UCS4 value = ((PreviousDBVersion*)self)->normalization(code);
if (value != 0) {
stack[stackptr++] = value;
continue;
}
}
/* Other decompositions. */
_PyUnicode_GetDecompRecord(self, code, &index, &prefix, &count);
/* Copy character if it is not decomposable, or has a
compatibility decomposition, but we do NFD. */
if (!count || (prefix && !k)) {
output[o++] = code;
space--;
continue;
}
/* Copy decomposition onto the stack, in reverse
order. */
while(count) {
code = _bextra(_PyUnicode_Decomp,
index + (--count),
_PyUnicode_DecompBits);
stack[stackptr++] = code;
}
}
}
result = PyUnicode_FromKindAndData(PyUnicode_4BYTE_KIND,
output, o);
PyMem_Free(output);
if (!result)
return NULL;
/* result is guaranteed to be ready, as it is compact. */
kind = PyUnicode_KIND(result);
data = PyUnicode_DATA(result);
/* Sort canonically. */
i = 0;
prev = _PyUnicode_GetRecord(PyUnicode_READ(kind, data, i))->combining;
for (i++; i < PyUnicode_GET_LENGTH(result); i++) {
cur = _PyUnicode_GetRecord(PyUnicode_READ(kind, data, i))->combining;
if (prev == 0 || cur == 0 || prev <= cur) {
prev = cur;
continue;
}
/* Non-canonical order. Need to switch *i with previous. */
o = i - 1;
while (1) {
Py_UCS4 tmp = PyUnicode_READ(kind, data, o+1);
PyUnicode_WRITE(kind, data, o+1,
PyUnicode_READ(kind, data, o));
PyUnicode_WRITE(kind, data, o, tmp);
o--;
if (o < 0)
break;
prev = _PyUnicode_GetRecord(PyUnicode_READ(kind, data, o))->combining;
if (prev == 0 || prev <= cur)
break;
}
prev = _PyUnicode_GetRecord(PyUnicode_READ(kind, data, i))->combining;
}
return result;
}
| 5,624 | 142 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Modules/unicodedata_comp.c | #include "libc/nexgen32e/kompressor.h"
#include "third_party/python/Modules/unicodedata.h"
/* clang-format off */
/* GENERATED BY third_party/python/Tools/unicode/makeunicodedata.py 3.2 */
unsigned short _PyUnicode_CompIndex[5938];
static const unsigned short _PyUnicode_CompIndex_rodata[1146+1][2] = { /* 38.5989% profit */
{ 6, 0x00},
{ 1, 0x01},
{ 15, 0x00},
{ 1, 0x02},
{ 15, 0x00},
{ 1, 0x03},
{ 8, 0x00},
{ 1, 0x04},
{ 1, 0x05},
{ 1, 0x06},
{ 1, 0x07},
{ 1, 0x08},
{ 1, 0x09},
{ 11, 0x00},
{ 1, 0x0a},
{ 2, 0x00},
{ 1, 0x0b},
{ 1, 0x00},
{ 1, 0x0c},
{ 9, 0x00},
{ 1, 0x0d},
{ 1, 0x0e},
{ 1, 0x0f},
{ 2, 0x00},
{ 1, 0x10},
{ 11, 0x00},
{ 1, 0x11},
{ 1, 0x12},
{ 1, 0x13},
{ 1, 0x14},
{ 1, 0x15},
{ 1, 0x16},
{ 8, 0x00},
{ 1, 0x17},
{ 1, 0x18},
{ 1, 0x19},
{ 1, 0x1a},
{ 1, 0x1b},
{ 1, 0x1c},
{ 1, 0x1d},
{ 10, 0x00},
{ 1, 0x1e},
{ 14, 0x00},
{ 1, 0x1f},
{ 1, 0x20},
{ 1, 0x21},
{ 2, 0x00},
{ 1, 0x22},
{ 10, 0x00},
{ 1, 0x23},
{ 1, 0x24},
{ 1, 0x25},
{ 1, 0x26},
{ 1, 0x27},
{ 1, 0x28},
{ 9, 0x00},
{ 1, 0x29},
{ 1, 0x2a},
{ 1, 0x2b},
{ 1, 0x2c},
{ 1, 0x2d},
{ 1, 0x2e},
{ 1, 0x2f},
{ 9, 0x00},
{ 1, 0x30},
{ 15, 0x00},
{ 1, 0x31},
{ 1, 0x00},
{ 1, 0x32},
{ 1, 0x00},
{ 1, 0x33},
{ 1, 0x34},
{ 1, 0x35},
{ 8, 0x00},
{ 1, 0x36},
{ 2, 0x00},
{ 1, 0x37},
{ 1, 0x38},
{ 1, 0x39},
{ 1, 0x3a},
{ 1, 0x3b},
{ 8, 0x00},
{ 1, 0x3c},
{ 1, 0x3d},
{ 2, 0x00},
{ 1, 0x3e},
{ 11, 0x00},
{ 1, 0x3f},
{ 1, 0x40},
{ 1, 0x41},
{ 1, 0x00},
{ 1, 0x42},
{ 1, 0x43},
{ 1, 0x44},
{ 8, 0x00},
{ 1, 0x45},
{ 1, 0x46},
{ 1, 0x47},
{ 1, 0x48},
{ 1, 0x49},
{ 1, 0x4a},
{ 1, 0x4b},
{ 9, 0x00},
{ 1, 0x4c},
{ 1, 0x00},
{ 1, 0x4d},
{ 13, 0x00},
{ 1, 0x4e},
{ 1, 0x4f},
{ 1, 0x00},
{ 1, 0x50},
{ 1, 0x51},
{ 1, 0x52},
{ 1, 0x53},
{ 9, 0x00},
{ 1, 0x54},
{ 1, 0x55},
{ 1, 0x56},
{ 1, 0x00},
{ 1, 0x57},
{ 1, 0x58},
{ 11, 0x00},
{ 1, 0x59},
{ 1, 0x5a},
{ 1, 0x00},
{ 1, 0x5b},
{ 1, 0x5c},
{ 1, 0x5d},
{ 8, 0x00},
{ 1, 0x5e},
{ 1, 0x5f},
{ 1, 0x60},
{ 1, 0x61},
{ 1, 0x62},
{ 1, 0x63},
{ 1, 0x64},
{ 10, 0x00},
{ 1, 0x65},
{ 2, 0x00},
{ 1, 0x66},
{ 11, 0x00},
{ 1, 0x67},
{ 1, 0x68},
{ 2, 0x00},
{ 1, 0x69},
{ 12, 0x00},
{ 1, 0x6a},
{ 13, 0x00},
{ 1, 0x6b},
{ 1, 0x6c},
{ 1, 0x6d},
{ 1, 0x00},
{ 1, 0x6e},
{ 11, 0x00},
{ 1, 0x6f},
{ 1, 0x70},
{ 1, 0x00},
{ 1, 0x71},
{ 1, 0x72},
{ 1, 0x00},
{ 1, 0x73},
{ 9, 0x00},
{ 1, 0x74},
{ 1, 0x75},
{ 1, 0x76},
{ 1, 0x77},
{ 1, 0x78},
{ 1, 0x79},
{ 11, 0x00},
{ 1, 0x7a},
{ 2, 0x00},
{ 1, 0x7b},
{ 1, 0x00},
{ 1, 0x7c},
{ 8, 0x00},
{ 1, 0x7d},
{ 1, 0x7e},
{ 1, 0x7f},
{ 1, 0x80},
{ 1, 0x00},
{ 1, 0x81},
{ 11, 0x00},
{ 1, 0x82},
{ 1, 0x00},
{ 1, 0x83},
{ 1, 0x84},
{ 1, 0x85},
{ 1, 0x86},
{ 9, 0x00},
{ 1, 0x87},
{ 1, 0x88},
{ 1, 0x89},
{ 1, 0x8a},
{ 1, 0x8b},
{ 1, 0x8c},
{ 1, 0x8d},
{ 10, 0x00},
{ 1, 0x8e},
{ 13, 0x00},
{ 1, 0x8f},
{ 1, 0x90},
{ 1, 0x91},
{ 1, 0x92},
{ 1, 0x00},
{ 1, 0x93},
{ 10, 0x00},
{ 1, 0x94},
{ 1, 0x95},
{ 1, 0x96},
{ 1, 0x97},
{ 1, 0x98},
{ 1, 0x99},
{ 1, 0x9a},
{ 9, 0x00},
{ 1, 0x9b},
{ 1, 0x9c},
{ 1, 0x9d},
{ 1, 0x9e},
{ 1, 0x9f},
{ 1, 0xa0},
{ 1, 0xa1},
{ 9, 0x00},
{ 1, 0xa2},
{ 1, 0x00},
{ 1, 0xa3},
{ 12, 0x00},
{ 1, 0xa4},
{ 2, 0x00},
{ 1, 0xa5},
{ 1, 0xa6},
{ 1, 0xa7},
{ 1, 0x00},
{ 1, 0xa8},
{ 8, 0x00},
{ 1, 0xa9},
{ 2, 0x00},
{ 1, 0xaa},
{ 1, 0xab},
{ 1, 0xac},
{ 1, 0xad},
{ 9, 0x00},
{ 1, 0xae},
{ 1, 0xaf},
{ 2, 0x00},
{ 1, 0xb0},
{ 10, 0x00},
{ 1, 0xb1},
{ 1, 0xb2},
{ 1, 0xb3},
{ 1, 0xb4},
{ 1, 0x00},
{ 1, 0xb5},
{ 1, 0xb6},
{ 1, 0xb7},
{ 8, 0x00},
{ 1, 0xb8},
{ 1, 0xb9},
{ 1, 0xba},
{ 1, 0xbb},
{ 1, 0xbc},
{ 1, 0x00},
{ 1, 0xbd},
{ 9, 0x00},
{ 1, 0xbe},
{ 1, 0xbf},
{ 14, 0x00},
{ 1, 0xc0},
{ 1, 0xc1},
{ 1, 0xc2},
{ 1, 0xc3},
{ 1, 0xc4},
{ 1, 0xc5},
{ 1, 0xc6},
{ 9, 0x00},
{ 1, 0xc7},
{ 1, 0xc8},
{ 1, 0xc9},
{ 1, 0x00},
{ 1, 0xca},
{ 1, 0xcb},
{ 11, 0x00},
{ 1, 0xcc},
{ 1, 0xcd},
{ 1, 0xce},
{ 1, 0xcf},
{ 1, 0xd0},
{ 1, 0xd1},
{ 8, 0x00},
{ 1, 0xd2},
{ 1, 0xd3},
{ 1, 0xd4},
{ 1, 0xd5},
{ 1, 0xd6},
{ 1, 0xd7},
{ 1, 0xd8},
{ 9, 0x00},
{ 1, 0xd9},
{ 3, 0x00},
{ 1, 0xda},
{ 10, 0x00},
{ 1, 0xdb},
{ 1, 0xdc},
{ 1, 0xdd},
{ 1, 0xde},
{ 1, 0x00},
{ 1, 0xdf},
{ 12, 0x00},
{ 1, 0xe0},
{ 13, 0x00},
{ 1, 0xe1},
{ 1, 0xe2},
{ 1, 0xe3},
{ 1, 0x00},
{ 1, 0xe4},
{ 11, 0x00},
{ 1, 0xe5},
{ 1, 0xe6},
{ 1, 0xe7},
{ 1, 0x00},
{ 1, 0xe8},
{ 1, 0x00},
{ 1, 0xe9},
{ 8, 0x00},
{ 1, 0xea},
{ 1, 0xeb},
{ 5, 0x00},
{ 1, 0xec},
{ 8, 0x00},
{ 1, 0xed},
{ 1, 0xee},
{ 1, 0xef},
{ 14, 0x00},
{ 1, 0xf0},
{ 14, 0x00},
{ 1, 0xf1},
{ 15, 0x00},
{ 1, 0xf2},
{ 14, 0x00},
{ 1, 0xf3},
{ 15, 0x00},
{ 1, 0xf4},
{ 1, 0xf5},
{ 1, 0xf6},
{ 13, 0x00},
{ 1, 0xf7},
{ 14, 0x00},
{ 1, 0xf8},
{ 1, 0xf9},
{ 1, 0xfa},
{ 13, 0x00},
{ 1, 0xfb},
{ 1, 0xfc},
{ 1, 0xfd},
{ 14, 0x00},
{ 1, 0xfe},
{ 14, 0x00},
{ 1, 0xff},
{ 14, 0x00},
{ 1, 0x100},
{ 1, 0x101},
{ 1, 0x00},
{ 1, 0x102},
{ 12, 0x00},
{ 1, 0x103},
{ 1, 0x104},
{ 1, 0x105},
{ 14, 0x00},
{ 1, 0x106},
{ 14, 0x00},
{ 1, 0x107},
{ 15, 0x00},
{ 1, 0x108},
{ 14, 0x00},
{ 1, 0x109},
{ 15, 0x00},
{ 1, 0x10a},
{ 1, 0x10b},
{ 1, 0x10c},
{ 13, 0x00},
{ 1, 0x10d},
{ 14, 0x00},
{ 1, 0x10e},
{ 1, 0x10f},
{ 1, 0x110},
{ 13, 0x00},
{ 1, 0x111},
{ 1, 0x112},
{ 1, 0x113},
{ 14, 0x00},
{ 1, 0x114},
{ 14, 0x00},
{ 1, 0x115},
{ 14, 0x00},
{ 1, 0x116},
{ 1, 0x117},
{ 1, 0x00},
{ 1, 0x118},
{ 12, 0x00},
{ 1, 0x119},
{ 1, 0x11a},
{ 1, 0x11b},
{ 13, 0x00},
{ 1, 0x11c},
{ 1, 0x11d},
{ 1, 0x11e},
{ 13, 0x00},
{ 1, 0x11f},
{ 14, 0x00},
{ 1, 0x120},
{ 1, 0x121},
{ 14, 0x00},
{ 1, 0x122},
{ 15, 0x00},
{ 1, 0x123},
{ 16, 0x00},
{ 1, 0x124},
{ 15, 0x00},
{ 1, 0x125},
{ 15, 0x00},
{ 1, 0x126},
{ 14, 0x00},
{ 1, 0x127},
{ 14, 0x00},
{ 1, 0x128},
{ 15, 0x00},
{ 1, 0x129},
{ 16, 0x00},
{ 1, 0x12a},
{ 15, 0x00},
{ 1, 0x12b},
{ 14, 0x00},
{ 1, 0x12c},
{ 13, 0x00},
{ 1, 0x12d},
{ 1, 0x12e},
{ 1, 0x12f},
{ 2, 0x00},
{ 1, 0x130},
{ 10, 0x00},
{ 1, 0x131},
{ 1, 0x132},
{ 1, 0x133},
{ 1, 0x00},
{ 1, 0x134},
{ 11, 0x00},
{ 1, 0x135},
{ 1, 0x136},
{ 1, 0x137},
{ 1, 0x00},
{ 1, 0x138},
{ 11, 0x00},
{ 1, 0x139},
{ 1, 0x00},
{ 1, 0x13a},
{ 1, 0x00},
{ 1, 0x13b},
{ 13, 0x00},
{ 1, 0x13c},
{ 13, 0x00},
{ 1, 0x13d},
{ 15, 0x00},
{ 1, 0x13e},
{ 15, 0x00},
{ 1, 0x13f},
{ 14, 0x00},
{ 1, 0x140},
{ 15, 0x00},
{ 1, 0x141},
{ 15, 0x00},
{ 1, 0x142},
{ 15, 0x00},
{ 1, 0x143},
{ 14, 0x00},
{ 1, 0x144},
{ 17, 0x00},
{ 1, 0x145},
{ 12, 0x00},
{ 1, 0x146},
{ 1, 0x147},
{ 1, 0x00},
{ 1, 0x148},
{ 1, 0x149},
{ 2, 0x00},
{ 1, 0x14a},
{ 8, 0x00},
{ 1, 0x14b},
{ 2, 0x00},
{ 1, 0x14c},
{ 11, 0x00},
{ 1, 0x14d},
{ 1, 0x14e},
{ 2, 0x00},
{ 1, 0x14f},
{ 3, 0x00},
{ 1, 0x150},
{ 7, 0x00},
{ 1, 0x151},
{ 1, 0x152},
{ 1, 0x153},
{ 1, 0x00},
{ 1, 0x154},
{ 11, 0x00},
{ 1, 0x155},
{ 2, 0x00},
{ 1, 0x156},
{ 1, 0x157},
{ 14, 0x00},
{ 1, 0x158},
{ 11, 0x00},
{ 1, 0x159},
{ 1, 0x15a},
{ 1, 0x15b},
{ 1, 0x00},
{ 1, 0x15c},
{ 11, 0x00},
{ 1, 0x15d},
{ 3, 0x00},
{ 1, 0x15e},
{ 2, 0x00},
{ 1, 0x15f},
{ 15, 0x00},
{ 1, 0x160},
{ 15, 0x00},
{ 1, 0x161},
{ 7, 0x00},
{ 1, 0x162},
{ 1, 0x163},
{ 1, 0x164},
{ 1, 0x00},
{ 1, 0x165},
{ 2, 0x00},
{ 1, 0x166},
{ 1, 0x167},
{ 7, 0x00},
{ 1, 0x168},
{ 3, 0x00},
{ 1, 0x169},
{ 11, 0x00},
{ 1, 0x16a},
{ 2, 0x00},
{ 1, 0x16b},
{ 1, 0x16c},
{ 2, 0x00},
{ 1, 0x16d},
{ 8, 0x00},
{ 1, 0x16e},
{ 1, 0x16f},
{ 1, 0x00},
{ 1, 0x170},
{ 3, 0x00},
{ 1, 0x171},
{ 7, 0x00},
{ 1, 0x172},
{ 1, 0x173},
{ 2, 0x00},
{ 1, 0x174},
{ 15, 0x00},
{ 1, 0x175},
{ 11, 0x00},
{ 1, 0x176},
{ 1, 0x177},
{ 1, 0x178},
{ 1, 0x179},
{ 1, 0x17a},
{ 2, 0x00},
{ 1, 0x17b},
{ 8, 0x00},
{ 1, 0x17c},
{ 2, 0x00},
{ 1, 0x17d},
{ 3, 0x00},
{ 1, 0x17e},
{ 7, 0x00},
{ 1, 0x17f},
{ 1, 0x180},
{ 5, 0x00},
{ 1, 0x181},
{ 8, 0x00},
{ 1, 0x182},
{ 6, 0x00},
{ 1, 0x183},
{ 15, 0x00},
{ 1, 0x184},
{ 8, 0x00},
{ 1, 0x185},
{ 1, 0x186},
{ 15, 0x00},
{ 1, 0x187},
{ 14, 0x00},
{ 1, 0x188},
{ 1, 0x189},
{ 13, 0x00},
{ 1, 0x18a},
{ 15, 0x00},
{ 1, 0x18b},
{ 1, 0x18c},
{ 15, 0x00},
{ 1, 0x18d},
{ 15, 0x00},
{ 1, 0x18e},
{ 13, 0x00},
{ 1, 0x18f},
{ 1, 0x190},
{ 1, 0x191},
{ 13, 0x00},
{ 1, 0x192},
{ 16, 0x00},
{ 1, 0x193},
{ 14, 0x00},
{ 1, 0x194},
{ 1, 0x195},
{ 1, 0x196},
{ 14, 0x00},
{ 1, 0x197},
{ 14, 0x00},
{ 1, 0x198},
{ 15, 0x00},
{ 1, 0x199},
{ 14, 0x00},
{ 1, 0x19a},
{ 1, 0x19b},
{ 13, 0x00},
{ 1, 0x19c},
{ 15, 0x00},
{ 1, 0x19d},
{ 1, 0x19e},
{ 15, 0x00},
{ 1, 0x19f},
{ 15, 0x00},
{ 1, 0x1a0},
{ 13, 0x00},
{ 1, 0x1a1},
{ 1, 0x1a2},
{ 1, 0x1a3},
{ 13, 0x00},
{ 1, 0x1a4},
{ 16, 0x00},
{ 1, 0x1a5},
{ 14, 0x00},
{ 1, 0x1a6},
{ 1, 0x1a7},
{ 1, 0x1a8},
{ 14, 0x00},
{ 1, 0x1a9},
{ 14, 0x00},
{ 1, 0x1aa},
{ 15, 0x00},
{ 1, 0x1ab},
{ 15, 0x00},
{ 1, 0x1ac},
{ 16, 0x00},
{ 1, 0x1ad},
{ 15, 0x00},
{ 1, 0x1ae},
{ 13, 0x00},
{ 1, 0x1af},
{ 15, 0x00},
{ 1, 0x1b0},
{ 15, 0x00},
{ 1, 0x1b1},
{ 14, 0x00},
{ 1, 0x1b2},
{ 21, 0x00},
{ 1, 0x1b3},
{ 15, 0x00},
{ 1, 0x1b4},
{ 15, 0x00},
{ 1, 0x1b5},
{ 14, 0x00},
{ 1, 0x1b6},
{ 15, 0x00},
{ 1, 0x1b7},
{ 15, 0x00},
{ 1, 0x1b8},
{ 15, 0x00},
{ 1, 0x1b9},
{ 15, 0x00},
{ 1, 0x1ba},
{ 15, 0x00},
{ 1, 0x1bb},
{ 15, 0x00},
{ 1, 0x1bc},
{ 15, 0x00},
{ 1, 0x1bd},
{ 16, 0x00},
{ 1, 0x1be},
{ 14, 0x00},
{ 1, 0x1bf},
{ 15, 0x00},
{ 1, 0x1c0},
{ 15, 0x00},
{ 1, 0x1c1},
{ 15, 0x00},
{ 1, 0x1c2},
{ 15, 0x00},
{ 1, 0x1c3},
{ 15, 0x00},
{ 1, 0x1c4},
{ 15, 0x00},
{ 1, 0x1c5},
{ 15, 0x00},
{ 1, 0x1c6},
{ 15, 0x00},
{ 1, 0x1c7},
{ 1, 0x1c8},
{ 14, 0x00},
{ 1, 0x1c9},
{ 15, 0x00},
{ 1, 0x1ca},
{ 15, 0x00},
{ 1, 0x1cb},
{ 15, 0x00},
{ 1, 0x1cc},
{ 15, 0x00},
{ 1, 0x1cd},
{ 15, 0x00},
{ 1, 0x1ce},
{ 14, 0x00},
{ 1, 0x1cf},
{ 15, 0x00},
{ 1, 0x1d0},
{ 15, 0x00},
{ 1, 0x1d1},
{ 15, 0x00},
{ 1, 0x1d2},
{ 14, 0x00},
{ 1, 0x1d3},
{ 15, 0x00},
{ 1, 0x1d4},
{ 15, 0x00},
{ 1, 0x1d5},
{ 3, 0x00},
{ 1, 0x1d6},
{ 15, 0x00},
{ 1, 0x1d7},
{ 14, 0x00},
{ 1, 0x1d8},
{ 15, 0x00},
{ 1, 0x1d9},
{ 15, 0x00},
{ 1, 0x1da},
{ 15, 0x00},
{ 1, 0x1db},
{ 14, 0x00},
{ 1, 0x1dc},
{ 1, 0x1dd},
{ 14, 0x00},
{ 1, 0x1de},
{ 14, 0x00},
{ 1, 0x1df},
{ 15, 0x00},
{ 1, 0x1e0},
{ 15, 0x00},
{ 1, 0x1e1},
{ 15, 0x00},
{ 1, 0x1e2},
{ 14, 0x00},
{ 1, 0x1e3},
{ 6, 0x00},
{ 1, 0x1e4},
{ 8, 0x00},
{ 1, 0x1e5},
{ 6, 0x00},
{ 1, 0x1e6},
{ 15, 0x00},
{ 1, 0x1e7},
{ 14, 0x00},
{ 1, 0x1e8},
{ 15, 0x00},
{ 1, 0x1e9},
{ 15, 0x00},
{ 1, 0x1ea},
{ 15, 0x00},
{ 1, 0x1eb},
{ 14, 0x00},
{ 1, 0x1ec},
{ 8, 0x00},
{ 1, 0x1ed},
{ 6, 0x00},
{ 1, 0x1ee},
{ 8, 0x00},
{ 1, 0x1ef},
{ 6, 0x00},
{ 1, 0x1f0},
{ 15, 0x00},
{ 1, 0x1f1},
{ 14, 0x00},
{ 1, 0x1f2},
{ 15, 0x00},
{ 1, 0x1f3},
{ 15, 0x00},
{ 1, 0x1f4},
{ 15, 0x00},
{ 1, 0x1f5},
{ 14, 0x00},
{ 1, 0x1f6},
{ 8, 0x00},
{ 1, 0x1f7},
{ 15, 0x00},
{ 1, 0x1f8},
{ 14, 0x00},
{ 1, 0x1f9},
{ 1, 0x1fa},
{ 14, 0x00},
{ 1, 0x1fb},
{ 15, 0x00},
{ 1, 0x1fc},
{ 6, 0x00},
{ 1, 0x1fd},
{ 8, 0x00},
{ 1, 0x1fe},
{ 6, 0x00},
{ 1, 0x1ff},
{ 15, 0x00},
{ 1, 0x200},
{ 14, 0x00},
{ 1, 0x201},
{ 15, 0x00},
{ 1, 0x202},
{ 15, 0x00},
{ 1, 0x203},
{ 15, 0x00},
{ 1, 0x204},
{ 14, 0x00},
{ 1, 0x205},
{ 8, 0x00},
{ 1, 0x206},
{ 6, 0x00},
{ 1, 0x207},
{ 8, 0x00},
{ 1, 0x208},
{ 6, 0x00},
{ 1, 0x209},
{ 15, 0x00},
{ 1, 0x20a},
{ 14, 0x00},
{ 1, 0x20b},
{ 15, 0x00},
{ 1, 0x20c},
{ 15, 0x00},
{ 1, 0x20d},
{ 15, 0x00},
{ 1, 0x20e},
{ 14, 0x00},
{ 1, 0x20f},
{ 8, 0x00},
{ 1, 0x210},
{ 6, 0x00},
{ 1, 0x211},
{ 8, 0x00},
{ 1, 0x212},
{ 6, 0x00},
{ 1, 0x213},
{ 7, 0x00},
{ 1, 0x214},
{ 1, 0x215},
{ 5, 0x00},
{ 1, 0x216},
{ 8, 0x00},
{ 1, 0x217},
{ 6, 0x00},
{ 1, 0x218},
{ 8, 0x00},
{ 1, 0x219},
{ 15, 0x00},
{ 1, 0x21a},
{ 14, 0x00},
{ 1, 0x21b},
{ 1, 0x21c},
{ 14, 0x00},
{ 1, 0x21d},
{ 15, 0x00},
{ 1, 0x21e},
{ 6, 0x00},
{ 1, 0x21f},
{ 8, 0x00},
{ 1, 0x220},
{ 6, 0x00},
{ 1, 0x221},
{ 7, 0x00},
{ 1, 0x222},
{ 1, 0x223},
{ 5, 0x00},
{ 1, 0x224},
{ 8, 0x00},
{ 1, 0x225},
{ 6, 0x00},
{ 1, 0x226},
{ 8, 0x00},
{ 1, 0x227},
{ 6, 0x00},
{ 1, 0x228},
{ 15, 0x00},
{ 1, 0x229},
{ 15, 0x00},
{ 1, 0x22a},
{ 14, 0x00},
{ 1, 0x22b},
{ 15, 0x00},
{ 1, 0x22c},
{ 15, 0x00},
{ 1, 0x22d},
{ 15, 0x00},
{ 1, 0x22e},
{ 7, 0x00},
{ 1, 0x22f},
{ 6, 0x00},
{ 1, 0x230},
{ 8, 0x00},
{ 1, 0x231},
{ 6, 0x00},
{ 1, 0x232},
{ 15, 0x00},
{ 1, 0x233},
{ 15, 0x00},
{ 1, 0x234},
{ 14, 0x00},
{ 1, 0x235},
{ 15, 0x00},
{ 1, 0x236},
{ 15, 0x00},
{ 1, 0x237},
{ 15, 0x00},
{ 1, 0x238},
{ 14, 0x00},
{ 1, 0x239},
{ 15, 0x00},
{ 1, 0x23a},
{ 15, 0x00},
{ 1, 0x23b},
{ 15, 0x00},
{ 1, 0x23c},
{ 7, 0x00},
{ 1, 0x23d},
{ 6, 0x00},
{ 1, 0x23e},
{ 15, 0x00},
{ 1, 0x23f},
{ 15, 0x00},
{ 1, 0x240},
{ 7, 0x00},
{ 1, 0x241},
{ 1, 0x242},
{ 5, 0x00},
{ 1, 0x243},
{ 15, 0x00},
{ 1, 0x244},
{ 15, 0x00},
{ 1, 0x245},
{ 14, 0x00},
{ 1, 0x246},
{ 15, 0x00},
{ 1, 0x247},
{ 15, 0x00},
{ 1, 0x248},
{ 15, 0x00},
{ 1, 0x249},
{ 14, 0x00},
{ 1, 0x24a},
{ 15, 0x00},
{ 1, 0x24b},
{ 15, 0x00},
{ 1, 0x24c},
{ 15, 0x00},
{ 1, 0x24d},
{ 14, 0x00},
{ 1, 0x24e},
{ 15, 0x00},
{ 1, 0x24f},
{ 15, 0x00},
{ 1, 0x250},
{ 15, 0x00},
{ 1, 0x251},
{ 14, 0x00},
{ 1, 0x252},
{ 15, 0x00},
{ 1, 0x253},
{ 15, 0x00},
{ 1, 0x254},
{ 15, 0x00},
{ 1, 0x255},
{ 14, 0x00},
{ 1, 0x256},
{ 15, 0x00},
{ 1, 0x257},
{ 15, 0x00},
{ 1, 0x258},
{ 15, 0x00},
{ 1, 0x259},
{ 14, 0x00},
{ 1, 0x25a},
{ 15, 0x00},
{ 1, 0x25b},
{ 15, 0x00},
{ 1, 0x25c},
{ 15, 0x00},
{ 1, 0x25d},
{ 14, 0x00},
{ 1, 0x25e},
{ 15, 0x00},
{ 1, 0x25f},
{ 15, 0x00},
{ 1, 0x260},
{ 15, 0x00},
{ 1, 0x261},
{ 14, 0x00},
{ 1, 0x262},
{ 15, 0x00},
{ 1, 0x263},
{ 15, 0x00},
{ 1, 0x264},
{ 15, 0x00},
{ 1, 0x265},
{ 14, 0x00},
{ 1, 0x266},
{ 15, 0x00},
{ 1, 0x267},
{ 15, 0x00},
{ 1, 0x268},
{ 15, 0x00},
{ 1, 0x269},
{ 14, 0x00},
{ 1, 0x26a},
{ 15, 0x00},
{ 1, 0x26b},
{ 15, 0x00},
{ 1, 0x26c},
{ 21, 0x00},
{ 1, 0x26d},
{ 15, 0x00},
{ 1, 0x26e},
{ 14, 0x00},
{ 1, 0x26f},
{ 15, 0x00},
{ 1, 0x270},
{ 15, 0x00},
{ 1, 0x271},
{ 15, 0x00},
{ 1, 0x272},
{ 14, 0x00},
{ 1, 0x273},
{ 15, 0x00},
{ 1, 0x274},
{ 15, 0x00},
{ 1, 0x275},
{ 15, 0x00},
{ 1, 0x276},
{ 14, 0x00},
{ 1, 0x277},
{ 15, 0x00},
{ 1, 0x278},
{ 15, 0x00},
{ 1, 0x279},
{ 15, 0x00},
{ 1, 0x27a},
{ 14, 0x00},
{ 1, 0x27b},
{ 15, 0x00},
{ 1, 0x27c},
{ 15, 0x00},
{ 1, 0x27d},
{ 15, 0x00},
{ 1, 0x27e},
{ 14, 0x00},
{ 1, 0x27f},
{ 1, 0x280},
{ 14, 0x00},
{ 1, 0x281},
{ 15, 0x00},
{ 1, 0x282},
{ 15, 0x00},
{ 1, 0x283},
{ 14, 0x00},
{ 1, 0x284},
{ 15, 0x00},
{ 1, 0x285},
{ 15, 0x00},
{ 1, 0x286},
{ 15, 0x00},
{ 1, 0x287},
{ 14, 0x00},
{ 1, 0x288},
{ 15, 0x00},
{ 1, 0x289},
{ 15, 0x00},
{ 1, 0x28a},
{ 15, 0x00},
{ 1, 0x28b},
{ 14, 0x00},
{ 1, 0x28c},
{ 15, 0x00},
{ 1, 0x28d},
{ 15, 0x00},
{ 1, 0x28e},
{ 15, 0x00},
{ 1, 0x28f},
{ 14, 0x00},
{ 1, 0x290},
{ 15, 0x00},
{ 1, 0x291},
{ 15, 0x00},
{ 1, 0x292},
{ 15, 0x00},
{ 1, 0x293},
{ 14, 0x00},
{ 1, 0x294},
{ 1, 0x295},
{ 14, 0x00},
{ 1, 0x296},
{ 15, 0x00},
{ 1, 0x297},
{ 15, 0x00},
{ 1, 0x298},
{ 14, 0x00},
{ 1, 0x299},
{ 1, 0x29a},
{ 14, 0x00},
{ 1, 0x29b},
{ 15, 0x00},
{ 1, 0x29c},
{ 15, 0x00},
{ 1, 0x29d},
{ 14, 0x00},
{ 1, 0x29e},
{ 15, 0x00},
{ 1, 0x29f},
{ 15, 0x00},
{ 1, 0x2a0},
{ 15, 0x00},
{ 1, 0x2a1},
{ 15, 0x00},
{ 1, 0x2a2},
{ 15, 0x00},
{ 1, 0x2a3},
{ 15, 0x00},
{ 1, 0x2a4},
{ 15, 0x00},
{ 1, 0x2a5},
{ 15, 0x00},
{ 1, 0x2a6},
{ 15, 0x00},
{ 1, 0x2a7},
{ 15, 0x00},
{ 1, 0x2a8},
{ 15, 0x00},
{ 1, 0x2a9},
{0},
};
static textstartup void _PyUnicode_CompIndex_init(void) {
int i, j, k;
for (k = i = 0; i < 1146; ++i) {
for (j = 0; j < _PyUnicode_CompIndex_rodata[i][0]; ++j) {
_PyUnicode_CompIndex[k++] = _PyUnicode_CompIndex_rodata[i][1];
}
}
}
const void *const _PyUnicode_CompIndex_ctor[] initarray = {
_PyUnicode_CompIndex_init,
};
const unsigned int _PyUnicode_CompData[1449] = {
0, 0, 0, 922746880, 17, 9011200, 3758096384, 1101, 0, 50594176,
204473872, 1082138624, 3288404736, 339559424, 3489660931, 2151677980,
128, 0, 31360, 122880, 2181038080, 0, 7866368, 2147483648, 960, 0,
2014838784, 274726912, 8448, 0, 136192, 0, 0, 67, 199, 0, 123040, 0,
469762048, 2, 0, 0, 3846, 0, 61568, 246336, 234881024, 30, 0, 1075380224,
6619186, 35921596, 145753168, 3611298992, 3, 134289920, 530436, 0,
128843776, 0, 144703488, 3783264448, 2256535553, 7, 2013265920,
1073741944, 2326559, 252706816, 37749022, 0, 0, 31104, 74240, 0, 1196032,
0, 505544704, 15436, 0, 17344, 0, 0, 15802368, 0, 252968960, 0, 30888,
427819008, 1728066368, 1409361920, 2147790850, 847881, 985, 30343168,
136840208, 0, 2994733056, 7, 0, 618496, 0, 1931, 0, 1232, 123648, 0, 0,
499712, 31662080, 0, 20316160, 0, 0, 247424, 0, 0, 641024, 2596864, 0, 0,
4054843392, 0, 2642411520, 2013265920, 60, 31694848, 0, 0, 2029518848, 0,
0, 991232, 134217728, 2147483769, 2646047, 6848512, 0, 30992, 0,
2743074816, 2348810240, 60, 2684354560, 40, 3877, 2032140288, 0, 0,
3540019456, 1409394688, 3758776323, 2152054804, 258408501, 44040192,
274728772, 8416, 3489660928, 2018304, 0, 1073741824, 61, 0, 0,
3848336032, 1, 0, 1342177280, 5, 0, 254541824, 69206360, 2120, 0, 497280,
0, 350208, 0, 0, 3887, 91226804, 0, 2550136832, 7, 0, 720896, 63717376,
0, 45875736, 0, 3443523584, 3, 0, 364544, 31899648, 0, 23200013,
2042626048, 0, 249280, 0, 1677721600, 2953236483, 2150432781, 11927642,
28835840, 191921048, 979375872, 184583424, 1, 537312256, 31924471, 0,
24248320, 15596, 3888182176, 1, 0, 4160749568, 121, 63980008, 93, 0,
4095769112, 3506438144, 3, 335544320, 8007741, 0, 2277277696, 24510574,
147340784, 3906994176, 3179294465, 7, 0, 16228352, 1073741824, 256376926,
0, 198705152, 6096, 0, 0, 8013824, 0, 0, 14683978, 59244994, 269485848,
2311069792, 2734715392, 117278, 269381632, 4218912, 0, 1027735552,
4027056128, 0, 16704, 100663296, 60, 31477760, 0, 0, 15374, 0, 0,
151028608, 1, 2952790016, 16, 0, 35258368, 0, 0, 1937768448, 0,
1476395008, 1110256, 0, 0, 2016673792, 0, 2218786816, 318767111, 30,
2163243008, 2149392398, 257851450, 36307219, 123208796, 125872,
2373976064, 235013376, 4, 536870912, 983, 0, 73663570, 61640, 246624, 0,
3948032, 0, 0, 16416768, 285, 150501508, 4624, 0, 3456106496, 3, 0,
2147483648, 145, 0, 2344, 0, 655298944, 30, 4026531840, 33, 0, 0, 30868,
0, 494144, 1442840576, 2952790076, 2685321460, 2151383069, 19595412, 602,
3968862072, 1, 151054336, 267778, 0, 64577536, 0, 0, 1212, 3315597312, 3,
1778384896, 2, 0, 8126464, 0, 0, 61832, 15648, 0, 0, 15833088, 0,
10190848, 7733, 0, 0, 20096, 81408, 0, 0, 126730240, 0, 82837504,
3822059520, 1, 990592, 3964416, 0, 1073741824, 1936, 1015414784, 0, 0,
4236247040, 82944, 246784, 2684354560, 968, 0, 85983232, 3832545280, 1,
1174405120, 738197505, 121, 63512576, 0, 0, 127402952, 513806144,
2810204992, 3959566080, 8076289, 1075122176, 2156085306, 263, 109314048,
514913896, 0, 0, 1409286144, 121, 0, 254509056, 44695552, 0, 0, 497216,
0, 3355443200, 1612779530, 66, 0, 15542, 0, 10976, 0, 2080374784,
2952790137, 2859029, 0, 1019346944, 0, 0, 22592, 1991424, 3355443200,
1437712, 0, 510328832, 15662, 0, 11424, 0, 0, 15951872, 3221225472,
11632774, 1021444096, 0, 124656, 0, 4060086272, 3624134657, 1612091399,
5980205, 16515072, 96222670, 490736520, 2243969696, 0, 2483249152,
15964283, 0, 12156928, 7799, 31188, 0, 1048576000, 4261412879, 60, 0,
2147483648, 511905600, 746, 0, 2705576160, 2550136839, 30, 2415919104,
488, 0, 1025121931, 0, 3730833408, 3145744195, 1713305856, 2013265924,
3759141108, 128336862, 0, 2077491200, 0, 2755669824, 7, 4026531840, 5, 0,
12517376, 1025900544, 0, 0, 501056, 0, 1744830464, 3690751, 0, 0, 0,
65032, 2843738112, 1004039, 4019200, 0, 0, 1962, 62652416, 0, 1061158912,
0, 130048, 268435456, 15, 0, 3844, 2063089024, 3963617280, 1, 0, 4031488,
0, 63291392, 0, 0, 4136632320, 126208, 505216, 0, 2684354560, 246, 0,
3878, 145752064, 0, 248256, 0, 283648, 0, 4177920, 0, 0, 249036800, 7536,
3934257152, 0, 484352, 0, 2276048896, 3922, 15702, 0, 2856321024, 7,
245248, 0, 4153344, 0, 509, 253231104, 0, 75497472, 2181038095, 8059965,
32264192, 0, 0, 15750, 0, 247264, 0, 0, 284596224, 3221225965, 1973, 0,
4138205184, 0, 645922816, 15, 570368, 3758096384, 969, 0, 1110, 0, 16352,
0, 0, 2148458496, 29, 15400960, 0, 1896, 0, 1460120576, 1744830479, 61,
0, 128745472, 0, 2059156834, 3947888640, 1, 0, 4023808, 1073741824,
63095265, 0, 0, 4037541888, 123248, 0, 0, 2423865344, 536871154,
127189962, 0, 2039480320, 0, 248992, 1711276032, 30, 0, 0, 255033344,
1022361600, 0, 124816, 0, 4093640704, 60, 31961088, 0, 0, 2053898240, 0,
0, 3658444288, 2147483678, 123, 0, 258932736, 7906, 0, 0, 1837610816,
3254779919, 61, 0, 129482752, 0, 0, 63256, 3120815424, 3992977415, 30, 0,
64847872, 0, 0, 31680, 3709988528, 2004877315, 2026767, 0, 536870912,
990, 0, 129499136, 0, 2063597568, 0, 252416, 0, 30, 0, 0, 252182528, 0,
234881024, 15, 7894016, 2293760, 0, 0, 0, 4488, 15840, 0, 406811648, 14,
66527232, 2030, 0, 4164943872, 127120, 0, 0, 8318976, 33325056, 113, 0,
2086666240, 63688, 0, 2299520256, 3, 0, 1139081216, 1994, 8140, 0, 0,
3305633408, 1, 3229574144, 1073742078, 117, 523763712, 15986, 0,
3808689920, 0, 0, 2432319488, 500, 0, 0, 4284481536, 0, 4110417920,
232975, 1207959552, 33456383, 15384576, 0, 2103705600, 0, 4269801472,
1744947079, 4117023, 0, 0, 268304384, 0, 32464, 4169138176, 3, 0,
2147483648, 3850491, 2147483648, 531632088, 0, 0, 3225673728, 7, 0,
821932032, 507, 0, 0, 493387208, 3793875200, 3, 3892314112, 964670, 0, 0,
522260368, 0, 0, 4039375040, 1979711495, 482847, 268435456, 66716157,
31784960, 0, 4186471616, 130400, 0, 0, 3221225472, 3981563, 0, 0,
2097430144, 4265607168, 261281, 0, 876540928, 15, 66854912, 2040, 971, 0,
0, 2818572288, 2052367, 0, 3221225472, 1020, 528220160, 1948, 0,
3623878656, 4128223367, 4187679, 0, 0, 266928128, 912, 0, 0, 3951034368,
15, 2155841536, 29, 133808128, 0, 2144337920, 0, 31328, 0, 0, 2007040,
3221225472, 257, 0, 645922816, 2587885568, 0, 0, 1051648, 4194304, 0, 0,
2476, 1276125192, 922746880, 1, 637952, 0, 8495104, 0, 163840000, 4196,
20032, 0, 402653184, 8, 0, 20545536, 0, 330825728, 8304, 40448,
4060086272, 4, 1073741824, 79, 0, 0, 666894336, 0, 80640, 0, 2281701376,
1610612774, 154, 0, 290193408, 1157627904, 0, 0, 634368, 539133952,
1073741900, 311, 163446784, 0, 2342518784, 0, 3321888768, 1106953,
5132288, 0, 0, 2232, 0, 968884224, 1, 3154116608, 2289683, 10362880, 0,
1267, 0, 20304, 0, 0, 3355443200, 39, 20660224, 0, 2222, 0, 36544,
1996488704, 4, 0, 2147483648, 310, 162922496, 0, 20128, 0, 0, 1476395008,
1073741863, 2173223108, 786, 3144, 1650458624, 0, 0, 0, 3543040,
3221225472, 436, 226492416, 0, 0, 150080, 1644167168, 18, 9650176, 0,
164298752, 5016, 0, 3523307872, 2483398146, 11, 0, 2147483648, 98960114,
395706368, 0, 0, 201216, 0, 0, 1073741926, 53592473, 1636, 6550, 0,
1384120320, 435715, 1742336, 0, 2147483648, 116261750, 3550, 0,
3147825152, 1, 0, 805306368, 129, 0, 3459, 1814036480, 0, 221504,
201326592, 27, 0, 0, 226951168, 0, 27720, 1734344704, 3, 1785088, 0, 0,
0, 3488, 1828978688, 0, 223328, 0, 3960832, 2415919104, 483, 0, 0,
4074766336, 0, 497472, 0, 1073741824, 243, 127549440, 0, 15704,
3948937216, 1, 2902458368, 30, 16103424, 0, 258146304, 0, 31516,
3674210304, 3, 2021632, 0, 1073741824, 130089952, 0, 2113945100,
4029677568, 254113, 117440512, 4129311, 536870912, 504, 0, 0, 4229431296,
0, 516352, 167772160, 63, 33054720, 0, 0, 0, 64568, 3271811392, 7,
540941312, 2952790142, 65118704, 0, 1058152207, 0, 129184, 0, 0,
1476395008, 252, 132317184, 0, 16154, 4175429632, 1, 0, 0, 16545792,
65159168, 1989, 1042947859, 0, 0, 2365587456, 2038799, 0, 0, 2277949440,
3982, 2089827908, 0, 3825460416, 587202567, 4082207, 1879048192,
66200050, 0, 8082, 0, 0, 3380609024, 15, 8278016, 2684354560, 1010,
529924096, 0, 0, 0, 1035136, 2956874752, 124, 65388544, 2022, 1046093611,
0, 4079088368, 3, 2071040, 0, 0, 2147483648, 4045, 2121269248, 0, 258976,
2650800128, 31, 0, 0, 265256960, 1046740992, 31952, 3871342592, 3,
1780429568, 62, 32731136, 0, 0, 0, 4089510352, 1, 0, 0, 16379904,
3221225472, 262047694, 0, 31996, 3896508416, 512259, 2317304576, 62, 0,
0, 525078437, 0, 0, 3535798272, 1025671, 1346282496, 125, 65716224, 0,
1051336531, 0, 128368, 0, 0, 3623878656, 32887034, 0, 0, 0, 64248,
3632267264, 1028615, 2550136832, 16580733, 1139564544, 2009, 1053687808,
32388, 4097835008, 3, 2073344, 0, 0, 0, 4050, 2123628544, 0, 259264,
2801795072, 31, 0, 2147483648, 263587802, 0, 4248862136, 3982491648,
514883, 3724541952, 8299582, 1073741824, 1013, 531300352, 0, 0, 0,
1037824, 3019898880, 126, 66437120, 0, 8111, 0, 0, 3640655872, 15,
8325120, 1073741824, 1022, 532086784, 0, 0, 4081057792, 1042183,
1006632960, 127, 3221225472, 2033, 1072562176, 0, 0, 4001366016, 2088463,
0, 0, 2147483648, 4079, 17204, 430964736, 2, 0, 0, 17657856, 1073741824,
2163, 1134428160, 0, 138464, 0, 0, 536870912, 272, 142753792, 0, 17432,
574619648, 2, 0, 0, 17903616, 1073741824, 2192, 1149763584, 0, 140400, 0,
0, 1207959552, 274, 144392192, 0, 17604, 654311424, 2, 0, 0, 18057216, 0,
2205, 1156186112, 0, 141184, 0, 0, 3355443200, 275, 144703488, 0, 17666,
771751936, 2, 0, 0, 18286592, 0, 2209, 1158283264, 0, 141440, 0, 0,
1207959552, 276, 146309120, 0, 17862, 717225984, 2, 0, 0, 18180096,
2147483648, 2219, 1163788288, 0, 143008, 0, 0, 1476395008, 279,
146472960, 0, 17882, 0, 397952, 1275068416, 48, 0, 0, 405209088, 0,
49472, 171966464, 6, 3167232, 0, 0, 0, 6187, 3244294144, 0, 396096,
1543503872, 48, 0, 0, 405733376, 0, 49536, 205520896, 6, 3171584, 0, 0,
2147483648, 6195, 3248750592, 0, 474353152, 1929379852, 6350896, 0, 0,
406519808, 12407, 0, 0, 1024204352, 4160749592, 12711008, 50978816, 0, 0,
0, 100256, 721420288, 12, 6380544, 0, 779, 0, 0, 2240806912, 1, 797952,
1811939328, 97, 51085312, 0, 0, 0, 99792, 788529152, 12, 6388736, 0, 780,
0, 0, 2249195520, 1, 799040, 2382364672, 97, 51154944, 0, 0, 0,
219252352, 3, 0, 1275068416, 25600195, 3323641856, 3125, 1639198937, 0,
0, 1845493760, 3202328, 0, 0, 205373440, 0, 25072, 261095424, 3, 0, 0,
25677824, 2147483648, 3135, 0, 2228224000, 8, 4466432, 1442840576, 545,
3221225472, 8741, 288292864, 1, 883949568, 2255249, 0, 3995695104,
145093714, 0, 2329739264, 0, 284396, 0, 4607488,
};
| 31,635 | 1,318 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Modules/unicodedata_extendedcase.c | #include "libc/nexgen32e/kompressor.h"
#include "third_party/python/Modules/unicodedata.h"
/* clang-format off */
/* GENERATED BY third_party/python/Tools/unicode/makeunicodedata.py 3.2 */
const char16_t _PyUnicode_ExtendedCase[1236] = {
181,
956,
924,
223,
115,
115,
83,
83,
83,
115,
105,
775,
304,
329,
700,
110,
700,
78,
383,
115,
83,
496,
106,
780,
74,
780,
837,
953,
921,
912,
953,
776,
769,
921,
776,
769,
944,
965,
776,
769,
933,
776,
769,
962,
963,
931,
976,
946,
914,
977,
952,
920,
981,
966,
934,
982,
960,
928,
1008,
954,
922,
1009,
961,
929,
1013,
949,
917,
1415,
1381,
1410,
1333,
1362,
1333,
1410,
43888,
5024,
5024,
43889,
5025,
5025,
43890,
5026,
5026,
43891,
5027,
5027,
43892,
5028,
5028,
43893,
5029,
5029,
43894,
5030,
5030,
43895,
5031,
5031,
43896,
5032,
5032,
43897,
5033,
5033,
43898,
5034,
5034,
43899,
5035,
5035,
43900,
5036,
5036,
43901,
5037,
5037,
43902,
5038,
5038,
43903,
5039,
5039,
43904,
5040,
5040,
43905,
5041,
5041,
43906,
5042,
5042,
43907,
5043,
5043,
43908,
5044,
5044,
43909,
5045,
5045,
43910,
5046,
5046,
43911,
5047,
5047,
43912,
5048,
5048,
43913,
5049,
5049,
43914,
5050,
5050,
43915,
5051,
5051,
43916,
5052,
5052,
43917,
5053,
5053,
43918,
5054,
5054,
43919,
5055,
5055,
43920,
5056,
5056,
43921,
5057,
5057,
43922,
5058,
5058,
43923,
5059,
5059,
43924,
5060,
5060,
43925,
5061,
5061,
43926,
5062,
5062,
43927,
5063,
5063,
43928,
5064,
5064,
43929,
5065,
5065,
43930,
5066,
5066,
43931,
5067,
5067,
43932,
5068,
5068,
43933,
5069,
5069,
43934,
5070,
5070,
43935,
5071,
5071,
43936,
5072,
5072,
43937,
5073,
5073,
43938,
5074,
5074,
43939,
5075,
5075,
43940,
5076,
5076,
43941,
5077,
5077,
43942,
5078,
5078,
43943,
5079,
5079,
43944,
5080,
5080,
43945,
5081,
5081,
43946,
5082,
5082,
43947,
5083,
5083,
43948,
5084,
5084,
43949,
5085,
5085,
43950,
5086,
5086,
43951,
5087,
5087,
43952,
5088,
5088,
43953,
5089,
5089,
43954,
5090,
5090,
43955,
5091,
5091,
43956,
5092,
5092,
43957,
5093,
5093,
43958,
5094,
5094,
43959,
5095,
5095,
43960,
5096,
5096,
43961,
5097,
5097,
43962,
5098,
5098,
43963,
5099,
5099,
43964,
5100,
5100,
43965,
5101,
5101,
43966,
5102,
5102,
43967,
5103,
5103,
5112,
5104,
5104,
5113,
5105,
5105,
5114,
5106,
5106,
5115,
5107,
5107,
5116,
5108,
5108,
5117,
5109,
5109,
5112,
5104,
5104,
5113,
5105,
5105,
5114,
5106,
5106,
5115,
5107,
5107,
5116,
5108,
5108,
5117,
5109,
5109,
7296,
1074,
1042,
7297,
1076,
1044,
7298,
1086,
1054,
7299,
1089,
1057,
7300,
1090,
1058,
7301,
1090,
1058,
7302,
1098,
1066,
7303,
1123,
1122,
7304,
42571,
42570,
7830,
104,
817,
72,
817,
7831,
116,
776,
84,
776,
7832,
119,
778,
87,
778,
7833,
121,
778,
89,
778,
7834,
97,
702,
65,
702,
7835,
7777,
7776,
223,
115,
115,
7838,
8016,
965,
787,
933,
787,
8018,
965,
787,
768,
933,
787,
768,
8020,
965,
787,
769,
933,
787,
769,
8022,
965,
787,
834,
933,
787,
834,
8064,
7936,
953,
7944,
921,
8072,
8065,
7937,
953,
7945,
921,
8073,
8066,
7938,
953,
7946,
921,
8074,
8067,
7939,
953,
7947,
921,
8075,
8068,
7940,
953,
7948,
921,
8076,
8069,
7941,
953,
7949,
921,
8077,
8070,
7942,
953,
7950,
921,
8078,
8071,
7943,
953,
7951,
921,
8079,
8064,
7936,
953,
7944,
921,
8072,
8065,
7937,
953,
7945,
921,
8073,
8066,
7938,
953,
7946,
921,
8074,
8067,
7939,
953,
7947,
921,
8075,
8068,
7940,
953,
7948,
921,
8076,
8069,
7941,
953,
7949,
921,
8077,
8070,
7942,
953,
7950,
921,
8078,
8071,
7943,
953,
7951,
921,
8079,
8080,
7968,
953,
7976,
921,
8088,
8081,
7969,
953,
7977,
921,
8089,
8082,
7970,
953,
7978,
921,
8090,
8083,
7971,
953,
7979,
921,
8091,
8084,
7972,
953,
7980,
921,
8092,
8085,
7973,
953,
7981,
921,
8093,
8086,
7974,
953,
7982,
921,
8094,
8087,
7975,
953,
7983,
921,
8095,
8080,
7968,
953,
7976,
921,
8088,
8081,
7969,
953,
7977,
921,
8089,
8082,
7970,
953,
7978,
921,
8090,
8083,
7971,
953,
7979,
921,
8091,
8084,
7972,
953,
7980,
921,
8092,
8085,
7973,
953,
7981,
921,
8093,
8086,
7974,
953,
7982,
921,
8094,
8087,
7975,
953,
7983,
921,
8095,
8096,
8032,
953,
8040,
921,
8104,
8097,
8033,
953,
8041,
921,
8105,
8098,
8034,
953,
8042,
921,
8106,
8099,
8035,
953,
8043,
921,
8107,
8100,
8036,
953,
8044,
921,
8108,
8101,
8037,
953,
8045,
921,
8109,
8102,
8038,
953,
8046,
921,
8110,
8103,
8039,
953,
8047,
921,
8111,
8096,
8032,
953,
8040,
921,
8104,
8097,
8033,
953,
8041,
921,
8105,
8098,
8034,
953,
8042,
921,
8106,
8099,
8035,
953,
8043,
921,
8107,
8100,
8036,
953,
8044,
921,
8108,
8101,
8037,
953,
8045,
921,
8109,
8102,
8038,
953,
8046,
921,
8110,
8103,
8039,
953,
8047,
921,
8111,
8114,
8048,
953,
8122,
921,
8122,
837,
8115,
945,
953,
913,
921,
8124,
8116,
940,
953,
902,
921,
902,
837,
8118,
945,
834,
913,
834,
8119,
945,
834,
953,
913,
834,
921,
913,
834,
837,
8115,
945,
953,
913,
921,
8124,
8126,
953,
921,
8130,
8052,
953,
8138,
921,
8138,
837,
8131,
951,
953,
919,
921,
8140,
8132,
942,
953,
905,
921,
905,
837,
8134,
951,
834,
919,
834,
8135,
951,
834,
953,
919,
834,
921,
919,
834,
837,
8131,
951,
953,
919,
921,
8140,
8146,
953,
776,
768,
921,
776,
768,
8147,
953,
776,
769,
921,
776,
769,
8150,
953,
834,
921,
834,
8151,
953,
776,
834,
921,
776,
834,
8162,
965,
776,
768,
933,
776,
768,
8163,
965,
776,
769,
933,
776,
769,
8164,
961,
787,
929,
787,
8166,
965,
834,
933,
834,
8167,
965,
776,
834,
933,
776,
834,
8178,
8060,
953,
8186,
921,
8186,
837,
8179,
969,
953,
937,
921,
8188,
8180,
974,
953,
911,
921,
911,
837,
8182,
969,
834,
937,
834,
8183,
969,
834,
953,
937,
834,
921,
937,
834,
837,
8179,
969,
953,
937,
921,
8188,
43888,
5024,
5024,
43889,
5025,
5025,
43890,
5026,
5026,
43891,
5027,
5027,
43892,
5028,
5028,
43893,
5029,
5029,
43894,
5030,
5030,
43895,
5031,
5031,
43896,
5032,
5032,
43897,
5033,
5033,
43898,
5034,
5034,
43899,
5035,
5035,
43900,
5036,
5036,
43901,
5037,
5037,
43902,
5038,
5038,
43903,
5039,
5039,
43904,
5040,
5040,
43905,
5041,
5041,
43906,
5042,
5042,
43907,
5043,
5043,
43908,
5044,
5044,
43909,
5045,
5045,
43910,
5046,
5046,
43911,
5047,
5047,
43912,
5048,
5048,
43913,
5049,
5049,
43914,
5050,
5050,
43915,
5051,
5051,
43916,
5052,
5052,
43917,
5053,
5053,
43918,
5054,
5054,
43919,
5055,
5055,
43920,
5056,
5056,
43921,
5057,
5057,
43922,
5058,
5058,
43923,
5059,
5059,
43924,
5060,
5060,
43925,
5061,
5061,
43926,
5062,
5062,
43927,
5063,
5063,
43928,
5064,
5064,
43929,
5065,
5065,
43930,
5066,
5066,
43931,
5067,
5067,
43932,
5068,
5068,
43933,
5069,
5069,
43934,
5070,
5070,
43935,
5071,
5071,
43936,
5072,
5072,
43937,
5073,
5073,
43938,
5074,
5074,
43939,
5075,
5075,
43940,
5076,
5076,
43941,
5077,
5077,
43942,
5078,
5078,
43943,
5079,
5079,
43944,
5080,
5080,
43945,
5081,
5081,
43946,
5082,
5082,
43947,
5083,
5083,
43948,
5084,
5084,
43949,
5085,
5085,
43950,
5086,
5086,
43951,
5087,
5087,
43952,
5088,
5088,
43953,
5089,
5089,
43954,
5090,
5090,
43955,
5091,
5091,
43956,
5092,
5092,
43957,
5093,
5093,
43958,
5094,
5094,
43959,
5095,
5095,
43960,
5096,
5096,
43961,
5097,
5097,
43962,
5098,
5098,
43963,
5099,
5099,
43964,
5100,
5100,
43965,
5101,
5101,
43966,
5102,
5102,
43967,
5103,
5103,
64256,
102,
102,
70,
70,
70,
102,
64257,
102,
105,
70,
73,
70,
105,
64258,
102,
108,
70,
76,
70,
108,
64259,
102,
102,
105,
70,
70,
73,
70,
102,
105,
64260,
102,
102,
108,
70,
70,
76,
70,
102,
108,
64261,
115,
116,
83,
84,
83,
116,
64262,
115,
116,
83,
84,
83,
116,
64275,
1396,
1398,
1348,
1350,
1348,
1398,
64276,
1396,
1381,
1348,
1333,
1348,
1381,
64277,
1396,
1387,
1348,
1339,
1348,
1387,
64278,
1406,
1398,
1358,
1350,
1358,
1398,
64279,
1396,
1389,
1348,
1341,
1348,
1389,
};
| 12,348 | 1,244 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Modules/unicodedata.h | #ifndef COSMOPOLITAN_THIRD_PARTY_PYTHON_MODULES_UNICODEDATA_H_
#define COSMOPOLITAN_THIRD_PARTY_PYTHON_MODULES_UNICODEDATA_H_
#include "libc/assert.h"
#include "third_party/python/Include/object.h"
#include "third_party/python/Include/unicodeobject.h"
#define _Hanghoul_SBase 0xAC00
#define _Hanghoul_LBase 0x1100
#define _Hanghoul_VBase 0x1161
#define _Hanghoul_TBase 0x11A7
#define _Hanghoul_LCount 19
#define _Hanghoul_VCount 21
#define _Hanghoul_TCount 28
#define _Hanghoul_NCount (_Hanghoul_VCount * _Hanghoul_TCount)
#define _Hanghoul_SCount (_Hanghoul_LCount * _Hanghoul_NCount)
#if !(__ASSEMBLER__ + __LINKER__ + 0)
COSMOPOLITAN_C_START_
/* clang-format off */
/*
* [jart] if it adds 1.2megs to each binary then it should have an api
* breaking this up into separate files allows ld to do its job
*/
#define UCD_Check(o) (Py_TYPE(o)==&UCD_Type)
#define get_old_record(self, v) ((((PreviousDBVersion*)self)->getrecord)(v))
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 normalization_quick_check; /* see is_normalized() */
} _PyUnicode_Record;
typedef struct {
/* sequence of fields should be the same as in merge_old_version */
const unsigned char bidir_changed;
const unsigned char category_changed;
const unsigned char decimal_changed;
const unsigned char mirrored_changed;
const unsigned char east_asian_width_changed;
const double numeric_changed;
} _PyUnicode_ChangeRecord;
typedef struct {
PyObject_HEAD
const char *name;
const _PyUnicode_ChangeRecord *(*getrecord)(Py_UCS4);
Py_UCS4 (*normalization)(Py_UCS4);
} PreviousDBVersion;
typedef struct {
int start;
short count;
short index;
} _PyUnicode_Reindex;
typedef struct {
/*
These are either deltas to the character or offsets in
_PyUnicode_ExtendedCase.
*/
int upper;
int lower;
int title;
/* Note if more flag space is needed, decimal and digit could be unified. */
unsigned char decimal;
unsigned char digit;
unsigned short flags;
} _PyUnicode_TypeRecord;
/*
* In Unicode 6.0.0, the sequences contain at most 4 BMP chars,
* so we are using Py_UCS2 seq[4]. This needs to be updated if longer
* sequences or sequences with non-BMP chars are added.
* unicodedata_lookup should be adapted too.
*/
typedef struct{
int seqlen;
Py_UCS2 seq[4];
} _PyUnicode_NamedSequence;
extern PyTypeObject UCD_Type;
int _PyUnicode_IsUnifiedIdeograph(Py_UCS4);
const _PyUnicode_Record *_PyUnicode_GetRecord(Py_UCS4);
PyObject *_PyUnicode_NfcNfkc(PyObject *, PyObject *, int);
PyObject *_PyUnicode_NfdNfkd(PyObject *, PyObject *, int);
int _PyUnicode_IsNormalized(PyObject *, PyObject *, int, int);
int _PyUnicode_GetUcName(PyObject *, Py_UCS4, char *, int, int);
int _PyUnicode_FindNfcIndex(const _PyUnicode_Reindex *, Py_UCS4);
void _PyUnicode_FindSyllable(const char *, int *, int *, int, int);
int _PyUnicode_GetCode(PyObject *, const char *, int, Py_UCS4 *, int);
void _PyUnicode_GetDecompRecord(PyObject *, Py_UCS4, int *, int *, int *);
COSMOPOLITAN_C_END_
#endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */
#endif /* COSMOPOLITAN_THIRD_PARTY_PYTHON_MODULES_UNICODEDATA_H_ */
| 3,589 | 102 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Modules/_testbuffer.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:8;coding:utf-8 -*-â
âvi: set net ft=c ts=4 sts=4 sw=4 fenc=utf-8 :viâ
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ¡
â Python 3 â
â https://docs.python.org/3/license.html â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
#define PY_SSIZE_T_CLEAN
#include "third_party/python/Include/abstract.h"
#include "third_party/python/Include/boolobject.h"
#include "third_party/python/Include/bytesobject.h"
#include "third_party/python/Include/descrobject.h"
#include "third_party/python/Include/floatobject.h"
#include "third_party/python/Include/import.h"
#include "third_party/python/Include/longobject.h"
#include "third_party/python/Include/memoryobject.h"
#include "third_party/python/Include/modsupport.h"
#include "third_party/python/Include/object.h"
#include "third_party/python/Include/objimpl.h"
#include "third_party/python/Include/pyerrors.h"
#include "third_party/python/Include/pymem.h"
#include "third_party/python/Include/sliceobject.h"
#include "third_party/python/Include/yoink.h"
/* clang-format off */
PYTHON_PROVIDE("_testbuffer");
PYTHON_PROVIDE("_testbuffer.ND_FORTRAN");
PYTHON_PROVIDE("_testbuffer.ND_GETBUF_FAIL");
PYTHON_PROVIDE("_testbuffer.ND_GETBUF_UNDEFINED");
PYTHON_PROVIDE("_testbuffer.ND_MAX_NDIM");
PYTHON_PROVIDE("_testbuffer.ND_PIL");
PYTHON_PROVIDE("_testbuffer.ND_REDIRECT");
PYTHON_PROVIDE("_testbuffer.ND_SCALAR");
PYTHON_PROVIDE("_testbuffer.ND_VAREXPORT");
PYTHON_PROVIDE("_testbuffer.ND_WRITABLE");
PYTHON_PROVIDE("_testbuffer.PyBUF_ANY_CONTIGUOUS");
PYTHON_PROVIDE("_testbuffer.PyBUF_CONTIG");
PYTHON_PROVIDE("_testbuffer.PyBUF_CONTIG_RO");
PYTHON_PROVIDE("_testbuffer.PyBUF_C_CONTIGUOUS");
PYTHON_PROVIDE("_testbuffer.PyBUF_FORMAT");
PYTHON_PROVIDE("_testbuffer.PyBUF_FULL");
PYTHON_PROVIDE("_testbuffer.PyBUF_FULL_RO");
PYTHON_PROVIDE("_testbuffer.PyBUF_F_CONTIGUOUS");
PYTHON_PROVIDE("_testbuffer.PyBUF_INDIRECT");
PYTHON_PROVIDE("_testbuffer.PyBUF_ND");
PYTHON_PROVIDE("_testbuffer.PyBUF_READ");
PYTHON_PROVIDE("_testbuffer.PyBUF_RECORDS");
PYTHON_PROVIDE("_testbuffer.PyBUF_RECORDS_RO");
PYTHON_PROVIDE("_testbuffer.PyBUF_SIMPLE");
PYTHON_PROVIDE("_testbuffer.PyBUF_STRIDED");
PYTHON_PROVIDE("_testbuffer.PyBUF_STRIDED_RO");
PYTHON_PROVIDE("_testbuffer.PyBUF_STRIDES");
PYTHON_PROVIDE("_testbuffer.PyBUF_WRITABLE");
PYTHON_PROVIDE("_testbuffer.PyBUF_WRITE");
PYTHON_PROVIDE("_testbuffer.cmp_contig");
PYTHON_PROVIDE("_testbuffer.get_contiguous");
PYTHON_PROVIDE("_testbuffer.get_pointer");
PYTHON_PROVIDE("_testbuffer.get_sizeof_void_p");
PYTHON_PROVIDE("_testbuffer.is_contiguous");
PYTHON_PROVIDE("_testbuffer.ndarray");
PYTHON_PROVIDE("_testbuffer.py_buffer_to_contiguous");
PYTHON_PROVIDE("_testbuffer.slice_indices");
PYTHON_PROVIDE("_testbuffer.staticarray");
/* C Extension module to test all aspects of PEP-3118.
Written by Stefan Krah. */
/* struct module */
static PyObject *structmodule = NULL;
static PyObject *Struct = NULL;
static PyObject *calcsize = NULL;
/* cache simple format string */
static const char *simple_fmt = "B";
static PyObject *simple_format = NULL;
#define SIMPLE_FORMAT(fmt) (fmt == NULL || strcmp(fmt, "B") == 0)
#define FIX_FORMAT(fmt) (fmt == NULL ? "B" : fmt)
/**************************************************************************/
/* NDArray Object */
/**************************************************************************/
static PyTypeObject NDArray_Type;
#define NDArray_Check(v) (Py_TYPE(v) == &NDArray_Type)
#define CHECK_LIST_OR_TUPLE(v) \
if (!PyList_Check(v) && !PyTuple_Check(v)) { \
PyErr_SetString(PyExc_TypeError, \
#v " must be a list or a tuple"); \
return NULL; \
} \
#define PyMem_XFree(v) \
do { if (v) PyMem_Free(v); } while (0)
/* Maximum number of dimensions. */
#define ND_MAX_NDIM (2 * PyBUF_MAX_NDIM)
/* Check for the presence of suboffsets in the first dimension. */
#define HAVE_PTR(suboffsets) (suboffsets && suboffsets[0] >= 0)
/* Adjust ptr if suboffsets are present. */
#define ADJUST_PTR(ptr, suboffsets) \
(HAVE_PTR(suboffsets) ? *((char**)ptr) + suboffsets[0] : ptr)
/* Default: NumPy style (strides), read-only, no var-export, C-style layout */
#define ND_DEFAULT 0x000
/* User configurable flags for the ndarray */
#define ND_VAREXPORT 0x001 /* change layout while buffers are exported */
/* User configurable flags for each base buffer */
#define ND_WRITABLE 0x002 /* mark base buffer as writable */
#define ND_FORTRAN 0x004 /* Fortran contiguous layout */
#define ND_SCALAR 0x008 /* scalar: ndim = 0 */
#define ND_PIL 0x010 /* convert to PIL-style array (suboffsets) */
#define ND_REDIRECT 0x020 /* redirect buffer requests */
#define ND_GETBUF_FAIL 0x040 /* trigger getbuffer failure */
#define ND_GETBUF_UNDEFINED 0x080 /* undefined view.obj */
/* Internal flags for the base buffer */
#define ND_C 0x100 /* C contiguous layout (default) */
#define ND_OWN_ARRAYS 0x200 /* consumer owns arrays */
/* ndarray properties */
#define ND_IS_CONSUMER(nd) \
(((NDArrayObject *)nd)->head == &((NDArrayObject *)nd)->staticbuf)
/* ndbuf->flags properties */
#define ND_C_CONTIGUOUS(flags) (!!(flags&(ND_SCALAR|ND_C)))
#define ND_FORTRAN_CONTIGUOUS(flags) (!!(flags&(ND_SCALAR|ND_FORTRAN)))
#define ND_ANY_CONTIGUOUS(flags) (!!(flags&(ND_SCALAR|ND_C|ND_FORTRAN)))
/* getbuffer() requests */
#define REQ_INDIRECT(flags) ((flags&PyBUF_INDIRECT) == PyBUF_INDIRECT)
#define REQ_C_CONTIGUOUS(flags) ((flags&PyBUF_C_CONTIGUOUS) == PyBUF_C_CONTIGUOUS)
#define REQ_F_CONTIGUOUS(flags) ((flags&PyBUF_F_CONTIGUOUS) == PyBUF_F_CONTIGUOUS)
#define REQ_ANY_CONTIGUOUS(flags) ((flags&PyBUF_ANY_CONTIGUOUS) == PyBUF_ANY_CONTIGUOUS)
#define REQ_STRIDES(flags) ((flags&PyBUF_STRIDES) == PyBUF_STRIDES)
#define REQ_SHAPE(flags) ((flags&PyBUF_ND) == PyBUF_ND)
#define REQ_WRITABLE(flags) (flags&PyBUF_WRITABLE)
#define REQ_FORMAT(flags) (flags&PyBUF_FORMAT)
/* Single node of a list of base buffers. The list is needed to implement
changes in memory layout while exported buffers are active. */
/* static PyTypeObject NDArray_Type; */
struct ndbuf;
typedef struct ndbuf {
struct ndbuf *next;
struct ndbuf *prev;
Py_ssize_t len; /* length of data */
Py_ssize_t offset; /* start of the array relative to data */
char *data; /* raw data */
int flags; /* capabilities of the base buffer */
Py_ssize_t exports; /* number of exports */
Py_buffer base; /* base buffer */
} ndbuf_t;
typedef struct {
PyObject_HEAD
int flags; /* ndarray flags */
ndbuf_t staticbuf; /* static buffer for re-exporting mode */
ndbuf_t *head; /* currently active base buffer */
} NDArrayObject;
static ndbuf_t *
ndbuf_new(Py_ssize_t nitems, Py_ssize_t itemsize, Py_ssize_t offset, int flags)
{
ndbuf_t *ndbuf;
Py_buffer *base;
Py_ssize_t len;
len = nitems * itemsize;
if (offset % itemsize) {
PyErr_SetString(PyExc_ValueError,
"offset must be a multiple of itemsize");
return NULL;
}
if (offset < 0 || offset+itemsize > len) {
PyErr_SetString(PyExc_ValueError, "offset out of bounds");
return NULL;
}
ndbuf = PyMem_Malloc(sizeof *ndbuf);
if (ndbuf == NULL) {
PyErr_NoMemory();
return NULL;
}
ndbuf->next = NULL;
ndbuf->prev = NULL;
ndbuf->len = len;
ndbuf->offset= offset;
ndbuf->data = PyMem_Malloc(len);
if (ndbuf->data == NULL) {
PyErr_NoMemory();
PyMem_Free(ndbuf);
return NULL;
}
ndbuf->flags = flags;
ndbuf->exports = 0;
base = &ndbuf->base;
base->obj = NULL;
base->buf = ndbuf->data;
base->len = len;
base->itemsize = 1;
base->readonly = 0;
base->format = NULL;
base->ndim = 1;
base->shape = NULL;
base->strides = NULL;
base->suboffsets = NULL;
base->internal = ndbuf;
return ndbuf;
}
static void
ndbuf_free(ndbuf_t *ndbuf)
{
Py_buffer *base = &ndbuf->base;
PyMem_XFree(ndbuf->data);
PyMem_XFree(base->format);
PyMem_XFree(base->shape);
PyMem_XFree(base->strides);
PyMem_XFree(base->suboffsets);
PyMem_Free(ndbuf);
}
static void
ndbuf_push(NDArrayObject *nd, ndbuf_t *elt)
{
elt->next = nd->head;
if (nd->head) nd->head->prev = elt;
nd->head = elt;
elt->prev = NULL;
}
static void
ndbuf_delete(NDArrayObject *nd, ndbuf_t *elt)
{
if (elt->prev)
elt->prev->next = elt->next;
else
nd->head = elt->next;
if (elt->next)
elt->next->prev = elt->prev;
ndbuf_free(elt);
}
static void
ndbuf_pop(NDArrayObject *nd)
{
ndbuf_delete(nd, nd->head);
}
static PyObject *
ndarray_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
NDArrayObject *nd;
nd = PyObject_New(NDArrayObject, &NDArray_Type);
if (nd == NULL)
return NULL;
nd->flags = 0;
nd->head = NULL;
return (PyObject *)nd;
}
static void
ndarray_dealloc(NDArrayObject *self)
{
if (self->head) {
if (ND_IS_CONSUMER(self)) {
Py_buffer *base = &self->head->base;
if (self->head->flags & ND_OWN_ARRAYS) {
PyMem_XFree(base->shape);
PyMem_XFree(base->strides);
PyMem_XFree(base->suboffsets);
}
PyBuffer_Release(base);
}
else {
while (self->head)
ndbuf_pop(self);
}
}
PyObject_Del(self);
}
static int
ndarray_init_staticbuf(PyObject *exporter, NDArrayObject *nd, int flags)
{
Py_buffer *base = &nd->staticbuf.base;
if (PyObject_GetBuffer(exporter, base, flags) < 0)
return -1;
nd->head = &nd->staticbuf;
nd->head->next = NULL;
nd->head->prev = NULL;
nd->head->len = -1;
nd->head->offset = -1;
nd->head->data = NULL;
nd->head->flags = base->readonly ? 0 : ND_WRITABLE;
nd->head->exports = 0;
return 0;
}
static void
init_flags(ndbuf_t *ndbuf)
{
if (ndbuf->base.ndim == 0)
ndbuf->flags |= ND_SCALAR;
if (ndbuf->base.suboffsets)
ndbuf->flags |= ND_PIL;
if (PyBuffer_IsContiguous(&ndbuf->base, 'C'))
ndbuf->flags |= ND_C;
if (PyBuffer_IsContiguous(&ndbuf->base, 'F'))
ndbuf->flags |= ND_FORTRAN;
}
/****************************************************************************/
/* Buffer/List conversions */
/****************************************************************************/
static Py_ssize_t *strides_from_shape(const ndbuf_t *, int flags);
/* Get number of members in a struct: see issue #12740 */
typedef struct {
PyObject_HEAD
Py_ssize_t s_size;
Py_ssize_t s_len;
} PyPartialStructObject;
static Py_ssize_t
get_nmemb(PyObject *s)
{
return ((PyPartialStructObject *)s)->s_len;
}
/* Pack all items into the buffer of 'obj'. The 'format' parameter must be
in struct module syntax. For standard C types, a single item is an integer.
For compound types, a single item is a tuple of integers. */
static int
pack_from_list(PyObject *obj, PyObject *items, PyObject *format,
Py_ssize_t itemsize)
{
PyObject *structobj, *pack_into;
PyObject *args, *offset;
PyObject *item, *tmp;
Py_ssize_t nitems; /* number of items */
Py_ssize_t nmemb; /* number of members in a single item */
Py_ssize_t i, j;
int ret = 0;
assert(PyObject_CheckBuffer(obj));
assert(PyList_Check(items) || PyTuple_Check(items));
structobj = PyObject_CallFunctionObjArgs(Struct, format, NULL);
if (structobj == NULL)
return -1;
nitems = PySequence_Fast_GET_SIZE(items);
nmemb = get_nmemb(structobj);
assert(nmemb >= 1);
pack_into = PyObject_GetAttrString(structobj, "pack_into");
if (pack_into == NULL) {
Py_DECREF(structobj);
return -1;
}
/* nmemb >= 1 */
args = PyTuple_New(2 + nmemb);
if (args == NULL) {
Py_DECREF(pack_into);
Py_DECREF(structobj);
return -1;
}
offset = NULL;
for (i = 0; i < nitems; i++) {
/* Loop invariant: args[j] are borrowed references or NULL. */
PyTuple_SET_ITEM(args, 0, obj);
for (j = 1; j < 2+nmemb; j++)
PyTuple_SET_ITEM(args, j, NULL);
Py_XDECREF(offset);
offset = PyLong_FromSsize_t(i*itemsize);
if (offset == NULL) {
ret = -1;
break;
}
PyTuple_SET_ITEM(args, 1, offset);
item = PySequence_Fast_GET_ITEM(items, i);
if ((PyBytes_Check(item) || PyLong_Check(item) ||
PyFloat_Check(item)) && nmemb == 1) {
PyTuple_SET_ITEM(args, 2, item);
}
else if ((PyList_Check(item) || PyTuple_Check(item)) &&
PySequence_Length(item) == nmemb) {
for (j = 0; j < nmemb; j++) {
tmp = PySequence_Fast_GET_ITEM(item, j);
PyTuple_SET_ITEM(args, 2+j, tmp);
}
}
else {
PyErr_SetString(PyExc_ValueError,
"mismatch between initializer element and format string");
ret = -1;
break;
}
tmp = PyObject_CallObject(pack_into, args);
if (tmp == NULL) {
ret = -1;
break;
}
Py_DECREF(tmp);
}
Py_INCREF(obj); /* args[0] */
/* args[1]: offset is either NULL or should be dealloc'd */
for (i = 2; i < 2+nmemb; i++) {
tmp = PyTuple_GET_ITEM(args, i);
Py_XINCREF(tmp);
}
Py_DECREF(args);
Py_DECREF(pack_into);
Py_DECREF(structobj);
return ret;
}
/* Pack single element */
static int
pack_single(char *ptr, PyObject *item, const char *fmt, Py_ssize_t itemsize)
{
PyObject *structobj = NULL, *pack_into = NULL, *args = NULL;
PyObject *format = NULL, *mview = NULL, *zero = NULL;
Py_ssize_t i, nmemb;
int ret = -1;
PyObject *x;
if (fmt == NULL) fmt = "B";
format = PyUnicode_FromString(fmt);
if (format == NULL)
goto out;
structobj = PyObject_CallFunctionObjArgs(Struct, format, NULL);
if (structobj == NULL)
goto out;
nmemb = get_nmemb(structobj);
assert(nmemb >= 1);
mview = PyMemoryView_FromMemory(ptr, itemsize, PyBUF_WRITE);
if (mview == NULL)
goto out;
zero = PyLong_FromLong(0);
if (zero == NULL)
goto out;
pack_into = PyObject_GetAttrString(structobj, "pack_into");
if (pack_into == NULL)
goto out;
args = PyTuple_New(2+nmemb);
if (args == NULL)
goto out;
PyTuple_SET_ITEM(args, 0, mview);
PyTuple_SET_ITEM(args, 1, zero);
if ((PyBytes_Check(item) || PyLong_Check(item) ||
PyFloat_Check(item)) && nmemb == 1) {
PyTuple_SET_ITEM(args, 2, item);
}
else if ((PyList_Check(item) || PyTuple_Check(item)) &&
PySequence_Length(item) == nmemb) {
for (i = 0; i < nmemb; i++) {
x = PySequence_Fast_GET_ITEM(item, i);
PyTuple_SET_ITEM(args, 2+i, x);
}
}
else {
PyErr_SetString(PyExc_ValueError,
"mismatch between initializer element and format string");
goto args_out;
}
x = PyObject_CallObject(pack_into, args);
if (x != NULL) {
Py_DECREF(x);
ret = 0;
}
args_out:
for (i = 0; i < 2+nmemb; i++)
Py_XINCREF(PyTuple_GET_ITEM(args, i));
Py_XDECREF(args);
out:
Py_XDECREF(pack_into);
Py_XDECREF(zero);
Py_XDECREF(mview);
Py_XDECREF(structobj);
Py_XDECREF(format);
return ret;
}
static void
copy_rec(const Py_ssize_t *shape, Py_ssize_t ndim, Py_ssize_t itemsize,
char *dptr, const Py_ssize_t *dstrides, const Py_ssize_t *dsuboffsets,
char *sptr, const Py_ssize_t *sstrides, const Py_ssize_t *ssuboffsets,
char *mem)
{
Py_ssize_t i;
assert(ndim >= 1);
if (ndim == 1) {
if (!HAVE_PTR(dsuboffsets) && !HAVE_PTR(ssuboffsets) &&
dstrides[0] == itemsize && sstrides[0] == itemsize) {
memmove(dptr, sptr, shape[0] * itemsize);
}
else {
char *p;
assert(mem != NULL);
for (i=0, p=mem; i<shape[0]; p+=itemsize, sptr+=sstrides[0], i++) {
char *xsptr = ADJUST_PTR(sptr, ssuboffsets);
memcpy(p, xsptr, itemsize);
}
for (i=0, p=mem; i<shape[0]; p+=itemsize, dptr+=dstrides[0], i++) {
char *xdptr = ADJUST_PTR(dptr, dsuboffsets);
memcpy(xdptr, p, itemsize);
}
}
return;
}
for (i = 0; i < shape[0]; dptr+=dstrides[0], sptr+=sstrides[0], i++) {
char *xdptr = ADJUST_PTR(dptr, dsuboffsets);
char *xsptr = ADJUST_PTR(sptr, ssuboffsets);
copy_rec(shape+1, ndim-1, itemsize,
xdptr, dstrides+1, dsuboffsets ? dsuboffsets+1 : NULL,
xsptr, sstrides+1, ssuboffsets ? ssuboffsets+1 : NULL,
mem);
}
}
static int
cmp_structure(Py_buffer *dest, Py_buffer *src)
{
Py_ssize_t i;
if (strcmp(FIX_FORMAT(dest->format), FIX_FORMAT(src->format)) != 0 ||
dest->itemsize != src->itemsize ||
dest->ndim != src->ndim)
return -1;
for (i = 0; i < dest->ndim; i++) {
if (dest->shape[i] != src->shape[i])
return -1;
if (dest->shape[i] == 0)
break;
}
return 0;
}
/* Copy src to dest. Both buffers must have the same format, itemsize,
ndim and shape. Copying is atomic, the function never fails with
a partial copy. */
static int
copy_buffer(Py_buffer *dest, Py_buffer *src)
{
char *mem = NULL;
assert(dest->ndim > 0);
if (cmp_structure(dest, src) < 0) {
PyErr_SetString(PyExc_ValueError,
"ndarray assignment: lvalue and rvalue have different structures");
return -1;
}
if ((dest->suboffsets && dest->suboffsets[dest->ndim-1] >= 0) ||
(src->suboffsets && src->suboffsets[src->ndim-1] >= 0) ||
dest->strides[dest->ndim-1] != dest->itemsize ||
src->strides[src->ndim-1] != src->itemsize) {
mem = PyMem_Malloc(dest->shape[dest->ndim-1] * dest->itemsize);
if (mem == NULL) {
PyErr_NoMemory();
return -1;
}
}
copy_rec(dest->shape, dest->ndim, dest->itemsize,
dest->buf, dest->strides, dest->suboffsets,
src->buf, src->strides, src->suboffsets,
mem);
PyMem_XFree(mem);
return 0;
}
/* Unpack single element */
static PyObject *
unpack_single(char *ptr, const char *fmt, Py_ssize_t itemsize)
{
PyObject *x, *unpack_from, *mview;
if (fmt == NULL) {
fmt = "B";
itemsize = 1;
}
unpack_from = PyObject_GetAttrString(structmodule, "unpack_from");
if (unpack_from == NULL)
return NULL;
mview = PyMemoryView_FromMemory(ptr, itemsize, PyBUF_READ);
if (mview == NULL) {
Py_DECREF(unpack_from);
return NULL;
}
x = PyObject_CallFunction(unpack_from, "sO", fmt, mview);
Py_DECREF(unpack_from);
Py_DECREF(mview);
if (x == NULL)
return NULL;
if (PyTuple_GET_SIZE(x) == 1) {
PyObject *tmp = PyTuple_GET_ITEM(x, 0);
Py_INCREF(tmp);
Py_DECREF(x);
return tmp;
}
return x;
}
/* Unpack a multi-dimensional matrix into a nested list. Return a scalar
for ndim = 0. */
static PyObject *
unpack_rec(PyObject *unpack_from, char *ptr, PyObject *mview, char *item,
const Py_ssize_t *shape, const Py_ssize_t *strides,
const Py_ssize_t *suboffsets, Py_ssize_t ndim, Py_ssize_t itemsize)
{
PyObject *lst, *x;
Py_ssize_t i;
assert(ndim >= 0);
assert(shape != NULL);
assert(strides != NULL);
if (ndim == 0) {
memcpy(item, ptr, itemsize);
x = PyObject_CallFunctionObjArgs(unpack_from, mview, NULL);
if (x == NULL)
return NULL;
if (PyTuple_GET_SIZE(x) == 1) {
PyObject *tmp = PyTuple_GET_ITEM(x, 0);
Py_INCREF(tmp);
Py_DECREF(x);
return tmp;
}
return x;
}
lst = PyList_New(shape[0]);
if (lst == NULL)
return NULL;
for (i = 0; i < shape[0]; ptr+=strides[0], i++) {
char *nextptr = ADJUST_PTR(ptr, suboffsets);
x = unpack_rec(unpack_from, nextptr, mview, item,
shape+1, strides+1, suboffsets ? suboffsets+1 : NULL,
ndim-1, itemsize);
if (x == NULL) {
Py_DECREF(lst);
return NULL;
}
PyList_SET_ITEM(lst, i, x);
}
return lst;
}
static PyObject *
ndarray_as_list(NDArrayObject *nd)
{
PyObject *structobj = NULL, *unpack_from = NULL;
PyObject *lst = NULL, *mview = NULL;
Py_buffer *base = &nd->head->base;
Py_ssize_t *shape = base->shape;
Py_ssize_t *strides = base->strides;
Py_ssize_t simple_shape[1];
Py_ssize_t simple_strides[1];
char *item = NULL;
PyObject *format;
char *fmt = base->format;
base = &nd->head->base;
if (fmt == NULL) {
PyErr_SetString(PyExc_ValueError,
"ndarray: tolist() does not support format=NULL, use "
"tobytes()");
return NULL;
}
if (shape == NULL) {
assert(ND_C_CONTIGUOUS(nd->head->flags));
assert(base->strides == NULL);
assert(base->ndim <= 1);
shape = simple_shape;
shape[0] = base->len;
strides = simple_strides;
strides[0] = base->itemsize;
}
else if (strides == NULL) {
assert(ND_C_CONTIGUOUS(nd->head->flags));
strides = strides_from_shape(nd->head, 0);
if (strides == NULL)
return NULL;
}
format = PyUnicode_FromString(fmt);
if (format == NULL)
goto out;
structobj = PyObject_CallFunctionObjArgs(Struct, format, NULL);
Py_DECREF(format);
if (structobj == NULL)
goto out;
unpack_from = PyObject_GetAttrString(structobj, "unpack_from");
if (unpack_from == NULL)
goto out;
item = PyMem_Malloc(base->itemsize);
if (item == NULL) {
PyErr_NoMemory();
goto out;
}
mview = PyMemoryView_FromMemory(item, base->itemsize, PyBUF_WRITE);
if (mview == NULL)
goto out;
lst = unpack_rec(unpack_from, base->buf, mview, item,
shape, strides, base->suboffsets,
base->ndim, base->itemsize);
out:
Py_XDECREF(mview);
PyMem_XFree(item);
Py_XDECREF(unpack_from);
Py_XDECREF(structobj);
if (strides != base->strides && strides != simple_strides)
PyMem_XFree(strides);
return lst;
}
/****************************************************************************/
/* Initialize ndbuf */
/****************************************************************************/
/*
State of a new ndbuf during initialization. 'OK' means that initialization
is complete. 'PTR' means that a pointer has been initialized, but the
state of the memory is still undefined and ndbuf->offset is disregarded.
+-----------------+-----------+-------------+----------------+
| | ndbuf_new | init_simple | init_structure |
+-----------------+-----------+-------------+----------------+
| next | OK (NULL) | OK | OK |
+-----------------+-----------+-------------+----------------+
| prev | OK (NULL) | OK | OK |
+-----------------+-----------+-------------+----------------+
| len | OK | OK | OK |
+-----------------+-----------+-------------+----------------+
| offset | OK | OK | OK |
+-----------------+-----------+-------------+----------------+
| data | PTR | OK | OK |
+-----------------+-----------+-------------+----------------+
| flags | user | user | OK |
+-----------------+-----------+-------------+----------------+
| exports | OK (0) | OK | OK |
+-----------------+-----------+-------------+----------------+
| base.obj | OK (NULL) | OK | OK |
+-----------------+-----------+-------------+----------------+
| base.buf | PTR | PTR | OK |
+-----------------+-----------+-------------+----------------+
| base.len | len(data) | len(data) | OK |
+-----------------+-----------+-------------+----------------+
| base.itemsize | 1 | OK | OK |
+-----------------+-----------+-------------+----------------+
| base.readonly | 0 | OK | OK |
+-----------------+-----------+-------------+----------------+
| base.format | NULL | OK | OK |
+-----------------+-----------+-------------+----------------+
| base.ndim | 1 | 1 | OK |
+-----------------+-----------+-------------+----------------+
| base.shape | NULL | NULL | OK |
+-----------------+-----------+-------------+----------------+
| base.strides | NULL | NULL | OK |
+-----------------+-----------+-------------+----------------+
| base.suboffsets | NULL | NULL | OK |
+-----------------+-----------+-------------+----------------+
| base.internal | OK | OK | OK |
+-----------------+-----------+-------------+----------------+
*/
static Py_ssize_t
get_itemsize(PyObject *format)
{
PyObject *tmp;
Py_ssize_t itemsize;
tmp = PyObject_CallFunctionObjArgs(calcsize, format, NULL);
if (tmp == NULL)
return -1;
itemsize = PyLong_AsSsize_t(tmp);
Py_DECREF(tmp);
return itemsize;
}
static char *
get_format(PyObject *format)
{
PyObject *tmp;
char *fmt;
tmp = PyUnicode_AsASCIIString(format);
if (tmp == NULL)
return NULL;
fmt = PyMem_Malloc(PyBytes_GET_SIZE(tmp)+1);
if (fmt == NULL) {
PyErr_NoMemory();
Py_DECREF(tmp);
return NULL;
}
strcpy(fmt, PyBytes_AS_STRING(tmp));
Py_DECREF(tmp);
return fmt;
}
static int
init_simple(ndbuf_t *ndbuf, PyObject *items, PyObject *format,
Py_ssize_t itemsize)
{
PyObject *mview;
Py_buffer *base = &ndbuf->base;
int ret;
mview = PyMemoryView_FromBuffer(base);
if (mview == NULL)
return -1;
ret = pack_from_list(mview, items, format, itemsize);
Py_DECREF(mview);
if (ret < 0)
return -1;
base->readonly = !(ndbuf->flags & ND_WRITABLE);
base->itemsize = itemsize;
base->format = get_format(format);
if (base->format == NULL)
return -1;
return 0;
}
static Py_ssize_t *
seq_as_ssize_array(PyObject *seq, Py_ssize_t len, int is_shape)
{
Py_ssize_t *dest;
Py_ssize_t x, i;
/* ndim = len <= ND_MAX_NDIM, so PyMem_New() is actually not needed. */
dest = PyMem_New(Py_ssize_t, len);
if (dest == NULL) {
PyErr_NoMemory();
return NULL;
}
for (i = 0; i < len; i++) {
PyObject *tmp = PySequence_Fast_GET_ITEM(seq, i);
if (!PyLong_Check(tmp)) {
PyErr_Format(PyExc_ValueError,
"elements of %s must be integers",
is_shape ? "shape" : "strides");
PyMem_Free(dest);
return NULL;
}
x = PyLong_AsSsize_t(tmp);
if (PyErr_Occurred()) {
PyMem_Free(dest);
return NULL;
}
if (is_shape && x < 0) {
PyErr_Format(PyExc_ValueError,
"elements of shape must be integers >= 0");
PyMem_Free(dest);
return NULL;
}
dest[i] = x;
}
return dest;
}
static Py_ssize_t *
strides_from_shape(const ndbuf_t *ndbuf, int flags)
{
const Py_buffer *base = &ndbuf->base;
Py_ssize_t *s, i;
s = PyMem_Malloc(base->ndim * (sizeof *s));
if (s == NULL) {
PyErr_NoMemory();
return NULL;
}
if (flags & ND_FORTRAN) {
s[0] = base->itemsize;
for (i = 1; i < base->ndim; i++)
s[i] = s[i-1] * base->shape[i-1];
}
else {
s[base->ndim-1] = base->itemsize;
for (i = base->ndim-2; i >= 0; i--)
s[i] = s[i+1] * base->shape[i+1];
}
return s;
}
/* Bounds check:
len := complete length of allocated memory
offset := start of the array
A single array element is indexed by:
i = indices[0] * strides[0] + indices[1] * strides[1] + ...
imin is reached when all indices[n] combined with positive strides are 0
and all indices combined with negative strides are shape[n]-1, which is
the maximum index for the nth dimension.
imax is reached when all indices[n] combined with negative strides are 0
and all indices combined with positive strides are shape[n]-1.
*/
static int
verify_structure(Py_ssize_t len, Py_ssize_t itemsize, Py_ssize_t offset,
const Py_ssize_t *shape, const Py_ssize_t *strides,
Py_ssize_t ndim)
{
Py_ssize_t imin, imax;
Py_ssize_t n;
assert(ndim >= 0);
if (ndim == 0 && (offset < 0 || offset+itemsize > len))
goto invalid_combination;
for (n = 0; n < ndim; n++)
if (strides[n] % itemsize) {
PyErr_SetString(PyExc_ValueError,
"strides must be a multiple of itemsize");
return -1;
}
for (n = 0; n < ndim; n++)
if (shape[n] == 0)
return 0;
imin = imax = 0;
for (n = 0; n < ndim; n++)
if (strides[n] <= 0)
imin += (shape[n]-1) * strides[n];
else
imax += (shape[n]-1) * strides[n];
if (imin + offset < 0 || imax + offset + itemsize > len)
goto invalid_combination;
return 0;
invalid_combination:
PyErr_SetString(PyExc_ValueError,
"invalid combination of buffer, shape and strides");
return -1;
}
/*
Convert a NumPy-style array to an array using suboffsets to stride in
the first dimension. Requirements: ndim > 0.
Contiguous example
==================
Input:
------
shape = {2, 2, 3};
strides = {6, 3, 1};
suboffsets = NULL;
data = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11};
buf = &data[0]
Output:
-------
shape = {2, 2, 3};
strides = {sizeof(char *), 3, 1};
suboffsets = {0, -1, -1};
data = {p1, p2, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11};
| | ^ ^
`---'---' |
| |
`---------------------'
buf = &data[0]
So, in the example the input resembles the three-dimensional array
char v[2][2][3], while the output resembles an array of two pointers
to two-dimensional arrays: char (*v[2])[2][3].
Non-contiguous example:
=======================
Input (with offset and negative strides):
-----------------------------------------
shape = {2, 2, 3};
strides = {-6, 3, -1};
offset = 8
suboffsets = NULL;
data = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11};
Output:
-------
shape = {2, 2, 3};
strides = {-sizeof(char *), 3, -1};
suboffsets = {2, -1, -1};
newdata = {p1, p2, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11};
| | ^ ^ ^ ^
`---'---' | | `- p2+suboffsets[0]
| `-----------|--- p1+suboffsets[0]
`---------------------'
buf = &newdata[1] # striding backwards over the pointers.
suboffsets[0] is the same as the offset that one would specify if
the two {2, 3} subarrays were created directly, hence the name.
*/
static int
init_suboffsets(ndbuf_t *ndbuf)
{
Py_buffer *base = &ndbuf->base;
Py_ssize_t start, step;
Py_ssize_t imin, suboffset0;
Py_ssize_t addsize;
Py_ssize_t n;
char *data;
assert(base->ndim > 0);
assert(base->suboffsets == NULL);
/* Allocate new data with additional space for shape[0] pointers. */
addsize = base->shape[0] * (sizeof (char *));
/* Align array start to a multiple of 8. */
addsize = 8 * ((addsize + 7) / 8);
data = PyMem_Malloc(ndbuf->len + addsize);
if (data == NULL) {
PyErr_NoMemory();
return -1;
}
memcpy(data + addsize, ndbuf->data, ndbuf->len);
PyMem_Free(ndbuf->data);
ndbuf->data = data;
ndbuf->len += addsize;
base->buf = ndbuf->data;
/* imin: minimum index of the input array relative to ndbuf->offset.
suboffset0: offset for each sub-array of the output. This is the
same as calculating -imin' for a sub-array of ndim-1. */
imin = suboffset0 = 0;
for (n = 0; n < base->ndim; n++) {
if (base->shape[n] == 0)
break;
if (base->strides[n] <= 0) {
Py_ssize_t x = (base->shape[n]-1) * base->strides[n];
imin += x;
suboffset0 += (n >= 1) ? -x : 0;
}
}
/* Initialize the array of pointers to the sub-arrays. */
start = addsize + ndbuf->offset + imin;
step = base->strides[0] < 0 ? -base->strides[0] : base->strides[0];
for (n = 0; n < base->shape[0]; n++)
((char **)base->buf)[n] = (char *)base->buf + start + n*step;
/* Initialize suboffsets. */
base->suboffsets = PyMem_Malloc(base->ndim * (sizeof *base->suboffsets));
if (base->suboffsets == NULL) {
PyErr_NoMemory();
return -1;
}
base->suboffsets[0] = suboffset0;
for (n = 1; n < base->ndim; n++)
base->suboffsets[n] = -1;
/* Adjust strides for the first (zeroth) dimension. */
if (base->strides[0] >= 0) {
base->strides[0] = sizeof(char *);
}
else {
/* Striding backwards. */
base->strides[0] = -(Py_ssize_t)sizeof(char *);
if (base->shape[0] > 0)
base->buf = (char *)base->buf + (base->shape[0]-1) * sizeof(char *);
}
ndbuf->flags &= ~(ND_C|ND_FORTRAN);
ndbuf->offset = 0;
return 0;
}
static void
init_len(Py_buffer *base)
{
Py_ssize_t i;
base->len = 1;
for (i = 0; i < base->ndim; i++)
base->len *= base->shape[i];
base->len *= base->itemsize;
}
static int
init_structure(ndbuf_t *ndbuf, PyObject *shape, PyObject *strides,
Py_ssize_t ndim)
{
Py_buffer *base = &ndbuf->base;
base->ndim = (int)ndim;
if (ndim == 0) {
if (ndbuf->flags & ND_PIL) {
PyErr_SetString(PyExc_TypeError,
"ndim = 0 cannot be used in conjunction with ND_PIL");
return -1;
}
ndbuf->flags |= (ND_SCALAR|ND_C|ND_FORTRAN);
return 0;
}
/* shape */
base->shape = seq_as_ssize_array(shape, ndim, 1);
if (base->shape == NULL)
return -1;
/* strides */
if (strides) {
base->strides = seq_as_ssize_array(strides, ndim, 0);
}
else {
base->strides = strides_from_shape(ndbuf, ndbuf->flags);
}
if (base->strides == NULL)
return -1;
if (verify_structure(base->len, base->itemsize, ndbuf->offset,
base->shape, base->strides, ndim) < 0)
return -1;
/* buf */
base->buf = ndbuf->data + ndbuf->offset;
/* len */
init_len(base);
/* ndbuf->flags */
if (PyBuffer_IsContiguous(base, 'C'))
ndbuf->flags |= ND_C;
if (PyBuffer_IsContiguous(base, 'F'))
ndbuf->flags |= ND_FORTRAN;
/* convert numpy array to suboffset representation */
if (ndbuf->flags & ND_PIL) {
/* modifies base->buf, base->strides and base->suboffsets **/
return init_suboffsets(ndbuf);
}
return 0;
}
static ndbuf_t *
init_ndbuf(PyObject *items, PyObject *shape, PyObject *strides,
Py_ssize_t offset, PyObject *format, int flags)
{
ndbuf_t *ndbuf;
Py_ssize_t ndim;
Py_ssize_t nitems;
Py_ssize_t itemsize;
/* ndim = len(shape) */
CHECK_LIST_OR_TUPLE(shape)
ndim = PySequence_Fast_GET_SIZE(shape);
if (ndim > ND_MAX_NDIM) {
PyErr_Format(PyExc_ValueError,
"ndim must not exceed %d", ND_MAX_NDIM);
return NULL;
}
/* len(strides) = len(shape) */
if (strides) {
CHECK_LIST_OR_TUPLE(strides)
if (PySequence_Fast_GET_SIZE(strides) == 0)
strides = NULL;
else if (flags & ND_FORTRAN) {
PyErr_SetString(PyExc_TypeError,
"ND_FORTRAN cannot be used together with strides");
return NULL;
}
else if (PySequence_Fast_GET_SIZE(strides) != ndim) {
PyErr_SetString(PyExc_ValueError,
"len(shape) != len(strides)");
return NULL;
}
}
/* itemsize */
itemsize = get_itemsize(format);
if (itemsize <= 0) {
if (itemsize == 0) {
PyErr_SetString(PyExc_ValueError,
"itemsize must not be zero");
}
return NULL;
}
/* convert scalar to list */
if (ndim == 0) {
items = Py_BuildValue("(O)", items);
if (items == NULL)
return NULL;
}
else {
CHECK_LIST_OR_TUPLE(items)
Py_INCREF(items);
}
/* number of items */
nitems = PySequence_Fast_GET_SIZE(items);
if (nitems == 0) {
PyErr_SetString(PyExc_ValueError,
"initializer list or tuple must not be empty");
Py_DECREF(items);
return NULL;
}
ndbuf = ndbuf_new(nitems, itemsize, offset, flags);
if (ndbuf == NULL) {
Py_DECREF(items);
return NULL;
}
if (init_simple(ndbuf, items, format, itemsize) < 0)
goto error;
if (init_structure(ndbuf, shape, strides, ndim) < 0)
goto error;
Py_DECREF(items);
return ndbuf;
error:
Py_DECREF(items);
ndbuf_free(ndbuf);
return NULL;
}
/* initialize and push a new base onto the linked list */
static int
ndarray_push_base(NDArrayObject *nd, PyObject *items,
PyObject *shape, PyObject *strides,
Py_ssize_t offset, PyObject *format, int flags)
{
ndbuf_t *ndbuf;
ndbuf = init_ndbuf(items, shape, strides, offset, format, flags);
if (ndbuf == NULL)
return -1;
ndbuf_push(nd, ndbuf);
return 0;
}
#define PyBUF_UNUSED 0x10000
static int
ndarray_init(PyObject *self, PyObject *args, PyObject *kwds)
{
NDArrayObject *nd = (NDArrayObject *)self;
static char *kwlist[] = {
"obj", "shape", "strides", "offset", "format", "flags", "getbuf", NULL
};
PyObject *v = NULL; /* initializer: scalar, list, tuple or base object */
PyObject *shape = NULL; /* size of each dimension */
PyObject *strides = NULL; /* number of bytes to the next elt in each dim */
Py_ssize_t offset = 0; /* buffer offset */
PyObject *format = simple_format; /* struct module specifier: "B" */
int flags = ND_DEFAULT; /* base buffer and ndarray flags */
int getbuf = PyBUF_UNUSED; /* re-exporter: getbuffer request flags */
if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|OOnOii", kwlist,
&v, &shape, &strides, &offset, &format, &flags, &getbuf))
return -1;
/* NDArrayObject is re-exporter */
if (PyObject_CheckBuffer(v) && shape == NULL) {
if (strides || offset || format != simple_format ||
!(flags == ND_DEFAULT || flags == ND_REDIRECT)) {
PyErr_SetString(PyExc_TypeError,
"construction from exporter object only takes 'obj', 'getbuf' "
"and 'flags' arguments");
return -1;
}
getbuf = (getbuf == PyBUF_UNUSED) ? PyBUF_FULL_RO : getbuf;
if (ndarray_init_staticbuf(v, nd, getbuf) < 0)
return -1;
init_flags(nd->head);
nd->head->flags |= flags;
return 0;
}
/* NDArrayObject is the original base object. */
if (getbuf != PyBUF_UNUSED) {
PyErr_SetString(PyExc_TypeError,
"getbuf argument only valid for construction from exporter "
"object");
return -1;
}
if (shape == NULL) {
PyErr_SetString(PyExc_TypeError,
"shape is a required argument when constructing from "
"list, tuple or scalar");
return -1;
}
if (flags & ND_VAREXPORT) {
nd->flags |= ND_VAREXPORT;
flags &= ~ND_VAREXPORT;
}
/* Initialize and push the first base buffer onto the linked list. */
return ndarray_push_base(nd, v, shape, strides, offset, format, flags);
}
/* Push an additional base onto the linked list. */
static PyObject *
ndarray_push(PyObject *self, PyObject *args, PyObject *kwds)
{
NDArrayObject *nd = (NDArrayObject *)self;
static char *kwlist[] = {
"items", "shape", "strides", "offset", "format", "flags", NULL
};
PyObject *items = NULL; /* initializer: scalar, list or tuple */
PyObject *shape = NULL; /* size of each dimension */
PyObject *strides = NULL; /* number of bytes to the next elt in each dim */
PyObject *format = simple_format; /* struct module specifier: "B" */
Py_ssize_t offset = 0; /* buffer offset */
int flags = ND_DEFAULT; /* base buffer flags */
if (!PyArg_ParseTupleAndKeywords(args, kwds, "OO|OnOi", kwlist,
&items, &shape, &strides, &offset, &format, &flags))
return NULL;
if (flags & ND_VAREXPORT) {
PyErr_SetString(PyExc_ValueError,
"ND_VAREXPORT flag can only be used during object creation");
return NULL;
}
if (ND_IS_CONSUMER(nd)) {
PyErr_SetString(PyExc_BufferError,
"structure of re-exporting object is immutable");
return NULL;
}
if (!(nd->flags&ND_VAREXPORT) && nd->head->exports > 0) {
PyErr_Format(PyExc_BufferError,
"cannot change structure: %zd exported buffer%s",
nd->head->exports, nd->head->exports==1 ? "" : "s");
return NULL;
}
if (ndarray_push_base(nd, items, shape, strides,
offset, format, flags) < 0)
return NULL;
Py_RETURN_NONE;
}
/* Pop a base from the linked list (if possible). */
static PyObject *
ndarray_pop(PyObject *self, PyObject *dummy)
{
NDArrayObject *nd = (NDArrayObject *)self;
if (ND_IS_CONSUMER(nd)) {
PyErr_SetString(PyExc_BufferError,
"structure of re-exporting object is immutable");
return NULL;
}
if (nd->head->exports > 0) {
PyErr_Format(PyExc_BufferError,
"cannot change structure: %zd exported buffer%s",
nd->head->exports, nd->head->exports==1 ? "" : "s");
return NULL;
}
if (nd->head->next == NULL) {
PyErr_SetString(PyExc_BufferError,
"list only has a single base");
return NULL;
}
ndbuf_pop(nd);
Py_RETURN_NONE;
}
/**************************************************************************/
/* getbuffer */
/**************************************************************************/
static int
ndarray_getbuf(NDArrayObject *self, Py_buffer *view, int flags)
{
ndbuf_t *ndbuf = self->head;
Py_buffer *base = &ndbuf->base;
int baseflags = ndbuf->flags;
/* redirect mode */
if (base->obj != NULL && (baseflags&ND_REDIRECT)) {
return PyObject_GetBuffer(base->obj, view, flags);
}
/* start with complete information */
*view = *base;
view->obj = NULL;
/* reconstruct format */
if (view->format == NULL)
view->format = "B";
if (base->ndim != 0 &&
((REQ_SHAPE(flags) && base->shape == NULL) ||
(REQ_STRIDES(flags) && base->strides == NULL))) {
/* The ndarray is a re-exporter that has been created without full
information for testing purposes. In this particular case the
ndarray is not a PEP-3118 compliant buffer provider. */
PyErr_SetString(PyExc_BufferError,
"re-exporter does not provide format, shape or strides");
return -1;
}
if (baseflags & ND_GETBUF_FAIL) {
PyErr_SetString(PyExc_BufferError,
"ND_GETBUF_FAIL: forced test exception");
if (baseflags & ND_GETBUF_UNDEFINED)
view->obj = (PyObject *)0x1; /* wrong but permitted in <= 3.2 */
return -1;
}
if (REQ_WRITABLE(flags) && base->readonly) {
PyErr_SetString(PyExc_BufferError,
"ndarray is not writable");
return -1;
}
if (!REQ_FORMAT(flags)) {
/* NULL indicates that the buffer's data type has been cast to 'B'.
view->itemsize is the _previous_ itemsize. If shape is present,
the equality product(shape) * itemsize = len still holds at this
point. The equality calcsize(format) = itemsize does _not_ hold
from here on! */
view->format = NULL;
}
if (REQ_C_CONTIGUOUS(flags) && !ND_C_CONTIGUOUS(baseflags)) {
PyErr_SetString(PyExc_BufferError,
"ndarray is not C-contiguous");
return -1;
}
if (REQ_F_CONTIGUOUS(flags) && !ND_FORTRAN_CONTIGUOUS(baseflags)) {
PyErr_SetString(PyExc_BufferError,
"ndarray is not Fortran contiguous");
return -1;
}
if (REQ_ANY_CONTIGUOUS(flags) && !ND_ANY_CONTIGUOUS(baseflags)) {
PyErr_SetString(PyExc_BufferError,
"ndarray is not contiguous");
return -1;
}
if (!REQ_INDIRECT(flags) && (baseflags & ND_PIL)) {
PyErr_SetString(PyExc_BufferError,
"ndarray cannot be represented without suboffsets");
return -1;
}
if (!REQ_STRIDES(flags)) {
if (!ND_C_CONTIGUOUS(baseflags)) {
PyErr_SetString(PyExc_BufferError,
"ndarray is not C-contiguous");
return -1;
}
view->strides = NULL;
}
if (!REQ_SHAPE(flags)) {
/* PyBUF_SIMPLE or PyBUF_WRITABLE: at this point buf is C-contiguous,
so base->buf = ndbuf->data. */
if (view->format != NULL) {
/* PyBUF_SIMPLE|PyBUF_FORMAT and PyBUF_WRITABLE|PyBUF_FORMAT do
not make sense. */
PyErr_Format(PyExc_BufferError,
"ndarray: cannot cast to unsigned bytes if the format flag "
"is present");
return -1;
}
/* product(shape) * itemsize = len and calcsize(format) = itemsize
do _not_ hold from here on! */
view->ndim = 1;
view->shape = NULL;
}
/* Ascertain that the new buffer has the same contiguity as the exporter */
if (ND_C_CONTIGUOUS(baseflags) != PyBuffer_IsContiguous(view, 'C') ||
/* skip cast to 1-d */
(view->format != NULL && view->shape != NULL &&
ND_FORTRAN_CONTIGUOUS(baseflags) != PyBuffer_IsContiguous(view, 'F')) ||
/* cast to 1-d */
(view->format == NULL && view->shape == NULL &&
!PyBuffer_IsContiguous(view, 'F'))) {
PyErr_SetString(PyExc_BufferError,
"ndarray: contiguity mismatch in getbuf()");
return -1;
}
view->obj = (PyObject *)self;
Py_INCREF(view->obj);
self->head->exports++;
return 0;
}
static void
ndarray_releasebuf(NDArrayObject *self, Py_buffer *view)
{
if (!ND_IS_CONSUMER(self)) {
ndbuf_t *ndbuf = view->internal;
if (--ndbuf->exports == 0 && ndbuf != self->head)
ndbuf_delete(self, ndbuf);
}
}
static PyBufferProcs ndarray_as_buffer = {
(getbufferproc)ndarray_getbuf, /* bf_getbuffer */
(releasebufferproc)ndarray_releasebuf /* bf_releasebuffer */
};
/**************************************************************************/
/* indexing/slicing */
/**************************************************************************/
static char *
ptr_from_index(Py_buffer *base, Py_ssize_t index)
{
char *ptr;
Py_ssize_t nitems; /* items in the first dimension */
if (base->shape)
nitems = base->shape[0];
else {
assert(base->ndim == 1 && SIMPLE_FORMAT(base->format));
nitems = base->len;
}
if (index < 0) {
index += nitems;
}
if (index < 0 || index >= nitems) {
PyErr_SetString(PyExc_IndexError, "index out of bounds");
return NULL;
}
ptr = (char *)base->buf;
if (base->strides == NULL)
ptr += base->itemsize * index;
else
ptr += base->strides[0] * index;
ptr = ADJUST_PTR(ptr, base->suboffsets);
return ptr;
}
static PyObject *
ndarray_item(NDArrayObject *self, Py_ssize_t index)
{
ndbuf_t *ndbuf = self->head;
Py_buffer *base = &ndbuf->base;
char *ptr;
if (base->ndim == 0) {
PyErr_SetString(PyExc_TypeError, "invalid indexing of scalar");
return NULL;
}
ptr = ptr_from_index(base, index);
if (ptr == NULL)
return NULL;
if (base->ndim == 1) {
return unpack_single(ptr, base->format, base->itemsize);
}
else {
NDArrayObject *nd;
Py_buffer *subview;
nd = (NDArrayObject *)ndarray_new(&NDArray_Type, NULL, NULL);
if (nd == NULL)
return NULL;
if (ndarray_init_staticbuf((PyObject *)self, nd, PyBUF_FULL_RO) < 0) {
Py_DECREF(nd);
return NULL;
}
subview = &nd->staticbuf.base;
subview->buf = ptr;
subview->len /= subview->shape[0];
subview->ndim--;
subview->shape++;
if (subview->strides) subview->strides++;
if (subview->suboffsets) subview->suboffsets++;
init_flags(&nd->staticbuf);
return (PyObject *)nd;
}
}
/*
For each dimension, we get valid (start, stop, step, slicelength) quadruples
from PySlice_GetIndicesEx().
Slicing NumPy arrays
====================
A pointer to an element in a NumPy array is defined by:
ptr = (char *)buf + indices[0] * strides[0] +
... +
indices[ndim-1] * strides[ndim-1]
Adjust buf:
-----------
Adding start[n] for each dimension effectively adds the constant:
c = start[0] * strides[0] + ... + start[ndim-1] * strides[ndim-1]
Therefore init_slice() adds all start[n] directly to buf.
Adjust shape:
-------------
Obviously shape[n] = slicelength[n]
Adjust strides:
---------------
In the original array, the next element in a dimension is reached
by adding strides[n] to the pointer. In the sliced array, elements
may be skipped, so the next element is reached by adding:
strides[n] * step[n]
Slicing PIL arrays
==================
Layout:
-------
In the first (zeroth) dimension, PIL arrays have an array of pointers
to sub-arrays of ndim-1. Striding in the first dimension is done by
getting the index of the nth pointer, dereference it and then add a
suboffset to it. The arrays pointed to can best be seen a regular
NumPy arrays.
Adjust buf:
-----------
In the original array, buf points to a location (usually the start)
in the array of pointers. For the sliced array, start[0] can be
added to buf in the same manner as for NumPy arrays.
Adjust suboffsets:
------------------
Due to the dereferencing step in the addressing scheme, it is not
possible to adjust buf for higher dimensions. Recall that the
sub-arrays pointed to are regular NumPy arrays, so for each of
those arrays adding start[n] effectively adds the constant:
c = start[1] * strides[1] + ... + start[ndim-1] * strides[ndim-1]
This constant is added to suboffsets[0]. suboffsets[0] in turn is
added to each pointer right after dereferencing.
Adjust shape and strides:
-------------------------
Shape and strides are not influenced by the dereferencing step, so
they are adjusted in the same manner as for NumPy arrays.
Multiple levels of suboffsets
=============================
For a construct like an array of pointers to array of pointers to
sub-arrays of ndim-2:
suboffsets[0] = start[1] * strides[1]
suboffsets[1] = start[2] * strides[2] + ...
*/
static int
init_slice(Py_buffer *base, PyObject *key, int dim)
{
Py_ssize_t start, stop, step, slicelength;
if (PySlice_Unpack(key, &start, &stop, &step) < 0) {
return -1;
}
slicelength = PySlice_AdjustIndices(base->shape[dim], &start, &stop, step);
if (base->suboffsets == NULL || dim == 0) {
adjust_buf:
base->buf = (char *)base->buf + base->strides[dim] * start;
}
else {
Py_ssize_t n = dim-1;
while (n >= 0 && base->suboffsets[n] < 0)
n--;
if (n < 0)
goto adjust_buf; /* all suboffsets are negative */
base->suboffsets[n] = base->suboffsets[n] + base->strides[dim] * start;
}
base->shape[dim] = slicelength;
base->strides[dim] = base->strides[dim] * step;
return 0;
}
static int
copy_structure(Py_buffer *base)
{
Py_ssize_t *shape = NULL, *strides = NULL, *suboffsets = NULL;
Py_ssize_t i;
shape = PyMem_Malloc(base->ndim * (sizeof *shape));
strides = PyMem_Malloc(base->ndim * (sizeof *strides));
if (shape == NULL || strides == NULL)
goto err_nomem;
suboffsets = NULL;
if (base->suboffsets) {
suboffsets = PyMem_Malloc(base->ndim * (sizeof *suboffsets));
if (suboffsets == NULL)
goto err_nomem;
}
for (i = 0; i < base->ndim; i++) {
shape[i] = base->shape[i];
strides[i] = base->strides[i];
if (suboffsets)
suboffsets[i] = base->suboffsets[i];
}
base->shape = shape;
base->strides = strides;
base->suboffsets = suboffsets;
return 0;
err_nomem:
PyErr_NoMemory();
PyMem_XFree(shape);
PyMem_XFree(strides);
PyMem_XFree(suboffsets);
return -1;
}
static PyObject *
ndarray_subscript(NDArrayObject *self, PyObject *key)
{
NDArrayObject *nd;
ndbuf_t *ndbuf;
Py_buffer *base = &self->head->base;
if (base->ndim == 0) {
if (PyTuple_Check(key) && PyTuple_GET_SIZE(key) == 0) {
return unpack_single(base->buf, base->format, base->itemsize);
}
else if (key == Py_Ellipsis) {
Py_INCREF(self);
return (PyObject *)self;
}
else {
PyErr_SetString(PyExc_TypeError, "invalid indexing of scalar");
return NULL;
}
}
if (PyIndex_Check(key)) {
Py_ssize_t index = PyLong_AsSsize_t(key);
if (index == -1 && PyErr_Occurred())
return NULL;
return ndarray_item(self, index);
}
nd = (NDArrayObject *)ndarray_new(&NDArray_Type, NULL, NULL);
if (nd == NULL)
return NULL;
/* new ndarray is a consumer */
if (ndarray_init_staticbuf((PyObject *)self, nd, PyBUF_FULL_RO) < 0) {
Py_DECREF(nd);
return NULL;
}
/* copy shape, strides and suboffsets */
ndbuf = nd->head;
base = &ndbuf->base;
if (copy_structure(base) < 0) {
Py_DECREF(nd);
return NULL;
}
ndbuf->flags |= ND_OWN_ARRAYS;
if (PySlice_Check(key)) {
/* one-dimensional slice */
if (init_slice(base, key, 0) < 0)
goto err_occurred;
}
else if (PyTuple_Check(key)) {
/* multi-dimensional slice */
PyObject *tuple = key;
Py_ssize_t i, n;
n = PyTuple_GET_SIZE(tuple);
for (i = 0; i < n; i++) {
key = PyTuple_GET_ITEM(tuple, i);
if (!PySlice_Check(key))
goto type_error;
if (init_slice(base, key, (int)i) < 0)
goto err_occurred;
}
}
else {
goto type_error;
}
init_len(base);
init_flags(ndbuf);
return (PyObject *)nd;
type_error:
PyErr_Format(PyExc_TypeError,
"cannot index memory using \"%.200s\"",
key->ob_type->tp_name);
err_occurred:
Py_DECREF(nd);
return NULL;
}
static int
ndarray_ass_subscript(NDArrayObject *self, PyObject *key, PyObject *value)
{
NDArrayObject *nd;
Py_buffer *dest = &self->head->base;
Py_buffer src;
char *ptr;
Py_ssize_t index;
int ret = -1;
if (dest->readonly) {
PyErr_SetString(PyExc_TypeError, "ndarray is not writable");
return -1;
}
if (value == NULL) {
PyErr_SetString(PyExc_TypeError, "ndarray data cannot be deleted");
return -1;
}
if (dest->ndim == 0) {
if (key == Py_Ellipsis ||
(PyTuple_Check(key) && PyTuple_GET_SIZE(key) == 0)) {
ptr = (char *)dest->buf;
return pack_single(ptr, value, dest->format, dest->itemsize);
}
else {
PyErr_SetString(PyExc_TypeError, "invalid indexing of scalar");
return -1;
}
}
if (dest->ndim == 1 && PyIndex_Check(key)) {
/* rvalue must be a single item */
index = PyLong_AsSsize_t(key);
if (index == -1 && PyErr_Occurred())
return -1;
else {
ptr = ptr_from_index(dest, index);
if (ptr == NULL)
return -1;
}
return pack_single(ptr, value, dest->format, dest->itemsize);
}
/* rvalue must be an exporter */
if (PyObject_GetBuffer(value, &src, PyBUF_FULL_RO) == -1)
return -1;
nd = (NDArrayObject *)ndarray_subscript(self, key);
if (nd != NULL) {
dest = &nd->head->base;
ret = copy_buffer(dest, &src);
Py_DECREF(nd);
}
PyBuffer_Release(&src);
return ret;
}
static PyObject *
slice_indices(PyObject *self, PyObject *args)
{
PyObject *ret, *key, *tmp;
Py_ssize_t s[4]; /* start, stop, step, slicelength */
Py_ssize_t i, len;
if (!PyArg_ParseTuple(args, "On", &key, &len)) {
return NULL;
}
if (!PySlice_Check(key)) {
PyErr_SetString(PyExc_TypeError,
"first argument must be a slice object");
return NULL;
}
if (PySlice_Unpack(key, &s[0], &s[1], &s[2]) < 0) {
return NULL;
}
s[3] = PySlice_AdjustIndices(len, &s[0], &s[1], s[2]);
ret = PyTuple_New(4);
if (ret == NULL)
return NULL;
for (i = 0; i < 4; i++) {
tmp = PyLong_FromSsize_t(s[i]);
if (tmp == NULL)
goto error;
PyTuple_SET_ITEM(ret, i, tmp);
}
return ret;
error:
Py_DECREF(ret);
return NULL;
}
static PyMappingMethods ndarray_as_mapping = {
NULL, /* mp_length */
(binaryfunc)ndarray_subscript, /* mp_subscript */
(objobjargproc)ndarray_ass_subscript /* mp_ass_subscript */
};
static PySequenceMethods ndarray_as_sequence = {
0, /* sq_length */
0, /* sq_concat */
0, /* sq_repeat */
(ssizeargfunc)ndarray_item, /* sq_item */
};
/**************************************************************************/
/* getters */
/**************************************************************************/
static PyObject *
ssize_array_as_tuple(Py_ssize_t *array, Py_ssize_t len)
{
PyObject *tuple, *x;
Py_ssize_t i;
if (array == NULL)
return PyTuple_New(0);
tuple = PyTuple_New(len);
if (tuple == NULL)
return NULL;
for (i = 0; i < len; i++) {
x = PyLong_FromSsize_t(array[i]);
if (x == NULL) {
Py_DECREF(tuple);
return NULL;
}
PyTuple_SET_ITEM(tuple, i, x);
}
return tuple;
}
static PyObject *
ndarray_get_flags(NDArrayObject *self, void *closure)
{
return PyLong_FromLong(self->head->flags);
}
static PyObject *
ndarray_get_offset(NDArrayObject *self, void *closure)
{
ndbuf_t *ndbuf = self->head;
return PyLong_FromSsize_t(ndbuf->offset);
}
static PyObject *
ndarray_get_obj(NDArrayObject *self, void *closure)
{
Py_buffer *base = &self->head->base;
if (base->obj == NULL) {
Py_RETURN_NONE;
}
Py_INCREF(base->obj);
return base->obj;
}
static PyObject *
ndarray_get_nbytes(NDArrayObject *self, void *closure)
{
Py_buffer *base = &self->head->base;
return PyLong_FromSsize_t(base->len);
}
static PyObject *
ndarray_get_readonly(NDArrayObject *self, void *closure)
{
Py_buffer *base = &self->head->base;
return PyLong_FromLong(base->readonly);
}
static PyObject *
ndarray_get_itemsize(NDArrayObject *self, void *closure)
{
Py_buffer *base = &self->head->base;
return PyLong_FromSsize_t(base->itemsize);
}
static PyObject *
ndarray_get_format(NDArrayObject *self, void *closure)
{
Py_buffer *base = &self->head->base;
char *fmt = base->format ? base->format : "";
return PyUnicode_FromString(fmt);
}
static PyObject *
ndarray_get_ndim(NDArrayObject *self, void *closure)
{
Py_buffer *base = &self->head->base;
return PyLong_FromSsize_t(base->ndim);
}
static PyObject *
ndarray_get_shape(NDArrayObject *self, void *closure)
{
Py_buffer *base = &self->head->base;
return ssize_array_as_tuple(base->shape, base->ndim);
}
static PyObject *
ndarray_get_strides(NDArrayObject *self, void *closure)
{
Py_buffer *base = &self->head->base;
return ssize_array_as_tuple(base->strides, base->ndim);
}
static PyObject *
ndarray_get_suboffsets(NDArrayObject *self, void *closure)
{
Py_buffer *base = &self->head->base;
return ssize_array_as_tuple(base->suboffsets, base->ndim);
}
static PyObject *
ndarray_c_contig(PyObject *self, PyObject *dummy)
{
NDArrayObject *nd = (NDArrayObject *)self;
int ret = PyBuffer_IsContiguous(&nd->head->base, 'C');
if (ret != ND_C_CONTIGUOUS(nd->head->flags)) {
PyErr_SetString(PyExc_RuntimeError,
"results from PyBuffer_IsContiguous() and flags differ");
return NULL;
}
return PyBool_FromLong(ret);
}
static PyObject *
ndarray_fortran_contig(PyObject *self, PyObject *dummy)
{
NDArrayObject *nd = (NDArrayObject *)self;
int ret = PyBuffer_IsContiguous(&nd->head->base, 'F');
if (ret != ND_FORTRAN_CONTIGUOUS(nd->head->flags)) {
PyErr_SetString(PyExc_RuntimeError,
"results from PyBuffer_IsContiguous() and flags differ");
return NULL;
}
return PyBool_FromLong(ret);
}
static PyObject *
ndarray_contig(PyObject *self, PyObject *dummy)
{
NDArrayObject *nd = (NDArrayObject *)self;
int ret = PyBuffer_IsContiguous(&nd->head->base, 'A');
if (ret != ND_ANY_CONTIGUOUS(nd->head->flags)) {
PyErr_SetString(PyExc_RuntimeError,
"results from PyBuffer_IsContiguous() and flags differ");
return NULL;
}
return PyBool_FromLong(ret);
}
static PyGetSetDef ndarray_getset [] =
{
/* ndbuf */
{ "flags", (getter)ndarray_get_flags, NULL, NULL, NULL},
{ "offset", (getter)ndarray_get_offset, NULL, NULL, NULL},
/* ndbuf.base */
{ "obj", (getter)ndarray_get_obj, NULL, NULL, NULL},
{ "nbytes", (getter)ndarray_get_nbytes, NULL, NULL, NULL},
{ "readonly", (getter)ndarray_get_readonly, NULL, NULL, NULL},
{ "itemsize", (getter)ndarray_get_itemsize, NULL, NULL, NULL},
{ "format", (getter)ndarray_get_format, NULL, NULL, NULL},
{ "ndim", (getter)ndarray_get_ndim, NULL, NULL, NULL},
{ "shape", (getter)ndarray_get_shape, NULL, NULL, NULL},
{ "strides", (getter)ndarray_get_strides, NULL, NULL, NULL},
{ "suboffsets", (getter)ndarray_get_suboffsets, NULL, NULL, NULL},
{ "c_contiguous", (getter)ndarray_c_contig, NULL, NULL, NULL},
{ "f_contiguous", (getter)ndarray_fortran_contig, NULL, NULL, NULL},
{ "contiguous", (getter)ndarray_contig, NULL, NULL, NULL},
{NULL}
};
static PyObject *
ndarray_tolist(PyObject *self, PyObject *dummy)
{
return ndarray_as_list((NDArrayObject *)self);
}
static PyObject *
ndarray_tobytes(PyObject *self, PyObject *dummy)
{
ndbuf_t *ndbuf = ((NDArrayObject *)self)->head;
Py_buffer *src = &ndbuf->base;
Py_buffer dest;
PyObject *ret = NULL;
char *mem;
if (ND_C_CONTIGUOUS(ndbuf->flags))
return PyBytes_FromStringAndSize(src->buf, src->len);
assert(src->shape != NULL);
assert(src->strides != NULL);
assert(src->ndim > 0);
mem = PyMem_Malloc(src->len);
if (mem == NULL) {
PyErr_NoMemory();
return NULL;
}
dest = *src;
dest.buf = mem;
dest.suboffsets = NULL;
dest.strides = strides_from_shape(ndbuf, 0);
if (dest.strides == NULL)
goto out;
if (copy_buffer(&dest, src) < 0)
goto out;
ret = PyBytes_FromStringAndSize(mem, src->len);
out:
PyMem_XFree(dest.strides);
PyMem_Free(mem);
return ret;
}
/* add redundant (negative) suboffsets for testing */
static PyObject *
ndarray_add_suboffsets(PyObject *self, PyObject *dummy)
{
NDArrayObject *nd = (NDArrayObject *)self;
Py_buffer *base = &nd->head->base;
Py_ssize_t i;
if (base->suboffsets != NULL) {
PyErr_SetString(PyExc_TypeError,
"cannot add suboffsets to PIL-style array");
return NULL;
}
if (base->strides == NULL) {
PyErr_SetString(PyExc_TypeError,
"cannot add suboffsets to array without strides");
return NULL;
}
base->suboffsets = PyMem_Malloc(base->ndim * (sizeof *base->suboffsets));
if (base->suboffsets == NULL) {
PyErr_NoMemory();
return NULL;
}
for (i = 0; i < base->ndim; i++)
base->suboffsets[i] = -1;
nd->head->flags &= ~(ND_C|ND_FORTRAN);
Py_RETURN_NONE;
}
/* Test PyMemoryView_FromBuffer(): return a memoryview from a static buffer.
Obviously this is fragile and only one such view may be active at any
time. Never use anything like this in real code! */
static char *infobuf = NULL;
static PyObject *
ndarray_memoryview_from_buffer(PyObject *self, PyObject *dummy)
{
const NDArrayObject *nd = (NDArrayObject *)self;
const Py_buffer *view = &nd->head->base;
const ndbuf_t *ndbuf;
static char format[ND_MAX_NDIM+1];
static Py_ssize_t shape[ND_MAX_NDIM];
static Py_ssize_t strides[ND_MAX_NDIM];
static Py_ssize_t suboffsets[ND_MAX_NDIM];
static Py_buffer info;
char *p;
if (!ND_IS_CONSUMER(nd))
ndbuf = nd->head; /* self is ndarray/original exporter */
else if (NDArray_Check(view->obj) && !ND_IS_CONSUMER(view->obj))
/* self is ndarray and consumer from ndarray/original exporter */
ndbuf = ((NDArrayObject *)view->obj)->head;
else {
PyErr_SetString(PyExc_TypeError,
"memoryview_from_buffer(): ndarray must be original exporter or "
"consumer from ndarray/original exporter");
return NULL;
}
info = *view;
p = PyMem_Realloc(infobuf, ndbuf->len);
if (p == NULL) {
PyMem_Free(infobuf);
PyErr_NoMemory();
infobuf = NULL;
return NULL;
}
else {
infobuf = p;
}
/* copy the complete raw data */
memcpy(infobuf, ndbuf->data, ndbuf->len);
info.buf = infobuf + ((char *)view->buf - ndbuf->data);
if (view->format) {
if (strlen(view->format) > ND_MAX_NDIM) {
PyErr_Format(PyExc_TypeError,
"memoryview_from_buffer: format is limited to %d characters",
ND_MAX_NDIM);
return NULL;
}
strcpy(format, view->format);
info.format = format;
}
if (view->ndim > ND_MAX_NDIM) {
PyErr_Format(PyExc_TypeError,
"memoryview_from_buffer: ndim is limited to %d", ND_MAX_NDIM);
return NULL;
}
if (view->shape) {
memcpy(shape, view->shape, view->ndim * sizeof(Py_ssize_t));
info.shape = shape;
}
if (view->strides) {
memcpy(strides, view->strides, view->ndim * sizeof(Py_ssize_t));
info.strides = strides;
}
if (view->suboffsets) {
memcpy(suboffsets, view->suboffsets, view->ndim * sizeof(Py_ssize_t));
info.suboffsets = suboffsets;
}
return PyMemoryView_FromBuffer(&info);
}
/* Get a single item from bufobj at the location specified by seq.
seq is a list or tuple of indices. The purpose of this function
is to check other functions against PyBuffer_GetPointer(). */
static PyObject *
get_pointer(PyObject *self, PyObject *args)
{
PyObject *ret = NULL, *bufobj, *seq;
Py_buffer view;
Py_ssize_t indices[ND_MAX_NDIM];
Py_ssize_t i;
void *ptr;
if (!PyArg_ParseTuple(args, "OO", &bufobj, &seq)) {
return NULL;
}
CHECK_LIST_OR_TUPLE(seq);
if (PyObject_GetBuffer(bufobj, &view, PyBUF_FULL_RO) < 0)
return NULL;
if (view.ndim > ND_MAX_NDIM) {
PyErr_Format(PyExc_ValueError,
"get_pointer(): ndim > %d", ND_MAX_NDIM);
goto out;
}
if (PySequence_Fast_GET_SIZE(seq) != view.ndim) {
PyErr_SetString(PyExc_ValueError,
"get_pointer(): len(indices) != ndim");
goto out;
}
for (i = 0; i < view.ndim; i++) {
PyObject *x = PySequence_Fast_GET_ITEM(seq, i);
indices[i] = PyLong_AsSsize_t(x);
if (PyErr_Occurred())
goto out;
if (indices[i] < 0 || indices[i] >= view.shape[i]) {
PyErr_Format(PyExc_ValueError,
"get_pointer(): invalid index %zd at position %zd",
indices[i], i);
goto out;
}
}
ptr = PyBuffer_GetPointer(&view, indices);
ret = unpack_single(ptr, view.format, view.itemsize);
out:
PyBuffer_Release(&view);
return ret;
}
static PyObject *
get_sizeof_void_p(PyObject *self)
{
return PyLong_FromSize_t(sizeof(void *));
}
static char
get_ascii_order(PyObject *order)
{
PyObject *ascii_order;
char ord;
if (!PyUnicode_Check(order)) {
PyErr_SetString(PyExc_TypeError,
"order must be a string");
return CHAR_MAX;
}
ascii_order = PyUnicode_AsASCIIString(order);
if (ascii_order == NULL) {
return CHAR_MAX;
}
ord = PyBytes_AS_STRING(ascii_order)[0];
Py_DECREF(ascii_order);
if (ord != 'C' && ord != 'F' && ord != 'A') {
PyErr_SetString(PyExc_ValueError,
"invalid order, must be C, F or A");
return CHAR_MAX;
}
return ord;
}
/* Get a contiguous memoryview. */
static PyObject *
get_contiguous(PyObject *self, PyObject *args)
{
PyObject *obj;
PyObject *buffertype;
PyObject *order;
long type;
char ord;
if (!PyArg_ParseTuple(args, "OOO", &obj, &buffertype, &order)) {
return NULL;
}
if (!PyLong_Check(buffertype)) {
PyErr_SetString(PyExc_TypeError,
"buffertype must be PyBUF_READ or PyBUF_WRITE");
return NULL;
}
type = PyLong_AsLong(buffertype);
if (type == -1 && PyErr_Occurred()) {
return NULL;
}
if (type != PyBUF_READ && type != PyBUF_WRITE) {
PyErr_SetString(PyExc_ValueError,
"invalid buffer type");
return NULL;
}
ord = get_ascii_order(order);
if (ord == CHAR_MAX)
return NULL;
return PyMemoryView_GetContiguous(obj, (int)type, ord);
}
/* PyBuffer_ToContiguous() */
static PyObject *
py_buffer_to_contiguous(PyObject *self, PyObject *args)
{
PyObject *obj;
PyObject *order;
PyObject *ret = NULL;
int flags;
char ord;
Py_buffer view;
char *buf = NULL;
if (!PyArg_ParseTuple(args, "OOi", &obj, &order, &flags)) {
return NULL;
}
if (PyObject_GetBuffer(obj, &view, flags) < 0) {
return NULL;
}
ord = get_ascii_order(order);
if (ord == CHAR_MAX) {
goto out;
}
buf = PyMem_Malloc(view.len);
if (buf == NULL) {
PyErr_NoMemory();
goto out;
}
if (PyBuffer_ToContiguous(buf, &view, view.len, ord) < 0) {
goto out;
}
ret = PyBytes_FromStringAndSize(buf, view.len);
out:
PyBuffer_Release(&view);
PyMem_XFree(buf);
return ret;
}
static int
fmtcmp(const char *fmt1, const char *fmt2)
{
if (fmt1 == NULL) {
return fmt2 == NULL || strcmp(fmt2, "B") == 0;
}
if (fmt2 == NULL) {
return fmt1 == NULL || strcmp(fmt1, "B") == 0;
}
return strcmp(fmt1, fmt2) == 0;
}
static int
arraycmp(const Py_ssize_t *a1, const Py_ssize_t *a2, const Py_ssize_t *shape,
Py_ssize_t ndim)
{
Py_ssize_t i;
for (i = 0; i < ndim; i++) {
if (shape && shape[i] <= 1) {
/* strides can differ if the dimension is less than 2 */
continue;
}
if (a1[i] != a2[i]) {
return 0;
}
}
return 1;
}
/* Compare two contiguous buffers for physical equality. */
static PyObject *
cmp_contig(PyObject *self, PyObject *args)
{
PyObject *b1, *b2; /* buffer objects */
Py_buffer v1, v2;
PyObject *ret;
int equal = 0;
if (!PyArg_ParseTuple(args, "OO", &b1, &b2)) {
return NULL;
}
if (PyObject_GetBuffer(b1, &v1, PyBUF_FULL_RO) < 0) {
PyErr_SetString(PyExc_TypeError,
"cmp_contig: first argument does not implement the buffer "
"protocol");
return NULL;
}
if (PyObject_GetBuffer(b2, &v2, PyBUF_FULL_RO) < 0) {
PyErr_SetString(PyExc_TypeError,
"cmp_contig: second argument does not implement the buffer "
"protocol");
PyBuffer_Release(&v1);
return NULL;
}
if (!(PyBuffer_IsContiguous(&v1, 'C')&&PyBuffer_IsContiguous(&v2, 'C')) &&
!(PyBuffer_IsContiguous(&v1, 'F')&&PyBuffer_IsContiguous(&v2, 'F'))) {
goto result;
}
/* readonly may differ if created from non-contiguous */
if (v1.len != v2.len ||
v1.itemsize != v2.itemsize ||
v1.ndim != v2.ndim ||
!fmtcmp(v1.format, v2.format) ||
!!v1.shape != !!v2.shape ||
!!v1.strides != !!v2.strides ||
!!v1.suboffsets != !!v2.suboffsets) {
goto result;
}
if ((v1.shape && !arraycmp(v1.shape, v2.shape, NULL, v1.ndim)) ||
(v1.strides && !arraycmp(v1.strides, v2.strides, v1.shape, v1.ndim)) ||
(v1.suboffsets && !arraycmp(v1.suboffsets, v2.suboffsets, NULL,
v1.ndim))) {
goto result;
}
if (bcmp((char *)v1.buf, (char *)v2.buf, v1.len)) {
goto result;
}
equal = 1;
result:
PyBuffer_Release(&v1);
PyBuffer_Release(&v2);
ret = equal ? Py_True : Py_False;
Py_INCREF(ret);
return ret;
}
static PyObject *
is_contiguous(PyObject *self, PyObject *args)
{
PyObject *obj;
PyObject *order;
PyObject *ret = NULL;
Py_buffer view, *base;
char ord;
if (!PyArg_ParseTuple(args, "OO", &obj, &order)) {
return NULL;
}
ord = get_ascii_order(order);
if (ord == CHAR_MAX) {
return NULL;
}
if (NDArray_Check(obj)) {
/* Skip the buffer protocol to check simple etc. buffers directly. */
base = &((NDArrayObject *)obj)->head->base;
ret = PyBuffer_IsContiguous(base, ord) ? Py_True : Py_False;
}
else {
if (PyObject_GetBuffer(obj, &view, PyBUF_FULL_RO) < 0) {
PyErr_SetString(PyExc_TypeError,
"is_contiguous: object does not implement the buffer "
"protocol");
return NULL;
}
ret = PyBuffer_IsContiguous(&view, ord) ? Py_True : Py_False;
PyBuffer_Release(&view);
}
Py_INCREF(ret);
return ret;
}
static Py_hash_t
ndarray_hash(PyObject *self)
{
const NDArrayObject *nd = (NDArrayObject *)self;
const Py_buffer *view = &nd->head->base;
PyObject *bytes;
Py_hash_t hash;
if (!view->readonly) {
PyErr_SetString(PyExc_ValueError,
"cannot hash writable ndarray object");
return -1;
}
if (view->obj != NULL && PyObject_Hash(view->obj) == -1) {
return -1;
}
bytes = ndarray_tobytes(self, NULL);
if (bytes == NULL) {
return -1;
}
hash = PyObject_Hash(bytes);
Py_DECREF(bytes);
return hash;
}
static PyMethodDef ndarray_methods [] =
{
{ "tolist", ndarray_tolist, METH_NOARGS, NULL },
{ "tobytes", ndarray_tobytes, METH_NOARGS, NULL },
{ "push", (PyCFunction)ndarray_push, METH_VARARGS|METH_KEYWORDS, NULL },
{ "pop", ndarray_pop, METH_NOARGS, NULL },
{ "add_suboffsets", ndarray_add_suboffsets, METH_NOARGS, NULL },
{ "memoryview_from_buffer", ndarray_memoryview_from_buffer, METH_NOARGS, NULL },
{NULL}
};
static PyTypeObject NDArray_Type = {
PyVarObject_HEAD_INIT(NULL, 0)
"ndarray", /* Name of this type */
sizeof(NDArrayObject), /* Basic object size */
0, /* Item size for varobject */
(destructor)ndarray_dealloc, /* tp_dealloc */
0, /* tp_print */
0, /* tp_getattr */
0, /* tp_setattr */
0, /* tp_compare */
0, /* tp_repr */
0, /* tp_as_number */
&ndarray_as_sequence, /* tp_as_sequence */
&ndarray_as_mapping, /* tp_as_mapping */
(hashfunc)ndarray_hash, /* tp_hash */
0, /* tp_call */
0, /* tp_str */
PyObject_GenericGetAttr, /* tp_getattro */
0, /* tp_setattro */
&ndarray_as_buffer, /* 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 */
ndarray_methods, /* tp_methods */
0, /* tp_members */
ndarray_getset, /* tp_getset */
0, /* tp_base */
0, /* tp_dict */
0, /* tp_descr_get */
0, /* tp_descr_set */
0, /* tp_dictoffset */
ndarray_init, /* tp_init */
0, /* tp_alloc */
ndarray_new, /* tp_new */
};
/**************************************************************************/
/* StaticArray Object */
/**************************************************************************/
static PyTypeObject StaticArray_Type;
typedef struct {
PyObject_HEAD
int legacy_mode; /* if true, use the view.obj==NULL hack */
} StaticArrayObject;
static char static_mem[12] = {0,1,2,3,4,5,6,7,8,9,10,11};
static Py_ssize_t static_shape[1] = {12};
static Py_ssize_t static_strides[1] = {1};
static Py_buffer static_buffer = {
static_mem, /* buf */
NULL, /* obj */
12, /* len */
1, /* itemsize */
1, /* readonly */
1, /* ndim */
"B", /* format */
static_shape, /* shape */
static_strides, /* strides */
NULL, /* suboffsets */
NULL /* internal */
};
static PyObject *
staticarray_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
return (PyObject *)PyObject_New(StaticArrayObject, &StaticArray_Type);
}
static int
staticarray_init(PyObject *self, PyObject *args, PyObject *kwds)
{
StaticArrayObject *a = (StaticArrayObject *)self;
static char *kwlist[] = {
"legacy_mode", NULL
};
PyObject *legacy_mode = Py_False;
if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O", kwlist, &legacy_mode))
return -1;
a->legacy_mode = (legacy_mode != Py_False);
return 0;
}
static void
staticarray_dealloc(StaticArrayObject *self)
{
PyObject_Del(self);
}
/* Return a buffer for a PyBUF_FULL_RO request. Flags are not checked,
which makes this object a non-compliant exporter! */
static int
staticarray_getbuf(StaticArrayObject *self, Py_buffer *view, int flags)
{
*view = static_buffer;
if (self->legacy_mode) {
view->obj = NULL; /* Don't use this in new code. */
}
else {
view->obj = (PyObject *)self;
Py_INCREF(view->obj);
}
return 0;
}
static PyBufferProcs staticarray_as_buffer = {
(getbufferproc)staticarray_getbuf, /* bf_getbuffer */
NULL, /* bf_releasebuffer */
};
static PyTypeObject StaticArray_Type = {
PyVarObject_HEAD_INIT(NULL, 0)
"staticarray", /* Name of this type */
sizeof(StaticArrayObject), /* Basic object size */
0, /* Item size for varobject */
(destructor)staticarray_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 */
&staticarray_as_buffer, /* 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 */
staticarray_init, /* tp_init */
0, /* tp_alloc */
staticarray_new, /* tp_new */
};
static struct PyMethodDef _testbuffer_functions[] = {
{"slice_indices", slice_indices, METH_VARARGS, NULL},
{"get_pointer", get_pointer, METH_VARARGS, NULL},
{"get_sizeof_void_p", (PyCFunction)get_sizeof_void_p, METH_NOARGS, NULL},
{"get_contiguous", get_contiguous, METH_VARARGS, NULL},
{"py_buffer_to_contiguous", py_buffer_to_contiguous, METH_VARARGS, NULL},
{"is_contiguous", is_contiguous, METH_VARARGS, NULL},
{"cmp_contig", cmp_contig, METH_VARARGS, NULL},
{NULL, NULL}
};
static struct PyModuleDef _testbuffermodule = {
PyModuleDef_HEAD_INIT,
"_testbuffer",
NULL,
-1,
_testbuffer_functions,
NULL,
NULL,
NULL,
NULL
};
PyMODINIT_FUNC
PyInit__testbuffer(void)
{
PyObject *m;
m = PyModule_Create(&_testbuffermodule);
if (m == NULL)
return NULL;
Py_TYPE(&NDArray_Type) = &PyType_Type;
Py_INCREF(&NDArray_Type);
PyModule_AddObject(m, "ndarray", (PyObject *)&NDArray_Type);
Py_TYPE(&StaticArray_Type) = &PyType_Type;
Py_INCREF(&StaticArray_Type);
PyModule_AddObject(m, "staticarray", (PyObject *)&StaticArray_Type);
structmodule = PyImport_ImportModule("struct");
if (structmodule == NULL)
return NULL;
Struct = PyObject_GetAttrString(structmodule, "Struct");
calcsize = PyObject_GetAttrString(structmodule, "calcsize");
if (Struct == NULL || calcsize == NULL)
return NULL;
simple_format = PyUnicode_FromString(simple_fmt);
if (simple_format == NULL)
return NULL;
PyModule_AddIntMacro(m, ND_MAX_NDIM);
PyModule_AddIntMacro(m, ND_VAREXPORT);
PyModule_AddIntMacro(m, ND_WRITABLE);
PyModule_AddIntMacro(m, ND_FORTRAN);
PyModule_AddIntMacro(m, ND_SCALAR);
PyModule_AddIntMacro(m, ND_PIL);
PyModule_AddIntMacro(m, ND_GETBUF_FAIL);
PyModule_AddIntMacro(m, ND_GETBUF_UNDEFINED);
PyModule_AddIntMacro(m, ND_REDIRECT);
PyModule_AddIntMacro(m, PyBUF_SIMPLE);
PyModule_AddIntMacro(m, PyBUF_WRITABLE);
PyModule_AddIntMacro(m, PyBUF_FORMAT);
PyModule_AddIntMacro(m, PyBUF_ND);
PyModule_AddIntMacro(m, PyBUF_STRIDES);
PyModule_AddIntMacro(m, PyBUF_INDIRECT);
PyModule_AddIntMacro(m, PyBUF_C_CONTIGUOUS);
PyModule_AddIntMacro(m, PyBUF_F_CONTIGUOUS);
PyModule_AddIntMacro(m, PyBUF_ANY_CONTIGUOUS);
PyModule_AddIntMacro(m, PyBUF_FULL);
PyModule_AddIntMacro(m, PyBUF_FULL_RO);
PyModule_AddIntMacro(m, PyBUF_RECORDS);
PyModule_AddIntMacro(m, PyBUF_RECORDS_RO);
PyModule_AddIntMacro(m, PyBUF_STRIDED);
PyModule_AddIntMacro(m, PyBUF_STRIDED_RO);
PyModule_AddIntMacro(m, PyBUF_CONTIG);
PyModule_AddIntMacro(m, PyBUF_CONTIG_RO);
PyModule_AddIntMacro(m, PyBUF_READ);
PyModule_AddIntMacro(m, PyBUF_WRITE);
return m;
}
| 87,352 | 2,952 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Modules/_csv.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:8;coding:utf-8 -*-â
âvi: set net ft=c ts=4 sts=4 sw=4 fenc=utf-8 :viâ
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ¡
â Python 3 â
â https://docs.python.org/3/license.html â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
#include "third_party/python/Include/abstract.h"
#include "third_party/python/Include/descrobject.h"
#include "third_party/python/Include/dictobject.h"
#include "third_party/python/Include/import.h"
#include "third_party/python/Include/listobject.h"
#include "third_party/python/Include/longobject.h"
#include "third_party/python/Include/modsupport.h"
#include "third_party/python/Include/moduleobject.h"
#include "third_party/python/Include/object.h"
#include "third_party/python/Include/objimpl.h"
#include "third_party/python/Include/pystate.h"
#include "third_party/python/Include/structmember.h"
#include "third_party/python/Include/unicodeobject.h"
#include "third_party/python/Include/yoink.h"
/* clang-format off */
PYTHON_PROVIDE("_csv");
PYTHON_PROVIDE("_csv.Dialect");
PYTHON_PROVIDE("_csv.Error");
PYTHON_PROVIDE("_csv.QUOTE_ALL");
PYTHON_PROVIDE("_csv.QUOTE_MINIMAL");
PYTHON_PROVIDE("_csv.QUOTE_NONE");
PYTHON_PROVIDE("_csv.QUOTE_NONNUMERIC");
PYTHON_PROVIDE("_csv.__doc__");
PYTHON_PROVIDE("_csv.__loader__");
PYTHON_PROVIDE("_csv.__name__");
PYTHON_PROVIDE("_csv.__package__");
PYTHON_PROVIDE("_csv.__spec__");
PYTHON_PROVIDE("_csv.__version__");
PYTHON_PROVIDE("_csv._dialects");
PYTHON_PROVIDE("_csv.field_size_limit");
PYTHON_PROVIDE("_csv.get_dialect");
PYTHON_PROVIDE("_csv.list_dialects");
PYTHON_PROVIDE("_csv.reader");
PYTHON_PROVIDE("_csv.register_dialect");
PYTHON_PROVIDE("_csv.unregister_dialect");
PYTHON_PROVIDE("_csv.writer");
/*
This module provides the low-level underpinnings of a CSV reading/writing
module. Users should not use this module directly, but import the csv.py
module instead.
*/
#define MODULE_VERSION "1.0"
typedef struct {
PyObject *error_obj; /* CSV exception */
PyObject *dialects; /* Dialect registry */
long field_limit; /* max parsed field size */
} _csvstate;
#define _csvstate(o) ((_csvstate *)PyModule_GetState(o))
static int
_csv_clear(PyObject *m)
{
Py_CLEAR(_csvstate(m)->error_obj);
Py_CLEAR(_csvstate(m)->dialects);
return 0;
}
static int
_csv_traverse(PyObject *m, visitproc visit, void *arg)
{
Py_VISIT(_csvstate(m)->error_obj);
Py_VISIT(_csvstate(m)->dialects);
return 0;
}
static void
_csv_free(void *m)
{
_csv_clear((PyObject *)m);
}
static struct PyModuleDef _csvmodule;
#define _csvstate_global ((_csvstate *)PyModule_GetState(PyState_FindModule(&_csvmodule)))
typedef enum {
START_RECORD, START_FIELD, ESCAPED_CHAR, IN_FIELD,
IN_QUOTED_FIELD, ESCAPE_IN_QUOTED_FIELD, QUOTE_IN_QUOTED_FIELD,
EAT_CRNL,AFTER_ESCAPED_CRNL
} ParserState;
typedef enum {
QUOTE_MINIMAL, QUOTE_ALL, QUOTE_NONNUMERIC, QUOTE_NONE
} QuoteStyle;
typedef struct {
QuoteStyle style;
const char *name;
} StyleDesc;
static const StyleDesc quote_styles[] = {
{ 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 ""? */
Py_UCS4 delimiter; /* field separator */
Py_UCS4 quotechar; /* quote character */
Py_UCS4 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;
static PyTypeObject Dialect_Type;
typedef struct {
PyObject_HEAD
PyObject *input_iter; /* iterate over this for input lines */
DialectObj *dialect; /* parsing dialect */
PyObject *fields; /* field list for current record */
ParserState state; /* current CSV parse state */
Py_UCS4 *field; /* temporary buffer */
Py_ssize_t field_size; /* size of allocated buffer */
Py_ssize_t field_len; /* length of current field */
int numeric_field; /* treat field as numeric */
unsigned long line_num; /* Source-file line number */
} ReaderObj;
static PyTypeObject Reader_Type;
#define ReaderObject_Check(v) (Py_TYPE(v) == &Reader_Type)
typedef struct {
PyObject_HEAD
PyObject *writeline; /* write output lines to this file */
DialectObj *dialect; /* parsing dialect */
Py_UCS4 *rec; /* buffer for parser.join */
Py_ssize_t rec_size; /* size of allocated record */
Py_ssize_t rec_len; /* length of record */
int num_fields; /* number of fields in record */
} WriterObj;
static PyTypeObject Writer_Type;
/*
* DIALECT class
*/
static PyObject *
get_dialect_from_registry(PyObject * name_obj)
{
PyObject *dialect_obj;
dialect_obj = PyDict_GetItem(_csvstate_global->dialects, name_obj);
if (dialect_obj == NULL) {
if (!PyErr_Occurred())
PyErr_Format(_csvstate_global->error_obj, "unknown dialect");
}
else
Py_INCREF(dialect_obj);
return dialect_obj;
}
static PyObject *
get_string(PyObject *str)
{
Py_XINCREF(str);
return str;
}
static PyObject *
get_nullchar_as_None(Py_UCS4 c)
{
if (c == '\0') {
Py_INCREF(Py_None);
return Py_None;
}
else
return PyUnicode_FromOrdinal(c);
}
static PyObject *
Dialect_get_lineterminator(DialectObj *self, void *Py_UNUSED(ignored))
{
return get_string(self->lineterminator);
}
static PyObject *
Dialect_get_delimiter(DialectObj *self, void *Py_UNUSED(ignored))
{
return get_nullchar_as_None(self->delimiter);
}
static PyObject *
Dialect_get_escapechar(DialectObj *self, void *Py_UNUSED(ignored))
{
return get_nullchar_as_None(self->escapechar);
}
static PyObject *
Dialect_get_quotechar(DialectObj *self, void *Py_UNUSED(ignored))
{
return get_nullchar_as_None(self->quotechar);
}
static PyObject *
Dialect_get_quoting(DialectObj *self, void *Py_UNUSED(ignored))
{
return PyLong_FromLong(self->quoting);
}
static int
_set_bool(const char *name, int *target, PyObject *src, int dflt)
{
if (src == NULL)
*target = dflt;
else {
int b = PyObject_IsTrue(src);
if (b < 0)
return -1;
*target = b;
}
return 0;
}
static int
_set_int(const char *name, int *target, PyObject *src, int dflt)
{
if (src == NULL)
*target = dflt;
else {
long value;
if (!PyLong_CheckExact(src)) {
PyErr_Format(PyExc_TypeError,
"\"%s\" must be an integer", name);
return -1;
}
value = PyLong_AsLong(src);
if (value == -1 && PyErr_Occurred())
return -1;
#if SIZEOF_LONG > SIZEOF_INT
if (value > INT_MAX || value < INT_MIN) {
PyErr_Format(PyExc_ValueError,
"integer out of range for \"%s\"", name);
return -1;
}
#endif
*target = (int)value;
}
return 0;
}
static int
_set_char(const char *name, Py_UCS4 *target, PyObject *src, Py_UCS4 dflt)
{
if (src == NULL)
*target = dflt;
else {
*target = '\0';
if (src != Py_None) {
Py_ssize_t len;
if (!PyUnicode_Check(src)) {
PyErr_Format(PyExc_TypeError,
"\"%s\" must be string, not %.200s", name,
src->ob_type->tp_name);
return -1;
}
len = PyUnicode_GetLength(src);
if (len > 1) {
PyErr_Format(PyExc_TypeError,
"\"%s\" must be a 1-character string",
name);
return -1;
}
/* PyUnicode_READY() is called in PyUnicode_GetLength() */
if (len > 0)
*target = PyUnicode_READ_CHAR(src, 0);
}
}
return 0;
}
static int
_set_str(const char *name, PyObject **target, PyObject *src, const char *dflt)
{
if (src == NULL)
*target = PyUnicode_DecodeASCII(dflt, strlen(dflt), NULL);
else {
if (src == Py_None)
*target = NULL;
else if (!PyUnicode_Check(src)) {
PyErr_Format(PyExc_TypeError,
"\"%s\" must be a string", name);
return -1;
}
else {
if (PyUnicode_READY(src) == -1)
return -1;
Py_INCREF(src);
Py_XSETREF(*target, src);
}
}
return 0;
}
static int
dialect_check_quoting(int quoting)
{
const StyleDesc *qs;
for (qs = quote_styles; qs->name; qs++) {
if ((int)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[] = {
{ "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[] = {
{ "delimiter", (getter)Dialect_get_delimiter},
{ "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);
}
static char *dialect_kws[] = {
"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,
"echar,
"ing,
&skipinitialspace,
&strict))
return NULL;
if (dialect != NULL) {
if (PyUnicode_Check(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 */
#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 a 1-character string");
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;
}
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 */
0, /* tp_reserved */
(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 */
};
/*
* Return an instance of the dialect type, given a Python instance or kwarg
* description of the dialect
*/
static PyObject *
_call_dialect(PyObject *dialect_inst, PyObject *kwargs)
{
PyObject *type = (PyObject *)&Dialect_Type;
if (dialect_inst) {
return _PyObject_FastCallDict(type, &dialect_inst, 1, kwargs);
}
else {
return _PyObject_FastCallDict(type, NULL, 0, kwargs);
}
}
/*
* READER
*/
static int
parse_save_field(ReaderObj *self)
{
PyObject *field;
field = PyUnicode_FromKindAndData(PyUnicode_4BYTE_KIND,
(void *) 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);
Py_DECREF(field);
if (tmp == NULL)
return -1;
field = tmp;
}
if (PyList_Append(self->fields, field) < 0) {
Py_DECREF(field);
return -1;
}
Py_DECREF(field);
return 0;
}
static int
parse_grow_buff(ReaderObj *self)
{
assert((size_t)self->field_size <= PY_SSIZE_T_MAX / sizeof(Py_UCS4));
Py_ssize_t field_size_new = self->field_size ? 2 * self->field_size : 4096;
Py_UCS4 *field_new = self->field;
PyMem_Resize(field_new, Py_UCS4, field_size_new);
if (field_new == NULL) {
PyErr_NoMemory();
return 0;
}
self->field = field_new;
self->field_size = field_size_new;
return 1;
}
static int
parse_add_char(ReaderObj *self, Py_UCS4 c)
{
if (self->field_len >= _csvstate_global->field_limit) {
PyErr_Format(_csvstate_global->error_obj, "field larger than field limit (%ld)",
_csvstate_global->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, Py_UCS4 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 == '\n' || c=='\r') {
if (parse_add_char(self, c) < 0)
return -1;
self->state = AFTER_ESCAPED_CRNL;
break;
}
if (c == '\0')
c = '\n';
if (parse_add_char(self, c) < 0)
return -1;
self->state = IN_FIELD;
break;
case AFTER_ESCAPED_CRNL:
if (c == '\0')
break;
/*fallthru*/
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 a 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(_csvstate_global->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(_csvstate_global->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_XSETREF(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 *fields = NULL;
Py_UCS4 c;
Py_ssize_t pos, linelen;
unsigned int kind;
void *data;
PyObject *lineobj;
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 ||
self->state == IN_QUOTED_FIELD)) {
if (self->dialect->strict)
PyErr_SetString(_csvstate_global->error_obj,
"unexpected end of data");
else if (parse_save_field(self) >= 0)
break;
}
return NULL;
}
if (!PyUnicode_Check(lineobj)) {
PyErr_Format(_csvstate_global->error_obj,
"iterator should return strings, "
"not %.200s "
"(did you open the file in text mode?)",
lineobj->ob_type->tp_name
);
Py_DECREF(lineobj);
return NULL;
}
if (PyUnicode_READY(lineobj) == -1) {
Py_DECREF(lineobj);
return NULL;
}
++self->line_num;
kind = PyUnicode_KIND(lineobj);
data = PyUnicode_DATA(lineobj);
pos = 0;
linelen = PyUnicode_GET_LENGTH(lineobj);
while (linelen--) {
c = PyUnicode_READ(kind, data, pos);
if (c == '\0') {
Py_DECREF(lineobj);
PyErr_Format(_csvstate_global->error_obj,
"line contains NULL byte");
goto err;
}
if (parse_process_char(self, c) < 0) {
Py_DECREF(lineobj);
goto err;
}
pos++;
}
Py_DECREF(lineobj);
if (parse_process_char(self, 0) < 0)
goto err;
} while (self->state != START_RECORD);
fields = self->fields;
self->fields = NULL;
err:
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);
}
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;
}
static int
Reader_clear(ReaderObj *self)
{
Py_CLEAR(self->dialect);
Py_CLEAR(self->input_iter);
Py_CLEAR(self->fields);
return 0;
}
PyDoc_STRVAR(Reader_Type_doc,
"CSV reader\n"
"\n"
"Reader objects are responsible for reading and parsing tabular data\n"
"in CSV format.\n"
);
static struct PyMethodDef Reader_methods[] = {
{ NULL, NULL }
};
#define R_OFF(x) offsetof(ReaderObj, x)
static struct PyMemberDef Reader_memberlist[] = {
{ "dialect", T_OBJECT, R_OFF(dialect), READONLY },
{ "line_num", T_ULONG, R_OFF(line_num), READONLY },
{ 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*/
0, /*tp_reserved*/
(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;
}
/*
* WRITER
*/
/* ---------------------------------------------------------------- */
static void
join_reset(WriterObj *self)
{
self->rec_len = 0;
self->num_fields = 0;
}
#define MEM_INCR 32768
/* Calculate new record length or append field to record. Return new
* record length.
*/
static Py_ssize_t
join_append_data(WriterObj *self, unsigned int field_kind, void *field_data,
Py_ssize_t field_len, int *quoted,
int copy_phase)
{
DialectObj *dialect = self->dialect;
int i;
Py_ssize_t rec_len;
#define INCLEN \
do {\
if (!copy_phase && rec_len == PY_SSIZE_T_MAX) { \
goto overflow; \
} \
rec_len++; \
} while(0)
#define ADDCH(c) \
do {\
if (copy_phase) \
self->rec[rec_len] = c;\
INCLEN;\
} while(0)
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 */
/* If field is null just pass over */
for (i = 0; field_data && (i < field_len); i++) {
Py_UCS4 c = PyUnicode_READ(field_kind, field_data, i);
int want_escape = 0;
if (c == dialect->delimiter ||
c == dialect->escapechar ||
c == dialect->quotechar ||
PyUnicode_FindChar(
dialect->lineterminator, c, 0,
PyUnicode_GET_LENGTH(dialect->lineterminator), 1) >= 0) {
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(_csvstate_global->error_obj,
"need to escape, but no escapechar set");
return -1;
}
ADDCH(dialect->escapechar);
}
}
/* Copy field character into record buffer.
*/
ADDCH(c);
}
if (*quoted) {
if (copy_phase)
ADDCH(dialect->quotechar);
else {
INCLEN; /* starting quote */
INCLEN; /* ending quote */
}
}
return rec_len;
overflow:
PyErr_NoMemory();
return -1;
#undef ADDCH
#undef INCLEN
}
static int
join_check_rec_size(WriterObj *self, Py_ssize_t rec_len)
{
assert(rec_len >= 0);
if (rec_len > self->rec_size) {
size_t rec_size_new = (size_t)(rec_len / MEM_INCR + 1) * MEM_INCR;
Py_UCS4 *rec_new = self->rec;
PyMem_Resize(rec_new, Py_UCS4, rec_size_new);
if (rec_new == NULL) {
PyErr_NoMemory();
return 0;
}
self->rec = rec_new;
self->rec_size = (Py_ssize_t)rec_size_new;
}
return 1;
}
static int
join_append(WriterObj *self, PyObject *field, int quoted)
{
unsigned int field_kind = -1;
void *field_data = NULL;
Py_ssize_t field_len = 0;
Py_ssize_t rec_len;
if (field != NULL) {
if (PyUnicode_READY(field) == -1)
return 0;
field_kind = PyUnicode_KIND(field);
field_data = PyUnicode_DATA(field);
field_len = PyUnicode_GET_LENGTH(field);
}
rec_len = join_append_data(self, field_kind, field_data, field_len,
"ed, 0);
if (rec_len < 0)
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_kind, field_data, field_len,
"ed, 1);
self->num_fields++;
return 1;
}
static int
join_append_lineterminator(WriterObj *self)
{
Py_ssize_t terminator_len, i;
unsigned int term_kind;
void *term_data;
terminator_len = PyUnicode_GET_LENGTH(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;
term_kind = PyUnicode_KIND(self->dialect->lineterminator);
term_data = PyUnicode_DATA(self->dialect->lineterminator);
for (i = 0; i < terminator_len; i++)
self->rec[self->rec_len + i] = PyUnicode_READ(term_kind, term_data, i);
self->rec_len += terminator_len;
return 1;
}
PyDoc_STRVAR(csv_writerow_doc,
"writerow(iterable)\n"
"\n"
"Construct and write a CSV record from an iterable of fields. Non-string\n"
"elements will be converted to string.");
static PyObject *
csv_writerow(WriterObj *self, PyObject *seq)
{
DialectObj *dialect = self->dialect;
PyObject *iter, *field, *line, *result;
iter = PyObject_GetIter(seq);
if (iter == NULL)
return PyErr_Format(_csvstate_global->error_obj,
"iterable expected, not %.200s",
seq->ob_type->tp_name);
/* Join all fields in internal buffer.
*/
join_reset(self);
while ((field = PyIter_Next(iter))) {
int append_ok;
int quoted;
switch (dialect->quoting) {
case QUOTE_NONNUMERIC:
quoted = !PyNumber_Check(field);
break;
case QUOTE_ALL:
quoted = 1;
break;
default:
quoted = 0;
break;
}
if (PyUnicode_Check(field)) {
append_ok = join_append(self, field, quoted);
Py_DECREF(field);
}
else if (field == Py_None) {
append_ok = join_append(self, NULL, quoted);
Py_DECREF(field);
}
else {
PyObject *str;
str = PyObject_Str(field);
Py_DECREF(field);
if (str == NULL) {
Py_DECREF(iter);
return NULL;
}
append_ok = join_append(self, str, quoted);
Py_DECREF(str);
}
if (!append_ok) {
Py_DECREF(iter);
return NULL;
}
}
Py_DECREF(iter);
if (PyErr_Occurred())
return NULL;
if (self->num_fields > 0 && self->rec_len == 0) {
if (dialect->quoting == QUOTE_NONE) {
PyErr_Format(_csvstate_global->error_obj,
"single empty field record must be quoted");
return NULL;
}
self->num_fields--;
if (!join_append(self, NULL, 1))
return NULL;
}
/* Add line terminator.
*/
if (!join_append_lineterminator(self))
return NULL;
line = PyUnicode_FromKindAndData(PyUnicode_4BYTE_KIND,
(void *) self->rec, self->rec_len);
if (line == NULL)
return NULL;
result = PyObject_CallFunctionObjArgs(self->writeline, line, NULL);
Py_DECREF(line);
return result;
}
PyDoc_STRVAR(csv_writerows_doc,
"writerows(iterable of iterables)\n"
"\n"
"Construct and write a series of iterables to a csv file. Non-string\n"
"elements will be converted to string.");
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;
}
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;
}
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 }
};
#define W_OFF(x) offsetof(WriterObj, x)
static struct PyMemberDef Writer_memberlist[] = {
{ "dialect", T_OBJECT, W_OFF(dialect), READONLY },
{ 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);
}
static int
Writer_traverse(WriterObj *self, visitproc visit, void *arg)
{
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;
}
PyDoc_STRVAR(Writer_Type_doc,
"CSV writer\n"
"\n"
"Writer objects are responsible for generating tabular data\n"
"in CSV format from sequence input.\n"
);
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*/
0, /*tp_reserved*/
(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);
_Py_IDENTIFIER(write);
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_GetAttrId(output_file, &PyId_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;
}
/*
* DIALECT REGISTRY
*/
static PyObject *
csv_list_dialects(PyObject *module, PyObject *args)
{
return PyDict_Keys(_csvstate_global->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 (!PyUnicode_Check(name_obj)) {
PyErr_SetString(PyExc_TypeError,
"dialect name must be a string");
return NULL;
}
if (PyUnicode_READY(name_obj) == -1)
return NULL;
dialect = _call_dialect(dialect_obj, kwargs);
if (dialect == NULL)
return NULL;
if (PyDict_SetItem(_csvstate_global->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(_csvstate_global->dialects, name_obj) < 0)
return PyErr_Format(_csvstate_global->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);
}
static PyObject *
csv_field_size_limit(PyObject *module, PyObject *args)
{
PyObject *new_limit = NULL;
long old_limit = _csvstate_global->field_limit;
if (!PyArg_UnpackTuple(args, "field_size_limit", 0, 1, &new_limit))
return NULL;
if (new_limit != NULL) {
if (!PyLong_CheckExact(new_limit)) {
PyErr_Format(PyExc_TypeError,
"limit must be an integer");
return NULL;
}
_csvstate_global->field_limit = PyLong_AsLong(new_limit);
if (_csvstate_global->field_limit == -1 && PyErr_Occurred()) {
_csvstate_global->field_limit = old_limit;
return NULL;
}
}
return PyLong_FromLong(old_limit);
}
/*
* MODULE
*/
PyDoc_STRVAR(csv_module_doc,
"CSV parsing and writing.\n"
"\n"
"This module provides classes that assist in the reading and writing\n"
"of Comma Separated Value (CSV) files, and implements the interface\n"
"described by PEP 305. Although many CSV files are simple to parse,\n"
"the format is not formally defined by a stable specification and\n"
"is subtle enough that parsing lines of a CSV file with something\n"
"like line.split(\",\") is bound to fail. The module supports three\n"
"basic APIs: reading, writing, and registration of dialects.\n"
"\n"
"\n"
"DIALECT REGISTRATION:\n"
"\n"
"Readers and writers support a dialect argument, which is a convenient\n"
"handle on a group of settings. When the dialect argument is a string,\n"
"it identifies one of the dialects previously registered with the module.\n"
"If it is a class or instance, the attributes of the argument are used as\n"
"the settings for the reader or writer:\n"
"\n"
" class excel:\n"
" delimiter = ','\n"
" quotechar = '\"'\n"
" escapechar = None\n"
" doublequote = True\n"
" skipinitialspace = False\n"
" lineterminator = '\\r\\n'\n"
" quoting = QUOTE_MINIMAL\n"
"\n"
"SETTINGS:\n"
"\n"
" * quotechar - specifies a one-character string to use as the \n"
" quoting character. It defaults to '\"'.\n"
" * delimiter - specifies a one-character string to use as the \n"
" field separator. It defaults to ','.\n"
" * skipinitialspace - specifies how to interpret whitespace which\n"
" immediately follows a delimiter. It defaults to False, which\n"
" means that whitespace immediately following a delimiter is part\n"
" of the following field.\n"
" * lineterminator - specifies the character sequence which should \n"
" terminate rows.\n"
" * quoting - controls when quotes should be generated by the writer.\n"
" It can take on any of the following module constants:\n"
"\n"
" csv.QUOTE_MINIMAL means only when required, for example, when a\n"
" field contains either the quotechar or the delimiter\n"
" csv.QUOTE_ALL means that quotes are always placed around fields.\n"
" csv.QUOTE_NONNUMERIC means that quotes are always placed around\n"
" fields which do not parse as integers or floating point\n"
" numbers.\n"
" csv.QUOTE_NONE means that quotes are never placed around fields.\n"
" * escapechar - specifies a one-character string used to escape \n"
" the delimiter when quoting is set to QUOTE_NONE.\n"
" * doublequote - controls the handling of quotes inside fields. When\n"
" True, two consecutive quotes are interpreted as one during read,\n"
" and when writing, each quote character embedded in the data is\n"
" written as two quotes\n");
PyDoc_STRVAR(csv_reader_doc,
" csv_reader = reader(iterable [, dialect='excel']\n"
" [optional keyword args])\n"
" for row in csv_reader:\n"
" process(row)\n"
"\n"
"The \"iterable\" argument can be any object that returns a line\n"
"of input for each iteration, such as a file object or a list. The\n"
"optional \"dialect\" parameter is discussed below. The function\n"
"also accepts optional keyword arguments which override settings\n"
"provided by the dialect.\n"
"\n"
"The returned object is an iterator. Each iteration returns a row\n"
"of the CSV file (which can span multiple input lines).\n");
PyDoc_STRVAR(csv_writer_doc,
" csv_writer = csv.writer(fileobj [, dialect='excel']\n"
" [optional keyword args])\n"
" for row in sequence:\n"
" csv_writer.writerow(row)\n"
"\n"
" [or]\n"
"\n"
" csv_writer = csv.writer(fileobj [, dialect='excel']\n"
" [optional keyword args])\n"
" csv_writer.writerows(rows)\n"
"\n"
"The \"fileobj\" argument can be any object that supports the file API.\n");
PyDoc_STRVAR(csv_list_dialects_doc,
"Return a list of all know dialect names.\n"
" names = csv.list_dialects()");
PyDoc_STRVAR(csv_get_dialect_doc,
"Return the dialect instance associated with name.\n"
" dialect = csv.get_dialect(name)");
PyDoc_STRVAR(csv_register_dialect_doc,
"Create a mapping from a string name to a dialect class.\n"
" dialect = csv.register_dialect(name[, dialect[, **fmtparams]])");
PyDoc_STRVAR(csv_unregister_dialect_doc,
"Delete the name/dialect mapping associated with a string name.\n"
" csv.unregister_dialect(name)");
PyDoc_STRVAR(csv_field_size_limit_doc,
"Sets an upper limit on parsed fields.\n"
" csv.field_size_limit([limit])\n"
"\n"
"Returns old limit. If limit is not given, no new limit is set and\n"
"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 }
};
static struct PyModuleDef _csvmodule = {
PyModuleDef_HEAD_INIT,
"_csv",
csv_module_doc,
sizeof(_csvstate),
csv_methods,
NULL,
_csv_traverse,
_csv_clear,
_csv_free
};
PyMODINIT_FUNC
PyInit__csv(void)
{
PyObject *module;
const StyleDesc *style;
if (PyType_Ready(&Dialect_Type) < 0)
return NULL;
if (PyType_Ready(&Reader_Type) < 0)
return NULL;
if (PyType_Ready(&Writer_Type) < 0)
return NULL;
/* Create the module and add the functions */
module = PyModule_Create(&_csvmodule);
if (module == NULL)
return NULL;
/* Add version to the module. */
if (PyModule_AddStringConstant(module, "__version__",
MODULE_VERSION) == -1)
return NULL;
/* Set the field limit */
_csvstate(module)->field_limit = 128 * 1024;
/* Do I still need to add this var to the Module Dict? */
/* Add _dialects dictionary */
_csvstate(module)->dialects = PyDict_New();
if (_csvstate(module)->dialects == NULL)
return NULL;
Py_INCREF(_csvstate(module)->dialects);
if (PyModule_AddObject(module, "_dialects", _csvstate(module)->dialects))
return NULL;
/* Add quote styles into dictionary */
for (style = quote_styles; style->name; style++) {
if (PyModule_AddIntConstant(module, style->name,
style->style) == -1)
return NULL;
}
/* Add the Dialect type */
Py_INCREF(&Dialect_Type);
if (PyModule_AddObject(module, "Dialect", (PyObject *)&Dialect_Type))
return NULL;
/* Add the CSV exception object to the module. */
_csvstate(module)->error_obj = PyErr_NewException("_csv.Error", NULL, NULL);
if (_csvstate(module)->error_obj == NULL)
return NULL;
Py_INCREF(_csvstate(module)->error_obj);
PyModule_AddObject(module, "Error", _csvstate(module)->error_obj);
return module;
}
_Section(".rodata.pytab.1") const struct _inittab _PyImport_Inittab__csv = {
"_csv",
PyInit__csv,
};
| 53,188 | 1,724 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Modules/_asynciomodule.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:8;coding:utf-8 -*-â
âvi: set net ft=c ts=4 sts=4 sw=4 fenc=utf-8 :viâ
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ¡
â Python 3 â
â https://docs.python.org/3/license.html â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
#include "third_party/python/Include/abstract.h"
#include "third_party/python/Include/boolobject.h"
#include "third_party/python/Include/descrobject.h"
#include "third_party/python/Include/dictobject.h"
#include "third_party/python/Include/genobject.h"
#include "third_party/python/Include/import.h"
#include "third_party/python/Include/listobject.h"
#include "third_party/python/Include/longobject.h"
#include "third_party/python/Include/modsupport.h"
#include "third_party/python/Include/object.h"
#include "third_party/python/Include/objimpl.h"
#include "third_party/python/Include/pyerrors.h"
#include "third_party/python/Include/pymacro.h"
#include "third_party/python/Include/setobject.h"
#include "third_party/python/Include/structmember.h"
#include "third_party/python/Include/traceback.h"
#include "third_party/python/Include/yoink.h"
/* clang-format off */
PYTHON_PROVIDE("_asyncio");
PYTHON_PROVIDE("_asyncio.Future");
PYTHON_PROVIDE("_asyncio.Task");
/*[clinic input]
module _asyncio
[clinic start generated code]*/
/*[clinic end generated code: output=da39a3ee5e6b4b0d input=8fd17862aa989c69]*/
/* identifiers used from some functions */
_Py_IDENTIFIER(add_done_callback);
_Py_IDENTIFIER(call_soon);
_Py_IDENTIFIER(cancel);
_Py_IDENTIFIER(send);
_Py_IDENTIFIER(throw);
_Py_IDENTIFIER(_step);
_Py_IDENTIFIER(_schedule_callbacks);
_Py_IDENTIFIER(_wakeup);
/* State of the _asyncio module */
static PyObject *all_tasks;
static PyObject *current_tasks;
static PyObject *traceback_extract_stack;
static PyObject *asyncio_get_event_loop;
static PyObject *asyncio_future_repr_info_func;
static PyObject *asyncio_task_repr_info_func;
static PyObject *asyncio_task_get_stack_func;
static PyObject *asyncio_task_print_stack_func;
static PyObject *asyncio_InvalidStateError;
static PyObject *asyncio_CancelledError;
static PyObject *inspect_isgenerator;
typedef enum {
STATE_PENDING,
STATE_CANCELLED,
STATE_FINISHED
} fut_state;
#define FutureObj_HEAD(prefix) \
PyObject_HEAD \
PyObject *prefix##_loop; \
PyObject *prefix##_callbacks; \
PyObject *prefix##_exception; \
PyObject *prefix##_result; \
PyObject *prefix##_source_tb; \
fut_state prefix##_state; \
int prefix##_log_tb; \
int prefix##_blocking; \
PyObject *dict; \
PyObject *prefix##_weakreflist;
typedef struct {
FutureObj_HEAD(fut)
} FutureObj;
typedef struct {
FutureObj_HEAD(task)
PyObject *task_fut_waiter;
PyObject *task_coro;
int task_must_cancel;
int task_log_destroy_pending;
} TaskObj;
typedef struct {
PyObject_HEAD
TaskObj *sw_task;
PyObject *sw_arg;
} TaskStepMethWrapper;
typedef struct {
PyObject_HEAD
TaskObj *ww_task;
} TaskWakeupMethWrapper;
#include "third_party/python/Modules/clinic/_asynciomodule.inc"
/*[clinic input]
class _asyncio.Future "FutureObj *" "&Future_Type"
[clinic start generated code]*/
/*[clinic end generated code: output=da39a3ee5e6b4b0d input=00d3e4abca711e0f]*/
/* Get FutureIter from Future */
static PyObject* future_new_iter(PyObject *);
static inline int future_call_schedule_callbacks(FutureObj *);
static int
future_schedule_callbacks(FutureObj *fut)
{
Py_ssize_t len;
PyObject *callbacks;
int i;
if (fut->fut_callbacks == NULL) {
PyErr_SetString(PyExc_RuntimeError, "uninitialized Future object");
return -1;
}
len = PyList_GET_SIZE(fut->fut_callbacks);
if (len == 0) {
return 0;
}
callbacks = PyList_GetSlice(fut->fut_callbacks, 0, len);
if (callbacks == NULL) {
return -1;
}
if (PyList_SetSlice(fut->fut_callbacks, 0, len, NULL) < 0) {
Py_DECREF(callbacks);
return -1;
}
for (i = 0; i < len; i++) {
PyObject *handle;
PyObject *cb = PyList_GET_ITEM(callbacks, i);
handle = _PyObject_CallMethodIdObjArgs(fut->fut_loop, &PyId_call_soon,
cb, fut, NULL);
if (handle == NULL) {
Py_DECREF(callbacks);
return -1;
}
Py_DECREF(handle);
}
Py_DECREF(callbacks);
return 0;
}
static int
future_init(FutureObj *fut, PyObject *loop)
{
PyObject *res;
int is_true;
_Py_IDENTIFIER(get_debug);
// Same to FutureObj_clear() but not clearing fut->dict
Py_CLEAR(fut->fut_loop);
Py_CLEAR(fut->fut_callbacks);
Py_CLEAR(fut->fut_result);
Py_CLEAR(fut->fut_exception);
Py_CLEAR(fut->fut_source_tb);
fut->fut_state = STATE_PENDING;
fut->fut_log_tb = 0;
fut->fut_blocking = 0;
if (loop == Py_None) {
loop = _PyObject_CallNoArg(asyncio_get_event_loop);
if (loop == NULL) {
return -1;
}
}
else {
Py_INCREF(loop);
}
fut->fut_loop = loop;
res = _PyObject_CallMethodId(fut->fut_loop, &PyId_get_debug, NULL);
if (res == NULL) {
return -1;
}
is_true = PyObject_IsTrue(res);
Py_DECREF(res);
if (is_true < 0) {
return -1;
}
if (is_true) {
fut->fut_source_tb = _PyObject_CallNoArg(traceback_extract_stack);
if (fut->fut_source_tb == NULL) {
return -1;
}
}
fut->fut_callbacks = PyList_New(0);
if (fut->fut_callbacks == NULL) {
return -1;
}
return 0;
}
static PyObject *
future_set_result(FutureObj *fut, PyObject *res)
{
if (fut->fut_state != STATE_PENDING) {
PyErr_SetString(asyncio_InvalidStateError, "invalid state");
return NULL;
}
assert(!fut->fut_result);
Py_INCREF(res);
fut->fut_result = res;
fut->fut_state = STATE_FINISHED;
if (future_call_schedule_callbacks(fut) == -1) {
return NULL;
}
Py_RETURN_NONE;
}
static PyObject *
future_set_exception(FutureObj *fut, PyObject *exc)
{
PyObject *exc_val = NULL;
if (fut->fut_state != STATE_PENDING) {
PyErr_SetString(asyncio_InvalidStateError, "invalid state");
return NULL;
}
if (PyExceptionClass_Check(exc)) {
exc_val = PyObject_CallObject(exc, NULL);
if (exc_val == NULL) {
return NULL;
}
if (fut->fut_state != STATE_PENDING) {
Py_DECREF(exc_val);
PyErr_SetString(asyncio_InvalidStateError, "invalid state");
return NULL;
}
}
else {
exc_val = exc;
Py_INCREF(exc_val);
}
if (!PyExceptionInstance_Check(exc_val)) {
Py_DECREF(exc_val);
PyErr_SetString(PyExc_TypeError, "invalid exception object");
return NULL;
}
if ((PyObject*)Py_TYPE(exc_val) == PyExc_StopIteration) {
Py_DECREF(exc_val);
PyErr_SetString(PyExc_TypeError,
"StopIteration interacts badly with generators "
"and cannot be raised into a Future");
return NULL;
}
assert(!fut->fut_exception);
fut->fut_exception = exc_val;
fut->fut_state = STATE_FINISHED;
if (future_call_schedule_callbacks(fut) == -1) {
return NULL;
}
fut->fut_log_tb = 1;
Py_RETURN_NONE;
}
static int
future_get_result(FutureObj *fut, PyObject **result)
{
if (fut->fut_state == STATE_CANCELLED) {
PyErr_SetNone(asyncio_CancelledError);
return -1;
}
if (fut->fut_state != STATE_FINISHED) {
PyErr_SetString(asyncio_InvalidStateError, "Result is not set.");
return -1;
}
fut->fut_log_tb = 0;
if (fut->fut_exception != NULL) {
Py_INCREF(fut->fut_exception);
*result = fut->fut_exception;
return 1;
}
Py_INCREF(fut->fut_result);
*result = fut->fut_result;
return 0;
}
static PyObject *
future_add_done_callback(FutureObj *fut, PyObject *arg)
{
if (fut->fut_state != STATE_PENDING) {
PyObject *handle = _PyObject_CallMethodIdObjArgs(fut->fut_loop,
&PyId_call_soon,
arg, fut, NULL);
if (handle == NULL) {
return NULL;
}
Py_DECREF(handle);
}
else {
if (fut->fut_callbacks == NULL) {
PyErr_SetString(PyExc_RuntimeError, "uninitialized Future object");
return NULL;
}
int err = PyList_Append(fut->fut_callbacks, arg);
if (err != 0) {
return NULL;
}
}
Py_RETURN_NONE;
}
static PyObject *
future_cancel(FutureObj *fut)
{
fut->fut_log_tb = 0;
if (fut->fut_state != STATE_PENDING) {
Py_RETURN_FALSE;
}
fut->fut_state = STATE_CANCELLED;
if (future_call_schedule_callbacks(fut) == -1) {
return NULL;
}
Py_RETURN_TRUE;
}
/*[clinic input]
_asyncio.Future.__init__
*
loop: object = None
This class is *almost* compatible with concurrent.futures.Future.
Differences:
- result() and exception() do not take a timeout argument and
raise an exception when the future isn't done yet.
- Callbacks registered with add_done_callback() are always called
via the event loop's call_soon_threadsafe().
- This class is not compatible with the wait() and as_completed()
methods in the concurrent.futures package.
[clinic start generated code]*/
static int
_asyncio_Future___init___impl(FutureObj *self, PyObject *loop)
/*[clinic end generated code: output=9ed75799eaccb5d6 input=89af317082bc0bf8]*/
{
return future_init(self, loop);
}
static int
FutureObj_clear(FutureObj *fut)
{
Py_CLEAR(fut->fut_loop);
Py_CLEAR(fut->fut_callbacks);
Py_CLEAR(fut->fut_result);
Py_CLEAR(fut->fut_exception);
Py_CLEAR(fut->fut_source_tb);
Py_CLEAR(fut->dict);
return 0;
}
static int
FutureObj_traverse(FutureObj *fut, visitproc visit, void *arg)
{
Py_VISIT(fut->fut_loop);
Py_VISIT(fut->fut_callbacks);
Py_VISIT(fut->fut_result);
Py_VISIT(fut->fut_exception);
Py_VISIT(fut->fut_source_tb);
Py_VISIT(fut->dict);
return 0;
}
/*[clinic input]
_asyncio.Future.result
Return the result this future represents.
If the future has been cancelled, raises CancelledError. If the
future's result isn't yet available, raises InvalidStateError. If
the future is done and has an exception set, this exception is raised.
[clinic start generated code]*/
static PyObject *
_asyncio_Future_result_impl(FutureObj *self)
/*[clinic end generated code: output=f35f940936a4b1e5 input=49ecf9cf5ec50dc5]*/
{
PyObject *result;
int res = future_get_result(self, &result);
if (res == -1) {
return NULL;
}
if (res == 0) {
return result;
}
assert(res == 1);
PyErr_SetObject(PyExceptionInstance_Class(result), result);
Py_DECREF(result);
return NULL;
}
/*[clinic input]
_asyncio.Future.exception
Return the exception that was set on this future.
The exception (or None if no exception was set) is returned only if
the future is done. If the future has been cancelled, raises
CancelledError. If the future isn't done yet, raises
InvalidStateError.
[clinic start generated code]*/
static PyObject *
_asyncio_Future_exception_impl(FutureObj *self)
/*[clinic end generated code: output=88b20d4f855e0710 input=733547a70c841c68]*/
{
if (self->fut_state == STATE_CANCELLED) {
PyErr_SetNone(asyncio_CancelledError);
return NULL;
}
if (self->fut_state != STATE_FINISHED) {
PyErr_SetString(asyncio_InvalidStateError, "Exception is not set.");
return NULL;
}
if (self->fut_exception != NULL) {
self->fut_log_tb = 0;
Py_INCREF(self->fut_exception);
return self->fut_exception;
}
Py_RETURN_NONE;
}
/*[clinic input]
_asyncio.Future.set_result
res: object
/
Mark the future done and set its result.
If the future is already done when this method is called, raises
InvalidStateError.
[clinic start generated code]*/
static PyObject *
_asyncio_Future_set_result(FutureObj *self, PyObject *res)
/*[clinic end generated code: output=a620abfc2796bfb6 input=5b9dc180f1baa56d]*/
{
return future_set_result(self, res);
}
/*[clinic input]
_asyncio.Future.set_exception
exception: object
/
Mark the future done and set an exception.
If the future is already done when this method is called, raises
InvalidStateError.
[clinic start generated code]*/
static PyObject *
_asyncio_Future_set_exception(FutureObj *self, PyObject *exception)
/*[clinic end generated code: output=f1c1b0cd321be360 input=e45b7d7aa71cc66d]*/
{
return future_set_exception(self, exception);
}
/*[clinic input]
_asyncio.Future.add_done_callback
fn: object
/
Add a callback to be run when the future becomes done.
The callback is called with a single argument - the future object. If
the future is already done when this is called, the callback is
scheduled with call_soon.
[clinic start generated code]*/
static PyObject *
_asyncio_Future_add_done_callback(FutureObj *self, PyObject *fn)
/*[clinic end generated code: output=819e09629b2ec2b5 input=8f818b39990b027d]*/
{
return future_add_done_callback(self, fn);
}
/*[clinic input]
_asyncio.Future.remove_done_callback
fn: object
/
Remove all instances of a callback from the "call when done" list.
Returns the number of callbacks removed.
[clinic start generated code]*/
static PyObject *
_asyncio_Future_remove_done_callback(FutureObj *self, PyObject *fn)
/*[clinic end generated code: output=5ab1fb52b24ef31f input=0a43280a149d505b]*/
{
PyObject *newlist;
Py_ssize_t len, i, j=0;
if (self->fut_callbacks == NULL) {
PyErr_SetString(PyExc_RuntimeError, "uninitialized Future object");
return NULL;
}
len = PyList_GET_SIZE(self->fut_callbacks);
if (len == 0) {
return PyLong_FromSsize_t(0);
}
newlist = PyList_New(len);
if (newlist == NULL) {
return NULL;
}
for (i = 0; i < PyList_GET_SIZE(self->fut_callbacks); i++) {
int ret;
PyObject *item = PyList_GET_ITEM(self->fut_callbacks, i);
Py_INCREF(item);
ret = PyObject_RichCompareBool(fn, item, Py_EQ);
if (ret == 0) {
if (j < len) {
PyList_SET_ITEM(newlist, j, item);
j++;
continue;
}
ret = PyList_Append(newlist, item);
}
Py_DECREF(item);
if (ret < 0) {
goto fail;
}
}
if (j < len) {
Py_SIZE(newlist) = j;
}
j = PyList_GET_SIZE(newlist);
len = PyList_GET_SIZE(self->fut_callbacks);
if (j != len) {
if (PyList_SetSlice(self->fut_callbacks, 0, len, newlist) < 0) {
goto fail;
}
}
Py_DECREF(newlist);
return PyLong_FromSsize_t(len - j);
fail:
Py_DECREF(newlist);
return NULL;
}
/*[clinic input]
_asyncio.Future.cancel
Cancel the future and schedule callbacks.
If the future is already done or cancelled, return False. Otherwise,
change the future's state to cancelled, schedule the callbacks and
return True.
[clinic start generated code]*/
static PyObject *
_asyncio_Future_cancel_impl(FutureObj *self)
/*[clinic end generated code: output=e45b932ba8bd68a1 input=515709a127995109]*/
{
return future_cancel(self);
}
/*[clinic input]
_asyncio.Future.cancelled
Return True if the future was cancelled.
[clinic start generated code]*/
static PyObject *
_asyncio_Future_cancelled_impl(FutureObj *self)
/*[clinic end generated code: output=145197ced586357d input=943ab8b7b7b17e45]*/
{
if (self->fut_state == STATE_CANCELLED) {
Py_RETURN_TRUE;
}
else {
Py_RETURN_FALSE;
}
}
/*[clinic input]
_asyncio.Future.done
Return True if the future is done.
Done means either that a result / exception are available, or that the
future was cancelled.
[clinic start generated code]*/
static PyObject *
_asyncio_Future_done_impl(FutureObj *self)
/*[clinic end generated code: output=244c5ac351145096 input=28d7b23fdb65d2ac]*/
{
if (self->fut_state == STATE_PENDING) {
Py_RETURN_FALSE;
}
else {
Py_RETURN_TRUE;
}
}
static PyObject *
FutureObj_get_blocking(FutureObj *fut, void *Py_UNUSED(ignored))
{
if (fut->fut_blocking) {
Py_RETURN_TRUE;
}
else {
Py_RETURN_FALSE;
}
}
static int
FutureObj_set_blocking(FutureObj *fut, PyObject *val, void *Py_UNUSED(ignored))
{
int is_true = PyObject_IsTrue(val);
if (is_true < 0) {
return -1;
}
fut->fut_blocking = is_true;
return 0;
}
static PyObject *
FutureObj_get_log_traceback(FutureObj *fut, void *Py_UNUSED(ignored))
{
if (fut->fut_log_tb) {
Py_RETURN_TRUE;
}
else {
Py_RETURN_FALSE;
}
}
static int
FutureObj_set_log_traceback(FutureObj *fut, PyObject *val, void *Py_UNUSED(ignored))
{
int is_true = PyObject_IsTrue(val);
if (is_true < 0) {
return -1;
}
fut->fut_log_tb = is_true;
return 0;
}
static PyObject *
FutureObj_get_loop(FutureObj *fut, void *Py_UNUSED(ignored))
{
if (fut->fut_loop == NULL) {
Py_RETURN_NONE;
}
Py_INCREF(fut->fut_loop);
return fut->fut_loop;
}
static PyObject *
FutureObj_get_callbacks(FutureObj *fut, void *Py_UNUSED(ignored))
{
if (fut->fut_callbacks == NULL) {
Py_RETURN_NONE;
}
Py_INCREF(fut->fut_callbacks);
return fut->fut_callbacks;
}
static PyObject *
FutureObj_get_result(FutureObj *fut, void *Py_UNUSED(ignored))
{
if (fut->fut_result == NULL) {
Py_RETURN_NONE;
}
Py_INCREF(fut->fut_result);
return fut->fut_result;
}
static PyObject *
FutureObj_get_exception(FutureObj *fut, void *Py_UNUSED(ignored))
{
if (fut->fut_exception == NULL) {
Py_RETURN_NONE;
}
Py_INCREF(fut->fut_exception);
return fut->fut_exception;
}
static PyObject *
FutureObj_get_source_traceback(FutureObj *fut, void *Py_UNUSED(ignored))
{
if (fut->fut_source_tb == NULL) {
Py_RETURN_NONE;
}
Py_INCREF(fut->fut_source_tb);
return fut->fut_source_tb;
}
static PyObject *
FutureObj_get_state(FutureObj *fut, void *Py_UNUSED(ignored))
{
_Py_IDENTIFIER(PENDING);
_Py_IDENTIFIER(CANCELLED);
_Py_IDENTIFIER(FINISHED);
PyObject *ret = NULL;
switch (fut->fut_state) {
case STATE_PENDING:
ret = _PyUnicode_FromId(&PyId_PENDING);
break;
case STATE_CANCELLED:
ret = _PyUnicode_FromId(&PyId_CANCELLED);
break;
case STATE_FINISHED:
ret = _PyUnicode_FromId(&PyId_FINISHED);
break;
default:
assert (0);
}
Py_XINCREF(ret);
return ret;
}
/*[clinic input]
_asyncio.Future._repr_info
[clinic start generated code]*/
static PyObject *
_asyncio_Future__repr_info_impl(FutureObj *self)
/*[clinic end generated code: output=fa69e901bd176cfb input=f21504d8e2ae1ca2]*/
{
return PyObject_CallFunctionObjArgs(
asyncio_future_repr_info_func, self, NULL);
}
/*[clinic input]
_asyncio.Future._schedule_callbacks
[clinic start generated code]*/
static PyObject *
_asyncio_Future__schedule_callbacks_impl(FutureObj *self)
/*[clinic end generated code: output=5e8958d89ea1c5dc input=4f5f295f263f4a88]*/
{
int ret = future_schedule_callbacks(self);
if (ret == -1) {
return NULL;
}
Py_RETURN_NONE;
}
static PyObject *
FutureObj_repr(FutureObj *fut)
{
_Py_IDENTIFIER(_repr_info);
PyObject *rinfo = _PyObject_CallMethodIdObjArgs((PyObject*)fut,
&PyId__repr_info,
NULL);
if (rinfo == NULL) {
return NULL;
}
PyObject *rinfo_s = PyUnicode_Join(NULL, rinfo);
Py_DECREF(rinfo);
if (rinfo_s == NULL) {
return NULL;
}
PyObject *rstr = NULL;
PyObject *type_name = PyObject_GetAttrString((PyObject*)Py_TYPE(fut),
"__name__");
if (type_name != NULL) {
rstr = PyUnicode_FromFormat("<%S %U>", type_name, rinfo_s);
Py_DECREF(type_name);
}
Py_DECREF(rinfo_s);
return rstr;
}
static void
FutureObj_finalize(FutureObj *fut)
{
_Py_IDENTIFIER(call_exception_handler);
_Py_IDENTIFIER(message);
_Py_IDENTIFIER(exception);
_Py_IDENTIFIER(future);
_Py_IDENTIFIER(source_traceback);
PyObject *error_type, *error_value, *error_traceback;
PyObject *context;
PyObject *type_name;
PyObject *message = NULL;
PyObject *func;
if (!fut->fut_log_tb) {
return;
}
assert(fut->fut_exception != NULL);
fut->fut_log_tb = 0;
/* Save the current exception, if any. */
PyErr_Fetch(&error_type, &error_value, &error_traceback);
context = PyDict_New();
if (context == NULL) {
goto finally;
}
type_name = PyObject_GetAttrString((PyObject*)Py_TYPE(fut), "__name__");
if (type_name == NULL) {
goto finally;
}
message = PyUnicode_FromFormat(
"%S exception was never retrieved", type_name);
Py_DECREF(type_name);
if (message == NULL) {
goto finally;
}
if (_PyDict_SetItemId(context, &PyId_message, message) < 0 ||
_PyDict_SetItemId(context, &PyId_exception, fut->fut_exception) < 0 ||
_PyDict_SetItemId(context, &PyId_future, (PyObject*)fut) < 0) {
goto finally;
}
if (fut->fut_source_tb != NULL) {
if (_PyDict_SetItemId(context, &PyId_source_traceback,
fut->fut_source_tb) < 0) {
goto finally;
}
}
func = _PyObject_GetAttrId(fut->fut_loop, &PyId_call_exception_handler);
if (func != NULL) {
PyObject *res = _PyObject_CallArg1(func, context);
if (res == NULL) {
PyErr_WriteUnraisable(func);
}
else {
Py_DECREF(res);
}
Py_DECREF(func);
}
finally:
Py_XDECREF(context);
Py_XDECREF(message);
/* Restore the saved exception. */
PyErr_Restore(error_type, error_value, error_traceback);
}
static PyAsyncMethods FutureType_as_async = {
(unaryfunc)future_new_iter, /* am_await */
0, /* am_aiter */
0 /* am_anext */
};
static PyMethodDef FutureType_methods[] = {
_ASYNCIO_FUTURE_RESULT_METHODDEF
_ASYNCIO_FUTURE_EXCEPTION_METHODDEF
_ASYNCIO_FUTURE_SET_RESULT_METHODDEF
_ASYNCIO_FUTURE_SET_EXCEPTION_METHODDEF
_ASYNCIO_FUTURE_ADD_DONE_CALLBACK_METHODDEF
_ASYNCIO_FUTURE_REMOVE_DONE_CALLBACK_METHODDEF
_ASYNCIO_FUTURE_CANCEL_METHODDEF
_ASYNCIO_FUTURE_CANCELLED_METHODDEF
_ASYNCIO_FUTURE_DONE_METHODDEF
_ASYNCIO_FUTURE__REPR_INFO_METHODDEF
_ASYNCIO_FUTURE__SCHEDULE_CALLBACKS_METHODDEF
{NULL, NULL} /* Sentinel */
};
#define FUTURE_COMMON_GETSETLIST \
{"_state", (getter)FutureObj_get_state, NULL, NULL}, \
{"_asyncio_future_blocking", (getter)FutureObj_get_blocking, \
(setter)FutureObj_set_blocking, NULL}, \
{"_loop", (getter)FutureObj_get_loop, NULL, NULL}, \
{"_callbacks", (getter)FutureObj_get_callbacks, NULL, NULL}, \
{"_result", (getter)FutureObj_get_result, NULL, NULL}, \
{"_exception", (getter)FutureObj_get_exception, NULL, NULL}, \
{"_log_traceback", (getter)FutureObj_get_log_traceback, \
(setter)FutureObj_set_log_traceback, NULL}, \
{"_source_traceback", (getter)FutureObj_get_source_traceback, NULL, NULL},
static PyGetSetDef FutureType_getsetlist[] = {
FUTURE_COMMON_GETSETLIST
{NULL} /* Sentinel */
};
static void FutureObj_dealloc(PyObject *self);
static PyTypeObject FutureType = {
PyVarObject_HEAD_INIT(NULL, 0)
"_asyncio.Future",
sizeof(FutureObj), /* tp_basicsize */
.tp_dealloc = FutureObj_dealloc,
.tp_as_async = &FutureType_as_async,
.tp_repr = (reprfunc)FutureObj_repr,
.tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC | Py_TPFLAGS_BASETYPE
| Py_TPFLAGS_HAVE_FINALIZE,
.tp_doc = _asyncio_Future___init____doc__,
.tp_traverse = (traverseproc)FutureObj_traverse,
.tp_clear = (inquiry)FutureObj_clear,
.tp_weaklistoffset = offsetof(FutureObj, fut_weakreflist),
.tp_iter = (getiterfunc)future_new_iter,
.tp_methods = FutureType_methods,
.tp_getset = FutureType_getsetlist,
.tp_dictoffset = offsetof(FutureObj, dict),
.tp_init = (initproc)_asyncio_Future___init__,
.tp_new = PyType_GenericNew,
.tp_finalize = (destructor)FutureObj_finalize,
};
#define Future_CheckExact(obj) (Py_TYPE(obj) == &FutureType)
static inline int
future_call_schedule_callbacks(FutureObj *fut)
{
if (Future_CheckExact(fut)) {
return future_schedule_callbacks(fut);
}
else {
/* `fut` is a subclass of Future */
PyObject *ret = _PyObject_CallMethodId(
(PyObject*)fut, &PyId__schedule_callbacks, NULL);
if (ret == NULL) {
return -1;
}
Py_DECREF(ret);
return 0;
}
}
static void
FutureObj_dealloc(PyObject *self)
{
FutureObj *fut = (FutureObj *)self;
if (Future_CheckExact(fut)) {
/* When fut is subclass of Future, finalizer is called from
* subtype_dealloc.
*/
if (PyObject_CallFinalizerFromDealloc(self) < 0) {
// resurrected.
return;
}
}
PyObject_GC_UnTrack(self);
if (fut->fut_weakreflist != NULL) {
PyObject_ClearWeakRefs(self);
}
(void)FutureObj_clear(fut);
Py_TYPE(fut)->tp_free(fut);
}
/*********************** Future Iterator **************************/
typedef struct {
PyObject_HEAD
FutureObj *future;
} futureiterobject;
static void
FutureIter_dealloc(futureiterobject *it)
{
PyObject_GC_UnTrack(it);
Py_XDECREF(it->future);
PyObject_GC_Del(it);
}
static PyObject *
FutureIter_iternext(futureiterobject *it)
{
PyObject *res;
FutureObj *fut = it->future;
if (fut == NULL) {
return NULL;
}
if (fut->fut_state == STATE_PENDING) {
if (!fut->fut_blocking) {
fut->fut_blocking = 1;
Py_INCREF(fut);
return (PyObject *)fut;
}
PyErr_SetString(PyExc_AssertionError,
"yield from wasn't used with future");
return NULL;
}
it->future = NULL;
res = _asyncio_Future_result_impl(fut);
if (res != NULL) {
/* The result of the Future is not an exception. */
(void)_PyGen_SetStopIterationValue(res);
Py_DECREF(res);
}
Py_DECREF(fut);
return NULL;
}
static PyObject *
FutureIter_send(futureiterobject *self, PyObject *unused)
{
/* Future.__iter__ doesn't care about values that are pushed to the
* generator, it just returns "self.result().
*/
return FutureIter_iternext(self);
}
static PyObject *
FutureIter_throw(futureiterobject *self, PyObject *args)
{
PyObject *type, *val = NULL, *tb = NULL;
if (!PyArg_ParseTuple(args, "O|OO", &type, &val, &tb))
return NULL;
if (val == Py_None) {
val = 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");
return NULL;
}
Py_INCREF(type);
Py_XINCREF(val);
Py_XINCREF(tb);
if (PyExceptionClass_Check(type)) {
PyErr_NormalizeException(&type, &val, &tb);
/* No need to call PyException_SetTraceback since we'll be calling
PyErr_Restore for `type`, `val`, and `tb`. */
} else if (PyExceptionInstance_Check(type)) {
if (val) {
PyErr_SetString(PyExc_TypeError,
"instance exception may not have a separate value");
goto fail;
}
val = type;
type = PyExceptionInstance_Class(type);
Py_INCREF(type);
if (tb == NULL)
tb = PyException_GetTraceback(val);
} else {
PyErr_SetString(PyExc_TypeError,
"exceptions must be classes deriving BaseException or "
"instances of such a class");
goto fail;
}
Py_CLEAR(self->future);
PyErr_Restore(type, val, tb);
return NULL;
fail:
Py_DECREF(type);
Py_XDECREF(val);
Py_XDECREF(tb);
return NULL;
}
static PyObject *
FutureIter_close(futureiterobject *self, PyObject *arg)
{
Py_CLEAR(self->future);
Py_RETURN_NONE;
}
static int
FutureIter_traverse(futureiterobject *it, visitproc visit, void *arg)
{
Py_VISIT(it->future);
return 0;
}
static PyMethodDef FutureIter_methods[] = {
{"send", (PyCFunction)FutureIter_send, METH_O, NULL},
{"throw", (PyCFunction)FutureIter_throw, METH_VARARGS, NULL},
{"close", (PyCFunction)FutureIter_close, METH_NOARGS, NULL},
{NULL, NULL} /* Sentinel */
};
static PyTypeObject FutureIterType = {
PyVarObject_HEAD_INIT(NULL, 0)
"_asyncio.FutureIter",
.tp_basicsize = sizeof(futureiterobject),
.tp_itemsize = 0,
.tp_dealloc = (destructor)FutureIter_dealloc,
.tp_getattro = PyObject_GenericGetAttr,
.tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,
.tp_traverse = (traverseproc)FutureIter_traverse,
.tp_iter = PyObject_SelfIter,
.tp_iternext = (iternextfunc)FutureIter_iternext,
.tp_methods = FutureIter_methods,
};
static PyObject *
future_new_iter(PyObject *fut)
{
futureiterobject *it;
if (!PyObject_TypeCheck(fut, &FutureType)) {
PyErr_BadInternalCall();
return NULL;
}
it = PyObject_GC_New(futureiterobject, &FutureIterType);
if (it == NULL) {
return NULL;
}
Py_INCREF(fut);
it->future = (FutureObj*)fut;
PyObject_GC_Track(it);
return (PyObject*)it;
}
/*********************** Task **************************/
/*[clinic input]
class _asyncio.Task "TaskObj *" "&Task_Type"
[clinic start generated code]*/
/*[clinic end generated code: output=da39a3ee5e6b4b0d input=719dcef0fcc03b37]*/
static int task_call_step_soon(TaskObj *, PyObject *);
static inline PyObject * task_call_wakeup(TaskObj *, PyObject *);
static inline PyObject * task_call_step(TaskObj *, PyObject *);
static PyObject * task_wakeup(TaskObj *, PyObject *);
static PyObject * task_step(TaskObj *, PyObject *);
/* ----- Task._step wrapper */
static int
TaskStepMethWrapper_clear(TaskStepMethWrapper *o)
{
Py_CLEAR(o->sw_task);
Py_CLEAR(o->sw_arg);
return 0;
}
static void
TaskStepMethWrapper_dealloc(TaskStepMethWrapper *o)
{
PyObject_GC_UnTrack(o);
(void)TaskStepMethWrapper_clear(o);
Py_TYPE(o)->tp_free(o);
}
static PyObject *
TaskStepMethWrapper_call(TaskStepMethWrapper *o,
PyObject *args, PyObject *kwds)
{
if (kwds != NULL && PyDict_Size(kwds) != 0) {
PyErr_SetString(PyExc_TypeError, "function takes no keyword arguments");
return NULL;
}
if (args != NULL && PyTuple_GET_SIZE(args) != 0) {
PyErr_SetString(PyExc_TypeError, "function takes no positional arguments");
return NULL;
}
return task_call_step(o->sw_task, o->sw_arg);
}
static int
TaskStepMethWrapper_traverse(TaskStepMethWrapper *o,
visitproc visit, void *arg)
{
Py_VISIT(o->sw_task);
Py_VISIT(o->sw_arg);
return 0;
}
static PyObject *
TaskStepMethWrapper_get___self__(TaskStepMethWrapper *o, void *Py_UNUSED(ignored))
{
if (o->sw_task) {
Py_INCREF(o->sw_task);
return (PyObject*)o->sw_task;
}
Py_RETURN_NONE;
}
static PyGetSetDef TaskStepMethWrapper_getsetlist[] = {
{"__self__", (getter)TaskStepMethWrapper_get___self__, NULL, NULL},
{NULL} /* Sentinel */
};
static PyTypeObject TaskStepMethWrapper_Type = {
PyVarObject_HEAD_INIT(NULL, 0)
"TaskStepMethWrapper",
.tp_basicsize = sizeof(TaskStepMethWrapper),
.tp_itemsize = 0,
.tp_getset = TaskStepMethWrapper_getsetlist,
.tp_dealloc = (destructor)TaskStepMethWrapper_dealloc,
.tp_call = (ternaryfunc)TaskStepMethWrapper_call,
.tp_getattro = PyObject_GenericGetAttr,
.tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,
.tp_traverse = (traverseproc)TaskStepMethWrapper_traverse,
.tp_clear = (inquiry)TaskStepMethWrapper_clear,
};
static PyObject *
TaskStepMethWrapper_new(TaskObj *task, PyObject *arg)
{
TaskStepMethWrapper *o;
o = PyObject_GC_New(TaskStepMethWrapper, &TaskStepMethWrapper_Type);
if (o == NULL) {
return NULL;
}
Py_INCREF(task);
o->sw_task = task;
Py_XINCREF(arg);
o->sw_arg = arg;
PyObject_GC_Track(o);
return (PyObject*) o;
}
/* ----- Task._wakeup wrapper */
static PyObject *
TaskWakeupMethWrapper_call(TaskWakeupMethWrapper *o,
PyObject *args, PyObject *kwds)
{
PyObject *fut;
if (kwds != NULL && PyDict_Size(kwds) != 0) {
PyErr_SetString(PyExc_TypeError, "function takes no keyword arguments");
return NULL;
}
if (!PyArg_ParseTuple(args, "O", &fut)) {
return NULL;
}
return task_call_wakeup(o->ww_task, fut);
}
static int
TaskWakeupMethWrapper_clear(TaskWakeupMethWrapper *o)
{
Py_CLEAR(o->ww_task);
return 0;
}
static int
TaskWakeupMethWrapper_traverse(TaskWakeupMethWrapper *o,
visitproc visit, void *arg)
{
Py_VISIT(o->ww_task);
return 0;
}
static void
TaskWakeupMethWrapper_dealloc(TaskWakeupMethWrapper *o)
{
PyObject_GC_UnTrack(o);
(void)TaskWakeupMethWrapper_clear(o);
Py_TYPE(o)->tp_free(o);
}
static PyTypeObject TaskWakeupMethWrapper_Type = {
PyVarObject_HEAD_INIT(NULL, 0)
"TaskWakeupMethWrapper",
.tp_basicsize = sizeof(TaskWakeupMethWrapper),
.tp_itemsize = 0,
.tp_dealloc = (destructor)TaskWakeupMethWrapper_dealloc,
.tp_call = (ternaryfunc)TaskWakeupMethWrapper_call,
.tp_getattro = PyObject_GenericGetAttr,
.tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,
.tp_traverse = (traverseproc)TaskWakeupMethWrapper_traverse,
.tp_clear = (inquiry)TaskWakeupMethWrapper_clear,
};
static PyObject *
TaskWakeupMethWrapper_new(TaskObj *task)
{
TaskWakeupMethWrapper *o;
o = PyObject_GC_New(TaskWakeupMethWrapper, &TaskWakeupMethWrapper_Type);
if (o == NULL) {
return NULL;
}
Py_INCREF(task);
o->ww_task = task;
PyObject_GC_Track(o);
return (PyObject*) o;
}
/* ----- Task */
/*[clinic input]
_asyncio.Task.__init__
coro: object
*
loop: object = None
A coroutine wrapped in a Future.
[clinic start generated code]*/
static int
_asyncio_Task___init___impl(TaskObj *self, PyObject *coro, PyObject *loop)
/*[clinic end generated code: output=9f24774c2287fc2f input=8d132974b049593e]*/
{
PyObject *res;
_Py_IDENTIFIER(add);
if (future_init((FutureObj*)self, loop)) {
return -1;
}
Py_CLEAR(self->task_fut_waiter);
self->task_must_cancel = 0;
self->task_log_destroy_pending = 1;
Py_INCREF(coro);
Py_XSETREF(self->task_coro, coro);
if (task_call_step_soon(self, NULL)) {
return -1;
}
res = _PyObject_CallMethodIdObjArgs(all_tasks, &PyId_add, self, NULL);
if (res == NULL) {
return -1;
}
Py_DECREF(res);
return 0;
}
static int
TaskObj_clear(TaskObj *task)
{
(void)FutureObj_clear((FutureObj*) task);
Py_CLEAR(task->task_coro);
Py_CLEAR(task->task_fut_waiter);
return 0;
}
static int
TaskObj_traverse(TaskObj *task, visitproc visit, void *arg)
{
Py_VISIT(task->task_coro);
Py_VISIT(task->task_fut_waiter);
(void)FutureObj_traverse((FutureObj*) task, visit, arg);
return 0;
}
static PyObject *
TaskObj_get_log_destroy_pending(TaskObj *task, void *Py_UNUSED(ignored))
{
if (task->task_log_destroy_pending) {
Py_RETURN_TRUE;
}
else {
Py_RETURN_FALSE;
}
}
static int
TaskObj_set_log_destroy_pending(TaskObj *task, PyObject *val, void *Py_UNUSED(ignored))
{
int is_true = PyObject_IsTrue(val);
if (is_true < 0) {
return -1;
}
task->task_log_destroy_pending = is_true;
return 0;
}
static PyObject *
TaskObj_get_must_cancel(TaskObj *task, void *Py_UNUSED(ignored))
{
if (task->task_must_cancel) {
Py_RETURN_TRUE;
}
else {
Py_RETURN_FALSE;
}
}
static PyObject *
TaskObj_get_coro(TaskObj *task, void *Py_UNUSED(ignored))
{
if (task->task_coro) {
Py_INCREF(task->task_coro);
return task->task_coro;
}
Py_RETURN_NONE;
}
static PyObject *
TaskObj_get_fut_waiter(TaskObj *task, void *Py_UNUSED(ignored))
{
if (task->task_fut_waiter) {
Py_INCREF(task->task_fut_waiter);
return task->task_fut_waiter;
}
Py_RETURN_NONE;
}
/*[clinic input]
@classmethod
_asyncio.Task.current_task
loop: object = None
Return the currently running task in an event loop or None.
By default the current task for the current event loop is returned.
None is returned when called not in the context of a Task.
[clinic start generated code]*/
static PyObject *
_asyncio_Task_current_task_impl(PyTypeObject *type, PyObject *loop)
/*[clinic end generated code: output=99fbe7332c516e03 input=cd14770c5b79c7eb]*/
{
PyObject *res;
if (loop == Py_None) {
loop = _PyObject_CallNoArg(asyncio_get_event_loop);
if (loop == NULL) {
return NULL;
}
res = PyDict_GetItem(current_tasks, loop);
Py_DECREF(loop);
}
else {
res = PyDict_GetItem(current_tasks, loop);
}
if (res == NULL) {
Py_RETURN_NONE;
}
else {
Py_INCREF(res);
return res;
}
}
static PyObject *
task_all_tasks(PyObject *loop)
{
PyObject *task;
PyObject *task_loop;
PyObject *set;
PyObject *iter;
assert(loop != NULL);
set = PySet_New(NULL);
if (set == NULL) {
return NULL;
}
iter = PyObject_GetIter(all_tasks);
if (iter == NULL) {
goto fail;
}
while ((task = PyIter_Next(iter))) {
task_loop = PyObject_GetAttrString(task, "_loop");
if (task_loop == NULL) {
Py_DECREF(task);
goto fail;
}
if (task_loop == loop) {
if (PySet_Add(set, task) == -1) {
Py_DECREF(task_loop);
Py_DECREF(task);
goto fail;
}
}
Py_DECREF(task_loop);
Py_DECREF(task);
}
if (PyErr_Occurred()) {
goto fail;
}
Py_DECREF(iter);
return set;
fail:
Py_DECREF(set);
Py_XDECREF(iter);
return NULL;
}
/*[clinic input]
@classmethod
_asyncio.Task.all_tasks
loop: object = None
Return a set of all tasks for an event loop.
By default all tasks for the current event loop are returned.
[clinic start generated code]*/
static PyObject *
_asyncio_Task_all_tasks_impl(PyTypeObject *type, PyObject *loop)
/*[clinic end generated code: output=11f9b20749ccca5d input=497f80bc9ce726b5]*/
{
PyObject *res;
if (loop == Py_None) {
loop = _PyObject_CallNoArg(asyncio_get_event_loop);
if (loop == NULL) {
return NULL;
}
res = task_all_tasks(loop);
Py_DECREF(loop);
}
else {
res = task_all_tasks(loop);
}
return res;
}
/*[clinic input]
_asyncio.Task._repr_info
[clinic start generated code]*/
static PyObject *
_asyncio_Task__repr_info_impl(TaskObj *self)
/*[clinic end generated code: output=6a490eb66d5ba34b input=3c6d051ed3ddec8b]*/
{
return PyObject_CallFunctionObjArgs(
asyncio_task_repr_info_func, self, NULL);
}
/*[clinic input]
_asyncio.Task.cancel
Request that this task cancel itself.
This arranges for a CancelledError to be thrown into the
wrapped coroutine on the next cycle through the event loop.
The coroutine then has a chance to clean up or even deny
the request using try/except/finally.
Unlike Future.cancel, this does not guarantee that the
task will be cancelled: the exception might be caught and
acted upon, delaying cancellation of the task or preventing
cancellation completely. The task may also return a value or
raise a different exception.
Immediately after this method is called, Task.cancelled() will
not return True (unless the task was already cancelled). A
task will be marked as cancelled when the wrapped coroutine
terminates with a CancelledError exception (even if cancel()
was not called).
[clinic start generated code]*/
static PyObject *
_asyncio_Task_cancel_impl(TaskObj *self)
/*[clinic end generated code: output=6bfc0479da9d5757 input=13f9bf496695cb52]*/
{
self->task_log_tb = 0;
if (self->task_state != STATE_PENDING) {
Py_RETURN_FALSE;
}
if (self->task_fut_waiter) {
PyObject *res;
int is_true;
res = _PyObject_CallMethodId(
self->task_fut_waiter, &PyId_cancel, NULL);
if (res == NULL) {
return NULL;
}
is_true = PyObject_IsTrue(res);
Py_DECREF(res);
if (is_true < 0) {
return NULL;
}
if (is_true) {
Py_RETURN_TRUE;
}
}
self->task_must_cancel = 1;
Py_RETURN_TRUE;
}
/*[clinic input]
_asyncio.Task.get_stack
*
limit: object = None
Return the list of stack frames for this task's coroutine.
If the coroutine is not done, this returns the stack where it is
suspended. If the coroutine has completed successfully or was
cancelled, this returns an empty list. If the coroutine was
terminated by an exception, this returns the list of traceback
frames.
The frames are always ordered from oldest to newest.
The optional limit gives the maximum number of frames to
return; by default all available frames are returned. Its
meaning differs depending on whether a stack or a traceback is
returned: the newest frames of a stack are returned, but the
oldest frames of a traceback are returned. (This matches the
behavior of the traceback module.)
For reasons beyond our control, only one stack frame is
returned for a suspended coroutine.
[clinic start generated code]*/
static PyObject *
_asyncio_Task_get_stack_impl(TaskObj *self, PyObject *limit)
/*[clinic end generated code: output=c9aeeeebd1e18118 input=05b323d42b809b90]*/
{
return PyObject_CallFunctionObjArgs(
asyncio_task_get_stack_func, self, limit, NULL);
}
/*[clinic input]
_asyncio.Task.print_stack
*
limit: object = None
file: object = None
Print the stack or traceback for this task's coroutine.
This produces output similar to that of the traceback module,
for the frames retrieved by get_stack(). The limit argument
is passed to get_stack(). The file argument is an I/O stream
to which the output is written; by default output is written
to sys.stderr.
[clinic start generated code]*/
static PyObject *
_asyncio_Task_print_stack_impl(TaskObj *self, PyObject *limit,
PyObject *file)
/*[clinic end generated code: output=7339e10314cd3f4d input=1a0352913b7fcd92]*/
{
return PyObject_CallFunctionObjArgs(
asyncio_task_print_stack_func, self, limit, file, NULL);
}
/*[clinic input]
_asyncio.Task._step
exc: object = None
[clinic start generated code]*/
static PyObject *
_asyncio_Task__step_impl(TaskObj *self, PyObject *exc)
/*[clinic end generated code: output=7ed23f0cefd5ae42 input=1e19a985ace87ca4]*/
{
return task_step(self, exc == Py_None ? NULL : exc);
}
/*[clinic input]
_asyncio.Task._wakeup
fut: object
[clinic start generated code]*/
static PyObject *
_asyncio_Task__wakeup_impl(TaskObj *self, PyObject *fut)
/*[clinic end generated code: output=75cb341c760fd071 input=6a0616406f829a7b]*/
{
return task_wakeup(self, fut);
}
static void
TaskObj_finalize(TaskObj *task)
{
_Py_IDENTIFIER(call_exception_handler);
_Py_IDENTIFIER(task);
_Py_IDENTIFIER(message);
_Py_IDENTIFIER(source_traceback);
PyObject *context;
PyObject *message = NULL;
PyObject *func;
PyObject *error_type, *error_value, *error_traceback;
if (task->task_state != STATE_PENDING || !task->task_log_destroy_pending) {
goto done;
}
/* Save the current exception, if any. */
PyErr_Fetch(&error_type, &error_value, &error_traceback);
context = PyDict_New();
if (context == NULL) {
goto finally;
}
message = PyUnicode_FromString("Task was destroyed but it is pending!");
if (message == NULL) {
goto finally;
}
if (_PyDict_SetItemId(context, &PyId_message, message) < 0 ||
_PyDict_SetItemId(context, &PyId_task, (PyObject*)task) < 0)
{
goto finally;
}
if (task->task_source_tb != NULL) {
if (_PyDict_SetItemId(context, &PyId_source_traceback,
task->task_source_tb) < 0)
{
goto finally;
}
}
func = _PyObject_GetAttrId(task->task_loop, &PyId_call_exception_handler);
if (func != NULL) {
PyObject *res = _PyObject_CallArg1(func, context);
if (res == NULL) {
PyErr_WriteUnraisable(func);
}
else {
Py_DECREF(res);
}
Py_DECREF(func);
}
finally:
Py_XDECREF(context);
Py_XDECREF(message);
/* Restore the saved exception. */
PyErr_Restore(error_type, error_value, error_traceback);
done:
FutureObj_finalize((FutureObj*)task);
}
static void TaskObj_dealloc(PyObject *); /* Needs Task_CheckExact */
static PyMethodDef TaskType_methods[] = {
_ASYNCIO_FUTURE_RESULT_METHODDEF
_ASYNCIO_FUTURE_EXCEPTION_METHODDEF
_ASYNCIO_FUTURE_SET_RESULT_METHODDEF
_ASYNCIO_FUTURE_SET_EXCEPTION_METHODDEF
_ASYNCIO_FUTURE_ADD_DONE_CALLBACK_METHODDEF
_ASYNCIO_FUTURE_REMOVE_DONE_CALLBACK_METHODDEF
_ASYNCIO_FUTURE_CANCELLED_METHODDEF
_ASYNCIO_FUTURE_DONE_METHODDEF
_ASYNCIO_TASK_CURRENT_TASK_METHODDEF
_ASYNCIO_TASK_ALL_TASKS_METHODDEF
_ASYNCIO_TASK_CANCEL_METHODDEF
_ASYNCIO_TASK_GET_STACK_METHODDEF
_ASYNCIO_TASK_PRINT_STACK_METHODDEF
_ASYNCIO_TASK__WAKEUP_METHODDEF
_ASYNCIO_TASK__STEP_METHODDEF
_ASYNCIO_TASK__REPR_INFO_METHODDEF
{NULL, NULL} /* Sentinel */
};
static PyGetSetDef TaskType_getsetlist[] = {
FUTURE_COMMON_GETSETLIST
{"_log_destroy_pending", (getter)TaskObj_get_log_destroy_pending,
(setter)TaskObj_set_log_destroy_pending, NULL},
{"_must_cancel", (getter)TaskObj_get_must_cancel, NULL, NULL},
{"_coro", (getter)TaskObj_get_coro, NULL, NULL},
{"_fut_waiter", (getter)TaskObj_get_fut_waiter, NULL, NULL},
{NULL} /* Sentinel */
};
static PyTypeObject TaskType = {
PyVarObject_HEAD_INIT(NULL, 0)
"_asyncio.Task",
sizeof(TaskObj), /* tp_basicsize */
.tp_base = &FutureType,
.tp_dealloc = TaskObj_dealloc,
.tp_as_async = &FutureType_as_async,
.tp_repr = (reprfunc)FutureObj_repr,
.tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC | Py_TPFLAGS_BASETYPE
| Py_TPFLAGS_HAVE_FINALIZE,
.tp_doc = _asyncio_Task___init____doc__,
.tp_traverse = (traverseproc)TaskObj_traverse,
.tp_clear = (inquiry)TaskObj_clear,
.tp_weaklistoffset = offsetof(TaskObj, task_weakreflist),
.tp_iter = (getiterfunc)future_new_iter,
.tp_methods = TaskType_methods,
.tp_getset = TaskType_getsetlist,
.tp_dictoffset = offsetof(TaskObj, dict),
.tp_init = (initproc)_asyncio_Task___init__,
.tp_new = PyType_GenericNew,
.tp_finalize = (destructor)TaskObj_finalize,
};
#define Task_CheckExact(obj) (Py_TYPE(obj) == &TaskType)
static void
TaskObj_dealloc(PyObject *self)
{
TaskObj *task = (TaskObj *)self;
if (Task_CheckExact(self)) {
/* When fut is subclass of Task, finalizer is called from
* subtype_dealloc.
*/
if (PyObject_CallFinalizerFromDealloc(self) < 0) {
// resurrected.
return;
}
}
PyObject_GC_UnTrack(self);
if (task->task_weakreflist != NULL) {
PyObject_ClearWeakRefs(self);
}
(void)TaskObj_clear(task);
Py_TYPE(task)->tp_free(task);
}
static inline PyObject *
task_call_wakeup(TaskObj *task, PyObject *fut)
{
if (Task_CheckExact(task)) {
return task_wakeup(task, fut);
}
else {
/* `task` is a subclass of Task */
return _PyObject_CallMethodIdObjArgs((PyObject*)task, &PyId__wakeup,
fut, NULL);
}
}
static inline PyObject *
task_call_step(TaskObj *task, PyObject *arg)
{
if (Task_CheckExact(task)) {
return task_step(task, arg);
}
else {
/* `task` is a subclass of Task */
return _PyObject_CallMethodIdObjArgs((PyObject*)task, &PyId__step,
arg, NULL);
}
}
static int
task_call_step_soon(TaskObj *task, PyObject *arg)
{
PyObject *handle;
PyObject *cb = TaskStepMethWrapper_new(task, arg);
if (cb == NULL) {
return -1;
}
handle = _PyObject_CallMethodIdObjArgs(task->task_loop, &PyId_call_soon,
cb, NULL);
Py_DECREF(cb);
if (handle == NULL) {
return -1;
}
Py_DECREF(handle);
return 0;
}
static PyObject *
task_set_error_soon(TaskObj *task, PyObject *et, const char *format, ...)
{
PyObject* msg;
va_list vargs;
#ifdef HAVE_STDARG_PROTOTYPES
va_start(vargs, format);
#else
va_start(vargs);
#endif
msg = PyUnicode_FromFormatV(format, vargs);
va_end(vargs);
if (msg == NULL) {
return NULL;
}
PyObject *e = PyObject_CallFunctionObjArgs(et, msg, NULL);
Py_DECREF(msg);
if (e == NULL) {
return NULL;
}
if (task_call_step_soon(task, e) == -1) {
Py_DECREF(e);
return NULL;
}
Py_DECREF(e);
Py_RETURN_NONE;
}
static PyObject *
task_step_impl(TaskObj *task, PyObject *exc)
{
int res;
int clear_exc = 0;
PyObject *result = NULL;
PyObject *coro;
PyObject *o;
if (task->task_state != STATE_PENDING) {
PyErr_Format(PyExc_AssertionError,
"_step(): already done: %R %R",
task,
exc ? exc : Py_None);
goto fail;
}
if (task->task_must_cancel) {
assert(exc != Py_None);
if (exc) {
/* Check if exc is a CancelledError */
res = PyObject_IsInstance(exc, asyncio_CancelledError);
if (res == -1) {
/* An error occurred, abort */
goto fail;
}
if (res == 0) {
/* exc is not CancelledError; reset it to NULL */
exc = NULL;
}
}
if (!exc) {
/* exc was not a CancelledError */
exc = PyObject_CallFunctionObjArgs(asyncio_CancelledError, NULL);
if (!exc) {
goto fail;
}
clear_exc = 1;
}
task->task_must_cancel = 0;
}
Py_CLEAR(task->task_fut_waiter);
coro = task->task_coro;
if (coro == NULL) {
PyErr_SetString(PyExc_RuntimeError, "uninitialized Task object");
return NULL;
}
if (exc == NULL) {
if (PyGen_CheckExact(coro) || PyCoro_CheckExact(coro)) {
result = _PyGen_Send((PyGenObject*)coro, Py_None);
}
else {
result = _PyObject_CallMethodIdObjArgs(
coro, &PyId_send, Py_None, NULL);
}
}
else {
result = _PyObject_CallMethodIdObjArgs(
coro, &PyId_throw, exc, NULL);
if (clear_exc) {
/* We created 'exc' during this call */
Py_DECREF(exc);
}
}
if (result == NULL) {
PyObject *et, *ev, *tb;
if (_PyGen_FetchStopIterationValue(&o) == 0) {
/* The error is StopIteration and that means that
the underlying coroutine has resolved */
if (task->task_must_cancel) {
// Task is cancelled right before coro stops.
Py_DECREF(o);
task->task_must_cancel = 0;
et = asyncio_CancelledError;
Py_INCREF(et);
ev = NULL;
tb = NULL;
goto set_exception;
}
PyObject *res = future_set_result((FutureObj*)task, o);
Py_DECREF(o);
if (res == NULL) {
return NULL;
}
Py_DECREF(res);
Py_RETURN_NONE;
}
if (PyErr_ExceptionMatches(asyncio_CancelledError)) {
/* CancelledError */
PyErr_Clear();
return future_cancel((FutureObj*)task);
}
/* Some other exception; pop it and call Task.set_exception() */
PyErr_Fetch(&et, &ev, &tb);
set_exception:
assert(et);
if (!ev || !PyObject_TypeCheck(ev, (PyTypeObject *) et)) {
PyErr_NormalizeException(&et, &ev, &tb);
}
if (tb != NULL) {
PyException_SetTraceback(ev, tb);
}
o = future_set_exception((FutureObj*)task, ev);
if (!o) {
/* An exception in Task.set_exception() */
Py_DECREF(et);
Py_XDECREF(tb);
Py_XDECREF(ev);
goto fail;
}
assert(o == Py_None);
Py_DECREF(o);
if (!PyErr_GivenExceptionMatches(et, PyExc_Exception)) {
/* We've got a BaseException; re-raise it */
PyErr_Restore(et, ev, tb);
goto fail;
}
Py_DECREF(et);
Py_XDECREF(tb);
Py_XDECREF(ev);
Py_RETURN_NONE;
}
if (result == (PyObject*)task) {
/* We have a task that wants to await on itself */
goto self_await;
}
/* Check if `result` is FutureObj or TaskObj (and not a subclass) */
if (Future_CheckExact(result) || Task_CheckExact(result)) {
PyObject *wrapper;
PyObject *res;
FutureObj *fut = (FutureObj*)result;
/* Check if `result` future is attached to a different loop */
if (fut->fut_loop != task->task_loop) {
goto different_loop;
}
if (fut->fut_blocking) {
fut->fut_blocking = 0;
/* result.add_done_callback(task._wakeup) */
wrapper = TaskWakeupMethWrapper_new(task);
if (wrapper == NULL) {
goto fail;
}
res = future_add_done_callback((FutureObj*)result, wrapper);
Py_DECREF(wrapper);
if (res == NULL) {
goto fail;
}
Py_DECREF(res);
/* task._fut_waiter = result */
task->task_fut_waiter = result; /* no incref is necessary */
if (task->task_must_cancel) {
PyObject *r;
int is_true;
r = _PyObject_CallMethodId(result, &PyId_cancel, NULL);
if (r == NULL) {
return NULL;
}
is_true = PyObject_IsTrue(r);
Py_DECREF(r);
if (is_true < 0) {
return NULL;
}
else if (is_true) {
task->task_must_cancel = 0;
}
}
Py_RETURN_NONE;
}
else {
goto yield_insteadof_yf;
}
}
/* Check if `result` is a Future-compatible object */
o = PyObject_GetAttrString(result, "_asyncio_future_blocking");
if (o == NULL) {
if (PyErr_ExceptionMatches(PyExc_AttributeError)) {
PyErr_Clear();
}
else {
goto fail;
}
}
else {
if (o == Py_None) {
Py_DECREF(o);
}
else {
/* `result` is a Future-compatible object */
PyObject *wrapper;
PyObject *res;
int blocking = PyObject_IsTrue(o);
Py_DECREF(o);
if (blocking < 0) {
goto fail;
}
/* Check if `result` future is attached to a different loop */
PyObject *oloop = PyObject_GetAttrString(result, "_loop");
if (oloop == NULL) {
goto fail;
}
if (oloop != task->task_loop) {
Py_DECREF(oloop);
goto different_loop;
}
else {
Py_DECREF(oloop);
}
if (blocking) {
/* result._asyncio_future_blocking = False */
if (PyObject_SetAttrString(
result, "_asyncio_future_blocking", Py_False) == -1) {
goto fail;
}
/* result.add_done_callback(task._wakeup) */
wrapper = TaskWakeupMethWrapper_new(task);
if (wrapper == NULL) {
goto fail;
}
res = _PyObject_CallMethodIdObjArgs(result,
&PyId_add_done_callback,
wrapper, NULL);
Py_DECREF(wrapper);
if (res == NULL) {
goto fail;
}
Py_DECREF(res);
/* task._fut_waiter = result */
task->task_fut_waiter = result; /* no incref is necessary */
if (task->task_must_cancel) {
PyObject *r;
int is_true;
r = _PyObject_CallMethodId(result, &PyId_cancel, NULL);
if (r == NULL) {
return NULL;
}
is_true = PyObject_IsTrue(r);
Py_DECREF(r);
if (is_true < 0) {
return NULL;
}
else if (is_true) {
task->task_must_cancel = 0;
}
}
Py_RETURN_NONE;
}
else {
goto yield_insteadof_yf;
}
}
}
/* Check if `result` is None */
if (result == Py_None) {
/* Bare yield relinquishes control for one event loop iteration. */
if (task_call_step_soon(task, NULL)) {
goto fail;
}
return result;
}
/* Check if `result` is a generator */
o = PyObject_CallFunctionObjArgs(inspect_isgenerator, result, NULL);
if (o == NULL) {
/* An exception in inspect.isgenerator */
goto fail;
}
res = PyObject_IsTrue(o);
Py_DECREF(o);
if (res == -1) {
/* An exception while checking if 'val' is True */
goto fail;
}
if (res == 1) {
/* `result` is a generator */
o = task_set_error_soon(
task, PyExc_RuntimeError,
"yield was used instead of yield from for "
"generator in task %R with %R", task, result);
Py_DECREF(result);
return o;
}
/* The `result` is none of the above */
o = task_set_error_soon(
task, PyExc_RuntimeError, "Task got bad yield: %R", result);
Py_DECREF(result);
return o;
self_await:
o = task_set_error_soon(
task, PyExc_RuntimeError,
"Task cannot await on itself: %R", task);
Py_DECREF(result);
return o;
yield_insteadof_yf:
o = task_set_error_soon(
task, PyExc_RuntimeError,
"yield was used instead of yield from "
"in task %R with %R",
task, result);
Py_DECREF(result);
return o;
different_loop:
o = task_set_error_soon(
task, PyExc_RuntimeError,
"Task %R got Future %R attached to a different loop",
task, result);
Py_DECREF(result);
return o;
fail:
Py_XDECREF(result);
return NULL;
}
static PyObject *
task_step(TaskObj *task, PyObject *exc)
{
PyObject *res;
PyObject *ot;
if (PyDict_SetItem(current_tasks,
task->task_loop, (PyObject*)task) == -1)
{
return NULL;
}
res = task_step_impl(task, exc);
if (res == NULL) {
PyObject *et, *ev, *tb;
PyErr_Fetch(&et, &ev, &tb);
ot = _PyDict_Pop(current_tasks, task->task_loop, NULL);
Py_XDECREF(ot);
_PyErr_ChainExceptions(et, ev, tb);
return NULL;
}
else {
ot = _PyDict_Pop(current_tasks, task->task_loop, NULL);
if (ot == NULL) {
Py_DECREF(res);
return NULL;
}
else {
Py_DECREF(ot);
return res;
}
}
}
static PyObject *
task_wakeup(TaskObj *task, PyObject *o)
{
PyObject *et, *ev, *tb;
PyObject *result;
assert(o);
if (Future_CheckExact(o) || Task_CheckExact(o)) {
PyObject *fut_result = NULL;
int res = future_get_result((FutureObj*)o, &fut_result);
switch(res) {
case -1:
assert(fut_result == NULL);
break; /* exception raised */
case 0:
Py_DECREF(fut_result);
return task_call_step(task, NULL);
default:
assert(res == 1);
result = task_call_step(task, fut_result);
Py_DECREF(fut_result);
return result;
}
}
else {
PyObject *fut_result = PyObject_CallMethod(o, "result", NULL);
if (fut_result != NULL) {
Py_DECREF(fut_result);
return task_call_step(task, NULL);
}
/* exception raised */
}
PyErr_Fetch(&et, &ev, &tb);
if (!PyErr_GivenExceptionMatches(et, PyExc_Exception)) {
/* We've got a BaseException; re-raise it */
PyErr_Restore(et, ev, tb);
return NULL;
}
if (!ev || !PyObject_TypeCheck(ev, (PyTypeObject *) et)) {
PyErr_NormalizeException(&et, &ev, &tb);
}
result = task_call_step(task, ev);
Py_DECREF(et);
Py_XDECREF(tb);
Py_XDECREF(ev);
return result;
}
/*********************** Module **************************/
static void
module_free(void *m)
{
Py_CLEAR(current_tasks);
Py_CLEAR(all_tasks);
Py_CLEAR(traceback_extract_stack);
Py_CLEAR(asyncio_get_event_loop);
Py_CLEAR(asyncio_future_repr_info_func);
Py_CLEAR(asyncio_task_repr_info_func);
Py_CLEAR(asyncio_task_get_stack_func);
Py_CLEAR(asyncio_task_print_stack_func);
Py_CLEAR(asyncio_InvalidStateError);
Py_CLEAR(asyncio_CancelledError);
Py_CLEAR(inspect_isgenerator);
}
static int
module_init(void)
{
PyObject *module = NULL;
PyObject *cls;
#define WITH_MOD(NAME) \
Py_CLEAR(module); \
module = PyImport_ImportModule(NAME); \
if (module == NULL) { \
goto fail; \
}
#define GET_MOD_ATTR(VAR, NAME) \
VAR = PyObject_GetAttrString(module, NAME); \
if (VAR == NULL) { \
goto fail; \
}
WITH_MOD("asyncio.events")
GET_MOD_ATTR(asyncio_get_event_loop, "get_event_loop")
WITH_MOD("asyncio.base_futures")
GET_MOD_ATTR(asyncio_future_repr_info_func, "_future_repr_info")
GET_MOD_ATTR(asyncio_InvalidStateError, "InvalidStateError")
GET_MOD_ATTR(asyncio_CancelledError, "CancelledError")
WITH_MOD("asyncio.base_tasks")
GET_MOD_ATTR(asyncio_task_repr_info_func, "_task_repr_info")
GET_MOD_ATTR(asyncio_task_get_stack_func, "_task_get_stack")
GET_MOD_ATTR(asyncio_task_print_stack_func, "_task_print_stack")
WITH_MOD("inspect")
GET_MOD_ATTR(inspect_isgenerator, "isgenerator")
WITH_MOD("traceback")
GET_MOD_ATTR(traceback_extract_stack, "extract_stack")
WITH_MOD("weakref")
GET_MOD_ATTR(cls, "WeakSet")
all_tasks = _PyObject_CallNoArg(cls);
Py_DECREF(cls);
if (all_tasks == NULL) {
goto fail;
}
current_tasks = PyDict_New();
if (current_tasks == NULL) {
goto fail;
}
Py_DECREF(module);
return 0;
fail:
Py_CLEAR(module);
module_free(NULL);
return -1;
#undef WITH_MOD
#undef GET_MOD_ATTR
}
PyDoc_STRVAR(module_doc, "Accelerator module for asyncio");
static struct PyModuleDef _asynciomodule = {
PyModuleDef_HEAD_INIT, /* m_base */
"_asyncio", /* m_name */
module_doc, /* m_doc */
-1, /* m_size */
NULL, /* m_methods */
NULL, /* m_slots */
NULL, /* m_traverse */
NULL, /* m_clear */
(freefunc)module_free /* m_free */
};
PyMODINIT_FUNC
PyInit__asyncio(void)
{
if (module_init() < 0) {
return NULL;
}
if (PyType_Ready(&FutureType) < 0) {
return NULL;
}
if (PyType_Ready(&FutureIterType) < 0) {
return NULL;
}
if (PyType_Ready(&TaskStepMethWrapper_Type) < 0) {
return NULL;
}
if(PyType_Ready(&TaskWakeupMethWrapper_Type) < 0) {
return NULL;
}
if (PyType_Ready(&TaskType) < 0) {
return NULL;
}
PyObject *m = PyModule_Create(&_asynciomodule);
if (m == NULL) {
return NULL;
}
Py_INCREF(&FutureType);
if (PyModule_AddObject(m, "Future", (PyObject *)&FutureType) < 0) {
Py_DECREF(&FutureType);
return NULL;
}
Py_INCREF(&TaskType);
if (PyModule_AddObject(m, "Task", (PyObject *)&TaskType) < 0) {
Py_DECREF(&TaskType);
return NULL;
}
return m;
}
| 67,151 | 2,551 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Modules/resource.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:8;coding:utf-8 -*-â
âvi: set net ft=c ts=4 sts=4 sw=4 fenc=utf-8 :viâ
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ¡
â Python 3 â
â https://docs.python.org/3/license.html â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
#include "libc/calls/calls.h"
#include "libc/calls/struct/rlimit.h"
#include "libc/calls/struct/rusage.h"
#include "libc/calls/weirdtypes.h"
#include "libc/errno.h"
#include "libc/runtime/runtime.h"
#include "libc/sysv/consts/rlim.h"
#include "libc/sysv/consts/rlimit.h"
#include "libc/sysv/consts/rusage.h"
#include "third_party/python/Include/abstract.h"
#include "third_party/python/Include/floatobject.h"
#include "third_party/python/Include/import.h"
#include "third_party/python/Include/longobject.h"
#include "third_party/python/Include/modsupport.h"
#include "third_party/python/Include/pyerrors.h"
#include "third_party/python/Include/pymacro.h"
#include "third_party/python/Include/structseq.h"
#include "third_party/python/Include/yoink.h"
#include "third_party/python/pyconfig.h"
/* clang-format off */
PYTHON_PROVIDE("resource");
PYTHON_PROVIDE("resource.RLIMIT_AS");
PYTHON_PROVIDE("resource.RLIMIT_CORE");
PYTHON_PROVIDE("resource.RLIMIT_CPU");
PYTHON_PROVIDE("resource.RLIMIT_DATA");
PYTHON_PROVIDE("resource.RLIMIT_FSIZE");
PYTHON_PROVIDE("resource.RLIMIT_MEMLOCK");
PYTHON_PROVIDE("resource.RLIMIT_MSGQUEUE");
PYTHON_PROVIDE("resource.RLIMIT_NICE");
PYTHON_PROVIDE("resource.RLIMIT_NOFILE");
PYTHON_PROVIDE("resource.RLIMIT_NPROC");
PYTHON_PROVIDE("resource.RLIMIT_RSS");
PYTHON_PROVIDE("resource.RLIMIT_RTPRIO");
PYTHON_PROVIDE("resource.RLIMIT_RTTIME");
PYTHON_PROVIDE("resource.RLIMIT_SIGPENDING");
PYTHON_PROVIDE("resource.RLIMIT_STACK");
PYTHON_PROVIDE("resource.RLIMIT_VMEM");
PYTHON_PROVIDE("resource.RLIM_INFINITY");
PYTHON_PROVIDE("resource.RUSAGE_BOTH");
PYTHON_PROVIDE("resource.RUSAGE_CHILDREN");
PYTHON_PROVIDE("resource.RUSAGE_SELF");
PYTHON_PROVIDE("resource.RUSAGE_THREAD");
PYTHON_PROVIDE("resource.error");
PYTHON_PROVIDE("resource.getpagesize");
PYTHON_PROVIDE("resource.getrlimit");
PYTHON_PROVIDE("resource.getrusage");
PYTHON_PROVIDE("resource.setrlimit");
PYTHON_PROVIDE("resource.struct_rusage");
/* On some systems, these aren't in any header file.
On others they are, with inconsistent prototypes.
We declare the (default) return type, to shut up gcc -Wall;
but we can't declare the prototype, to avoid errors
when the header files declare it different.
Worse, on some Linuxes, getpagesize() returns a size_t... */
#define doubletime(TV) ((double)(TV).tv_sec + (TV).tv_usec * 0.000001)
PyDoc_STRVAR(struct_rusage__doc__,
"struct_rusage: Result from getrusage.\n\n"
"This object may be accessed either as a tuple of\n"
" (utime,stime,maxrss,ixrss,idrss,isrss,minflt,majflt,\n"
" nswap,inblock,oublock,msgsnd,msgrcv,nsignals,nvcsw,nivcsw)\n"
"or via the attributes ru_utime, ru_stime, ru_maxrss, and so on.");
static PyStructSequence_Field struct_rusage_fields[] = {
{"ru_utime", PyDoc_STR("user time used")},
{"ru_stime", PyDoc_STR("system time used")},
{"ru_maxrss", PyDoc_STR("max. resident set size")},
{"ru_ixrss", PyDoc_STR("shared memory size")},
{"ru_idrss", PyDoc_STR("unshared data size")},
{"ru_isrss", PyDoc_STR("unshared stack size")},
{"ru_minflt", PyDoc_STR("page faults not requiring I/O")},
{"ru_majflt", PyDoc_STR("page faults requiring I/O")},
{"ru_nswap", PyDoc_STR("number of swap outs")},
{"ru_inblock", PyDoc_STR("block input operations")},
{"ru_oublock", PyDoc_STR("block output operations")},
{"ru_msgsnd", PyDoc_STR("IPC messages sent")},
{"ru_msgrcv", PyDoc_STR("IPC messages received")},
{"ru_nsignals", PyDoc_STR("signals received")},
{"ru_nvcsw", PyDoc_STR("voluntary context switches")},
{"ru_nivcsw", PyDoc_STR("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 */
};
static int initialized;
static PyTypeObject StructRUsageType;
static PyObject *
resource_getrusage(PyObject *self, PyObject *args)
{
int who;
struct rusage ru;
PyObject *r;
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(PyExc_OSError);
return NULL;
}
r = PyStructSequence_New(&StructRUsageType);
if (!r)
return NULL;
PyStructSequence_SET_ITEM(r, 0, PyFloat_FromDouble(doubletime(ru.ru_utime)));
PyStructSequence_SET_ITEM(r, 1, PyFloat_FromDouble(doubletime(ru.ru_stime)));
PyStructSequence_SET_ITEM(r, 2, PyLong_FromLong(ru.ru_maxrss));
PyStructSequence_SET_ITEM(r, 3, PyLong_FromLong(ru.ru_ixrss));
PyStructSequence_SET_ITEM(r, 4, PyLong_FromLong(ru.ru_idrss));
PyStructSequence_SET_ITEM(r, 5, PyLong_FromLong(ru.ru_isrss));
PyStructSequence_SET_ITEM(r, 6, PyLong_FromLong(ru.ru_minflt));
PyStructSequence_SET_ITEM(r, 7, PyLong_FromLong(ru.ru_majflt));
PyStructSequence_SET_ITEM(r, 8, PyLong_FromLong(ru.ru_nswap));
PyStructSequence_SET_ITEM(r, 9, PyLong_FromLong(ru.ru_inblock));
PyStructSequence_SET_ITEM(r, 10, PyLong_FromLong(ru.ru_oublock));
PyStructSequence_SET_ITEM(r, 11, PyLong_FromLong(ru.ru_msgsnd));
PyStructSequence_SET_ITEM(r, 12, PyLong_FromLong(ru.ru_msgrcv));
PyStructSequence_SET_ITEM(r, 13, PyLong_FromLong(ru.ru_nsignals));
PyStructSequence_SET_ITEM(r, 14, PyLong_FromLong(ru.ru_nvcsw));
PyStructSequence_SET_ITEM(r, 15, PyLong_FromLong(ru.ru_nivcsw));
if (PyErr_Occurred()) {
Py_DECREF(r);
return NULL;
}
return r;
}
static int
py2rlimit(PyObject *limits, struct rlimit *rl_out)
{
PyObject *curobj, *maxobj;
limits = PySequence_Tuple(limits);
if (!limits)
/* Here limits is a borrowed reference */
return -1;
if (PyTuple_GET_SIZE(limits) != 2) {
PyErr_SetString(PyExc_ValueError,
"expected a tuple of 2 integers");
goto error;
}
curobj = PyTuple_GET_ITEM(limits, 0);
maxobj = PyTuple_GET_ITEM(limits, 1);
#if !defined(HAVE_LARGEFILE_SUPPORT)
rl_out->rlim_cur = PyLong_AsLong(curobj);
if (rl_out->rlim_cur == (rlim_t)-1 && PyErr_Occurred())
goto error;
rl_out->rlim_max = PyLong_AsLong(maxobj);
if (rl_out->rlim_max == (rlim_t)-1 && PyErr_Occurred())
goto error;
#else
/* The limits are probably bigger than a long */
rl_out->rlim_cur = PyLong_AsLongLong(curobj);
if (rl_out->rlim_cur == (rlim_t)-1 && PyErr_Occurred())
goto error;
rl_out->rlim_max = PyLong_AsLongLong(maxobj);
if (rl_out->rlim_max == (rlim_t)-1 && PyErr_Occurred())
goto error;
#endif
Py_DECREF(limits);
rl_out->rlim_cur = rl_out->rlim_cur & RLIM_INFINITY;
rl_out->rlim_max = rl_out->rlim_max & RLIM_INFINITY;
return 0;
error:
Py_DECREF(limits);
return -1;
}
static PyObject*
rlimit2py(struct rlimit rl)
{
if (sizeof(rl.rlim_cur) > sizeof(long)) {
return Py_BuildValue("LL",
(long long) rl.rlim_cur,
(long long) rl.rlim_max);
}
return Py_BuildValue("ll", (long) rl.rlim_cur, (long) rl.rlim_max);
}
static PyObject *
resource_getrlimit(PyObject *self, PyObject *args)
{
struct rlimit rl;
int resource;
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 (getrlimit(resource, &rl) == -1) {
PyErr_SetFromErrno(PyExc_OSError);
return NULL;
}
return rlimit2py(rl);
}
static PyObject *
resource_setrlimit(PyObject *self, PyObject *args)
{
struct rlimit rl;
int resource;
PyObject *limits;
if (!PyArg_ParseTuple(args, "iO:setrlimit", &resource, &limits))
return NULL;
if (resource < 0 || resource >= RLIM_NLIMITS) {
PyErr_SetString(PyExc_ValueError,
"invalid resource specified");
return NULL;
}
if (py2rlimit(limits, &rl) < 0) {
return NULL;
}
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(PyExc_OSError);
return NULL;
}
Py_RETURN_NONE;
}
#ifdef HAVE_PRLIMIT
static PyObject *
resource_prlimit(PyObject *self, PyObject *args)
{
struct rlimit old_limit, new_limit;
int resource, retval;
pid_t pid;
PyObject *limits = NULL;
if (!PyArg_ParseTuple(args, _Py_PARSE_PID "i|O:prlimit",
&pid, &resource, &limits))
return NULL;
if (resource < 0 || resource >= RLIM_NLIMITS) {
PyErr_SetString(PyExc_ValueError,
"invalid resource specified");
return NULL;
}
if (limits != NULL) {
if (py2rlimit(limits, &new_limit) < 0) {
return NULL;
}
retval = prlimit(pid, resource, &new_limit, &old_limit);
}
else {
retval = prlimit(pid, resource, NULL, &old_limit);
}
if (retval == -1) {
if (errno == EINVAL) {
PyErr_SetString(PyExc_ValueError,
"current limit exceeds maximum limit");
} else {
PyErr_SetFromErrno(PyExc_OSError);
}
return NULL;
}
return rlimit2py(old_limit);
}
#endif /* HAVE_PRLIMIT */
static PyObject *
resource_getpagesize(PyObject *self, PyObject *unused)
{
long pagesize = 0;
#if defined(HAVE_GETPAGESIZE)
pagesize = getpagesize();
#elif defined(HAVE_SYSCONF)
#if defined(_SC_PAGE_SIZE)
pagesize = sysconf(_SC_PAGE_SIZE);
#else
/* Irix 5.3 has _SC_PAGESIZE, but not _SC_PAGE_SIZE */
pagesize = sysconf(_SC_PAGESIZE);
#endif
#endif
return Py_BuildValue("i", pagesize);
}
static struct PyMethodDef
resource_methods[] = {
{"getrusage", resource_getrusage, METH_VARARGS},
{"getrlimit", resource_getrlimit, METH_VARARGS},
#ifdef HAVE_PRLIMIT
{"prlimit", resource_prlimit, METH_VARARGS},
#endif
{"setrlimit", resource_setrlimit, METH_VARARGS},
{"getpagesize", resource_getpagesize, METH_NOARGS},
{NULL, NULL} /* sentinel */
};
static struct PyModuleDef resourcemodule = {
PyModuleDef_HEAD_INIT,
"resource",
NULL,
-1,
resource_methods,
NULL,
NULL,
NULL,
NULL
};
PyMODINIT_FUNC
PyInit_resource(void)
{
PyObject *m, *v;
/* Create the module and add the functions */
m = PyModule_Create(&resourcemodule);
if (m == NULL)
return NULL;
/* Add some symbolic constants to the module */
Py_INCREF(PyExc_OSError);
PyModule_AddObject(m, "error", PyExc_OSError);
if (!initialized) {
if (PyStructSequence_InitType2(&StructRUsageType,
&struct_rusage_desc) < 0)
return NULL;
}
Py_INCREF(&StructRUsageType);
PyModule_AddObject(m, "struct_rusage",
(PyObject*) &StructRUsageType);
/* insert constants */
if (RLIMIT_CPU!=127) PyModule_AddIntMacro(m, RLIMIT_CPU);
if (RLIMIT_FSIZE!=127) PyModule_AddIntMacro(m, RLIMIT_FSIZE);
if (RLIMIT_DATA!=127) PyModule_AddIntMacro(m, RLIMIT_DATA);
if (RLIMIT_STACK!=127) PyModule_AddIntMacro(m, RLIMIT_STACK);
if (RLIMIT_CORE!=127) PyModule_AddIntMacro(m, RLIMIT_CORE);
if (RLIMIT_NOFILE!=127) PyModule_AddIntMacro(m, RLIMIT_NOFILE);
if (RLIMIT_VMEM!=127) PyModule_AddIntMacro(m, RLIMIT_VMEM);
if (RLIMIT_AS!=127) PyModule_AddIntMacro(m, RLIMIT_AS);
if (RLIMIT_RSS!=127) PyModule_AddIntMacro(m, RLIMIT_RSS);
if (RLIMIT_NPROC!=127) PyModule_AddIntMacro(m, RLIMIT_NPROC);
if (RLIMIT_MEMLOCK!=127) PyModule_AddIntMacro(m, RLIMIT_MEMLOCK);
if (RLIMIT_SBSIZE!=127) PyModule_AddIntMacro(m, RLIMIT_SBSIZE);
/* Linux specific */
if (RLIMIT_MSGQUEUE!=127) PyModule_AddIntMacro(m, RLIMIT_MSGQUEUE);
if (RLIMIT_NICE!=127) PyModule_AddIntMacro(m, RLIMIT_NICE);
if (RLIMIT_RTPRIO!=127) PyModule_AddIntMacro(m, RLIMIT_RTPRIO);
if (RLIMIT_RTTIME!=127) PyModule_AddIntMacro(m, RLIMIT_RTTIME);
if (RLIMIT_SIGPENDING!=127) PyModule_AddIntMacro(m, RLIMIT_SIGPENDING);
/* FreeBSD specific */
if (RLIMIT_SWAP!=127) PyModule_AddIntMacro(m, RLIMIT_SWAP);
if (RLIMIT_SBSIZE!=127) PyModule_AddIntMacro(m, RLIMIT_SBSIZE);
if (RLIMIT_NPTS!=127) PyModule_AddIntMacro(m, RLIMIT_NPTS);
/* target */
PyModule_AddIntMacro(m, RUSAGE_SELF);
if (RUSAGE_CHILDREN!=99) PyModule_AddIntMacro(m, RUSAGE_CHILDREN);
if (RUSAGE_BOTH!=99) PyModule_AddIntMacro(m, RUSAGE_BOTH);
if (RUSAGE_THREAD!=99) PyModule_AddIntMacro(m, RUSAGE_THREAD);
if (sizeof(RLIM_INFINITY) > sizeof(long)) {
v = PyLong_FromLongLong((long long) RLIM_INFINITY);
} else
{
v = PyLong_FromLong((long) RLIM_INFINITY);
}
if (v) {
PyModule_AddObject(m, "RLIM_INFINITY", v);
}
initialized = 1;
return m;
}
_Section(".rodata.pytab.1") const struct _inittab _PyImport_Inittab_resource = {
"resource",
PyInit_resource,
};
| 14,447 | 397 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Modules/_threadmodule.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:8;coding:utf-8 -*-â
âvi: set net ft=c ts=4 sts=4 sw=4 fenc=utf-8 :viâ
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ¡
â Python 3 â
â https://docs.python.org/3/license.html â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
#include "libc/assert.h"
#include "libc/calls/calls.h"
#include "libc/calls/internal.h"
#include "libc/calls/makedev.h"
#include "libc/calls/struct/dirent.h"
#include "libc/calls/struct/iovec.h"
#include "libc/calls/struct/rusage.h"
#include "libc/calls/struct/sched_param.h"
#include "libc/calls/struct/stat.macros.h"
#include "libc/calls/struct/statvfs.h"
#include "libc/calls/struct/timespec.h"
#include "libc/calls/struct/timeval.h"
#include "libc/calls/struct/tms.h"
#include "libc/calls/struct/utsname.h"
#include "libc/calls/struct/winsize.h"
#include "libc/calls/syscall-sysv.internal.h"
#include "libc/calls/sysparam.h"
#include "libc/calls/termios.h"
#include "libc/calls/weirdtypes.h"
#include "libc/dce.h"
#include "libc/errno.h"
#include "libc/log/log.h"
#include "libc/mem/alg.h"
#include "libc/mem/gc.internal.h"
#include "libc/nt/createfile.h"
#include "libc/nt/dll.h"
#include "libc/nt/enum/creationdisposition.h"
#include "libc/nt/enum/fileflagandattributes.h"
#include "libc/nt/enum/sw.h"
#include "libc/nt/files.h"
#include "libc/nt/runtime.h"
#include "libc/runtime/dlfcn.h"
#include "libc/runtime/pathconf.h"
#include "libc/runtime/sysconf.h"
#include "libc/sock/sendfile.internal.h"
#include "libc/sock/sock.h"
#include "libc/stdio/stdio.h"
#include "libc/sysv/consts/at.h"
#include "libc/sysv/consts/dt.h"
#include "libc/sysv/consts/ex.h"
#include "libc/sysv/consts/f.h"
#include "libc/sysv/consts/grnd.h"
#include "libc/sysv/consts/o.h"
#include "libc/sysv/consts/posix.h"
#include "libc/sysv/consts/prio.h"
#include "libc/sysv/consts/s.h"
#include "libc/sysv/consts/sched.h"
#include "libc/sysv/consts/seek.h"
#include "libc/sysv/consts/sf.h"
#include "libc/sysv/consts/sicode.h"
#include "libc/sysv/consts/st.h"
#include "libc/sysv/consts/w.h"
#include "libc/sysv/consts/waitid.h"
#include "libc/sysv/errfuns.h"
#include "libc/time/struct/utimbuf.h"
#include "libc/time/time.h"
#include "libc/x/x.h"
#include "third_party/musl/lockf.h"
#include "third_party/musl/passwd.h"
#include "third_party/python/Include/abstract.h"
#include "third_party/python/Include/boolobject.h"
#include "third_party/python/Include/ceval.h"
#include "third_party/python/Include/dictobject.h"
#include "third_party/python/Include/fileobject.h"
#include "third_party/python/Include/fileutils.h"
#include "third_party/python/Include/floatobject.h"
#include "third_party/python/Include/import.h"
#include "third_party/python/Include/intrcheck.h"
#include "third_party/python/Include/longobject.h"
#include "third_party/python/Include/modsupport.h"
#include "third_party/python/Include/objimpl.h"
#include "third_party/python/Include/osmodule.h"
#include "third_party/python/Include/pyerrors.h"
#include "third_party/python/Include/pylifecycle.h"
#include "third_party/python/Include/pymacro.h"
#include "third_party/python/Include/pymem.h"
#include "third_party/python/Include/pythread.h"
#include "third_party/python/Include/pytime.h"
#include "third_party/python/Include/structmember.h"
#include "third_party/python/Include/structseq.h"
#include "third_party/python/Include/sysmodule.h"
#include "third_party/python/Include/warnings.h"
#include "third_party/python/Include/weakrefobject.h"
#include "third_party/python/Include/yoink.h"
#include "third_party/python/pyconfig.h"
/* clang-format off */
PYTHON_PROVIDE("_thread");
PYTHON_PROVIDE("_thread.LockType");
PYTHON_PROVIDE("_thread.RLock");
PYTHON_PROVIDE("_thread.TIMEOUT_MAX");
PYTHON_PROVIDE("_thread._count");
PYTHON_PROVIDE("_thread._local");
PYTHON_PROVIDE("_thread._set_sentinel");
PYTHON_PROVIDE("_thread.allocate");
PYTHON_PROVIDE("_thread.allocate_lock");
PYTHON_PROVIDE("_thread.error");
PYTHON_PROVIDE("_thread.exit");
PYTHON_PROVIDE("_thread.exit_thread");
PYTHON_PROVIDE("_thread.get_ident");
PYTHON_PROVIDE("_thread.interrupt_main");
PYTHON_PROVIDE("_thread.stack_size");
PYTHON_PROVIDE("_thread.start_new");
PYTHON_PROVIDE("_thread.start_new_thread");
/* Thread module */
/* Interface to Sjoerd's portable C thread library */
#ifndef WITH_THREAD
#error "Error! The rest of Python is not compiled with thread support."
#error "Rerun configure, adding a --with-threads option."
#error "Then run `make clean' followed by `make'."
#endif
#include "third_party/python/Include/pythread.h"
static PyObject *ThreadError;
static long nb_threads = 0;
static PyObject *str_dict;
_Py_IDENTIFIER(stderr);
/* Lock objects */
typedef struct {
PyObject_HEAD
PyThread_type_lock lock_lock;
PyObject *in_weakreflist;
char locked; /* for sanity checking */
} 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 */
if (self->locked)
PyThread_release_lock(self->lock_lock);
PyThread_free_lock(self->lock_lock);
}
PyObject_Del(self);
}
/* Helper to acquire an interruptible lock with a timeout. If the lock acquire
* is interrupted, signal handlers are run, and if they raise an exception,
* PY_LOCK_INTR is returned. Otherwise, PY_LOCK_ACQUIRED or PY_LOCK_FAILURE
* are returned, depending on whether the lock can be acquired within the
* timeout.
*/
static PyLockStatus
acquire_timed(PyThread_type_lock lock, _PyTime_t timeout)
{
PyLockStatus r;
_PyTime_t endtime = 0;
_PyTime_t microseconds;
if (timeout > 0)
endtime = _PyTime_GetMonotonicClock() + timeout;
do {
microseconds = _PyTime_AsMicroseconds(timeout, _PyTime_ROUND_CEILING);
/* first a simple non-blocking try without releasing the GIL */
r = PyThread_acquire_lock_timed(lock, 0, 0);
if (r == PY_LOCK_FAILURE && microseconds != 0) {
Py_BEGIN_ALLOW_THREADS
r = PyThread_acquire_lock_timed(lock, microseconds, 1);
Py_END_ALLOW_THREADS
}
if (r == PY_LOCK_INTR) {
/* Run signal handlers if we were interrupted. Propagate
* exceptions from signal handlers, such as KeyboardInterrupt, by
* passing up PY_LOCK_INTR. */
if (Py_MakePendingCalls() < 0) {
return PY_LOCK_INTR;
}
/* If we're using a timeout, recompute the timeout after processing
* signals, since those can take time. */
if (timeout > 0) {
timeout = endtime - _PyTime_GetMonotonicClock();
/* Check for negative values, since those mean block forever.
*/
if (timeout < 0) {
r = PY_LOCK_FAILURE;
}
}
}
} while (r == PY_LOCK_INTR); /* Retry if we were interrupted. */
return r;
}
static int
lock_acquire_parse_args(PyObject *args, PyObject *kwds,
_PyTime_t *timeout)
{
char *kwlist[] = {"blocking", "timeout", NULL};
int blocking = 1;
PyObject *timeout_obj = NULL;
const _PyTime_t unset_timeout = _PyTime_FromSeconds(-1);
*timeout = unset_timeout ;
if (!PyArg_ParseTupleAndKeywords(args, kwds, "|iO:acquire", kwlist,
&blocking, &timeout_obj))
return -1;
if (timeout_obj
&& _PyTime_FromSecondsObject(timeout,
timeout_obj, _PyTime_ROUND_TIMEOUT) < 0)
return -1;
if (!blocking && *timeout != unset_timeout ) {
PyErr_SetString(PyExc_ValueError,
"can't specify a timeout for a non-blocking call");
return -1;
}
if (*timeout < 0 && *timeout != unset_timeout) {
PyErr_SetString(PyExc_ValueError,
"timeout value must be positive");
return -1;
}
if (!blocking)
*timeout = 0;
else if (*timeout != unset_timeout) {
_PyTime_t microseconds;
microseconds = _PyTime_AsMicroseconds(*timeout, _PyTime_ROUND_TIMEOUT);
if (microseconds >= PY_TIMEOUT_MAX) {
PyErr_SetString(PyExc_OverflowError,
"timeout value is too large");
return -1;
}
}
return 0;
}
static PyObject *
lock_PyThread_acquire_lock(lockobject *self, PyObject *args, PyObject *kwds)
{
_PyTime_t timeout;
PyLockStatus r;
if (lock_acquire_parse_args(args, kwds, &timeout) < 0)
return NULL;
r = acquire_timed(self->lock_lock, timeout);
if (r == PY_LOCK_INTR) {
return NULL;
}
if (r == PY_LOCK_ACQUIRED)
self->locked = 1;
return PyBool_FromLong(r == PY_LOCK_ACQUIRED);
}
PyDoc_STRVAR(acquire_doc,
"acquire(blocking=True, timeout=-1) -> bool\n\
(acquire_lock() is an obsolete synonym)\n\
\n\
Lock the lock. Without argument, this blocks if the lock is already\n\
locked (even by the same thread), waiting for another thread to release\n\
the lock, and return True once the lock is acquired.\n\
With an argument, this will only block if the argument is true,\n\
and the return value reflects whether the lock is acquired.\n\
The blocking operation is interruptible.");
static PyObject *
lock_PyThread_release_lock(lockobject *self)
{
/* Sanity check: the lock must be locked */
if (!self->locked) {
PyErr_SetString(ThreadError, "release unlocked lock");
return NULL;
}
PyThread_release_lock(self->lock_lock);
self->locked = 0;
Py_INCREF(Py_None);
return Py_None;
}
PyDoc_STRVAR(release_doc,
"release()\n\
(release_lock() is an obsolete synonym)\n\
\n\
Release the lock, allowing another thread that is blocked waiting for\n\
the lock to acquire the lock. The lock must be in the locked state,\n\
but it needn't be locked by the same thread that unlocks it.");
static PyObject *
lock_locked_lock(lockobject *self)
{
return PyBool_FromLong((long)self->locked);
}
PyDoc_STRVAR(locked_doc,
"locked() -> bool\n\
(locked_lock() is an obsolete synonym)\n\
\n\
Return whether the lock is in the locked state.");
static PyObject *
lock_repr(lockobject *self)
{
return PyUnicode_FromFormat("<%s %s object at %p>",
self->locked ? "locked" : "unlocked", Py_TYPE(self)->tp_name, self);
}
static PyMethodDef lock_methods[] = {
{"acquire_lock", (PyCFunction)lock_PyThread_acquire_lock,
METH_VARARGS | METH_KEYWORDS, acquire_doc},
{"acquire", (PyCFunction)lock_PyThread_acquire_lock,
METH_VARARGS | METH_KEYWORDS, 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 | METH_KEYWORDS, acquire_doc},
{"__exit__", (PyCFunction)lock_PyThread_release_lock,
METH_VARARGS, release_doc},
{NULL, NULL} /* sentinel */
};
static PyTypeObject Locktype = {
PyVarObject_HEAD_INIT(&PyType_Type, 0)
"_thread.lock", /*tp_name*/
sizeof(lockobject), /*tp_basicsize*/
0, /*tp_itemsize*/
/* methods */
(destructor)lock_dealloc, /*tp_dealloc*/
0, /*tp_print*/
0, /*tp_getattr*/
0, /*tp_setattr*/
0, /*tp_reserved*/
(reprfunc)lock_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*/
offsetof(lockobject, in_weakreflist), /*tp_weaklistoffset*/
0, /*tp_iter*/
0, /*tp_iternext*/
lock_methods, /*tp_methods*/
};
/* Recursive lock objects */
typedef struct {
PyObject_HEAD
PyThread_type_lock rlock_lock;
long rlock_owner;
unsigned long rlock_count;
PyObject *in_weakreflist;
} rlockobject;
static void
rlock_dealloc(rlockobject *self)
{
if (self->in_weakreflist != NULL)
PyObject_ClearWeakRefs((PyObject *) self);
/* self->rlock_lock can be NULL if PyThread_allocate_lock() failed
in rlock_new() */
if (self->rlock_lock != NULL) {
/* Unlock the lock so it's safe to free it */
if (self->rlock_count > 0)
PyThread_release_lock(self->rlock_lock);
PyThread_free_lock(self->rlock_lock);
}
Py_TYPE(self)->tp_free(self);
}
static PyObject *
rlock_acquire(rlockobject *self, PyObject *args, PyObject *kwds)
{
_PyTime_t timeout;
long tid;
PyLockStatus r = PY_LOCK_ACQUIRED;
if (lock_acquire_parse_args(args, kwds, &timeout) < 0)
return NULL;
tid = PyThread_get_thread_ident();
if (self->rlock_count > 0 && tid == self->rlock_owner) {
unsigned long count = self->rlock_count + 1;
if (count <= self->rlock_count) {
PyErr_SetString(PyExc_OverflowError,
"Internal lock count overflowed");
return NULL;
}
self->rlock_count = count;
Py_RETURN_TRUE;
}
r = acquire_timed(self->rlock_lock, timeout);
if (r == PY_LOCK_ACQUIRED) {
assert(self->rlock_count == 0);
self->rlock_owner = tid;
self->rlock_count = 1;
}
else if (r == PY_LOCK_INTR) {
return NULL;
}
return PyBool_FromLong(r == PY_LOCK_ACQUIRED);
}
PyDoc_STRVAR(rlock_acquire_doc,
"acquire(blocking=True) -> bool\n\
\n\
Lock the lock. `blocking` indicates whether we should wait\n\
for the lock to be available or not. If `blocking` is False\n\
and another thread holds the lock, the method will return False\n\
immediately. If `blocking` is True and another thread holds\n\
the lock, the method will wait for the lock to be released,\n\
take it and then return True.\n\
(note: the blocking operation is interruptible.)\n\
\n\
In all other cases, the method will return True immediately.\n\
Precisely, if the current thread already holds the lock, its\n\
internal counter is simply incremented. If nobody holds the lock,\n\
the lock is taken and its internal counter initialized to 1.");
static PyObject *
rlock_release(rlockobject *self)
{
long tid = PyThread_get_thread_ident();
if (self->rlock_count == 0 || self->rlock_owner != tid) {
PyErr_SetString(PyExc_RuntimeError,
"cannot release un-acquired lock");
return NULL;
}
if (--self->rlock_count == 0) {
self->rlock_owner = 0;
PyThread_release_lock(self->rlock_lock);
}
Py_RETURN_NONE;
}
PyDoc_STRVAR(rlock_release_doc,
"release()\n\
\n\
Release the lock, allowing another thread that is blocked waiting for\n\
the lock to acquire the lock. The lock must be in the locked state,\n\
and must be locked by the same thread that unlocks it; otherwise a\n\
`RuntimeError` is raised.\n\
\n\
Do note that if the lock was acquire()d several times in a row by the\n\
current thread, release() needs to be called as many times for the lock\n\
to be available for other threads.");
static PyObject *
rlock_acquire_restore(rlockobject *self, PyObject *args)
{
long owner;
unsigned long count;
int r = 1;
if (!PyArg_ParseTuple(args, "(kl):_acquire_restore", &count, &owner))
return NULL;
if (!PyThread_acquire_lock(self->rlock_lock, 0)) {
Py_BEGIN_ALLOW_THREADS
r = PyThread_acquire_lock(self->rlock_lock, 1);
Py_END_ALLOW_THREADS
}
if (!r) {
PyErr_SetString(ThreadError, "couldn't acquire lock");
return NULL;
}
assert(self->rlock_count == 0);
self->rlock_owner = owner;
self->rlock_count = count;
Py_RETURN_NONE;
}
PyDoc_STRVAR(rlock_acquire_restore_doc,
"_acquire_restore(state) -> None\n\
\n\
For internal use by `threading.Condition`.");
static PyObject *
rlock_release_save(rlockobject *self)
{
long owner;
unsigned long count;
if (self->rlock_count == 0) {
PyErr_SetString(PyExc_RuntimeError,
"cannot release un-acquired lock");
return NULL;
}
owner = self->rlock_owner;
count = self->rlock_count;
self->rlock_count = 0;
self->rlock_owner = 0;
PyThread_release_lock(self->rlock_lock);
return Py_BuildValue("kl", count, owner);
}
PyDoc_STRVAR(rlock_release_save_doc,
"_release_save() -> tuple\n\
\n\
For internal use by `threading.Condition`.");
static PyObject *
rlock_is_owned(rlockobject *self)
{
long tid = PyThread_get_thread_ident();
if (self->rlock_count > 0 && self->rlock_owner == tid) {
Py_RETURN_TRUE;
}
Py_RETURN_FALSE;
}
PyDoc_STRVAR(rlock_is_owned_doc,
"_is_owned() -> bool\n\
\n\
For internal use by `threading.Condition`.");
static PyObject *
rlock_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
rlockobject *self;
self = (rlockobject *) type->tp_alloc(type, 0);
if (self != NULL) {
self->in_weakreflist = NULL;
self->rlock_owner = 0;
self->rlock_count = 0;
self->rlock_lock = PyThread_allocate_lock();
if (self->rlock_lock == NULL) {
Py_DECREF(self);
PyErr_SetString(ThreadError, "can't allocate lock");
return NULL;
}
}
return (PyObject *) self;
}
static PyObject *
rlock_repr(rlockobject *self)
{
return PyUnicode_FromFormat("<%s %s object owner=%ld count=%lu at %p>",
self->rlock_count ? "locked" : "unlocked",
Py_TYPE(self)->tp_name, self->rlock_owner,
self->rlock_count, self);
}
static PyMethodDef rlock_methods[] = {
{"acquire", (PyCFunction)rlock_acquire,
METH_VARARGS | METH_KEYWORDS, rlock_acquire_doc},
{"release", (PyCFunction)rlock_release,
METH_NOARGS, rlock_release_doc},
{"_is_owned", (PyCFunction)rlock_is_owned,
METH_NOARGS, rlock_is_owned_doc},
{"_acquire_restore", (PyCFunction)rlock_acquire_restore,
METH_VARARGS, rlock_acquire_restore_doc},
{"_release_save", (PyCFunction)rlock_release_save,
METH_NOARGS, rlock_release_save_doc},
{"__enter__", (PyCFunction)rlock_acquire,
METH_VARARGS | METH_KEYWORDS, rlock_acquire_doc},
{"__exit__", (PyCFunction)rlock_release,
METH_VARARGS, rlock_release_doc},
{NULL, NULL} /* sentinel */
};
static PyTypeObject RLocktype = {
PyVarObject_HEAD_INIT(&PyType_Type, 0)
"_thread.RLock", /*tp_name*/
sizeof(rlockobject), /*tp_basicsize*/
0, /*tp_itemsize*/
/* methods */
(destructor)rlock_dealloc, /*tp_dealloc*/
0, /*tp_print*/
0, /*tp_getattr*/
0, /*tp_setattr*/
0, /*tp_reserved*/
(reprfunc)rlock_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_BASETYPE, /* tp_flags */
0, /*tp_doc*/
0, /*tp_traverse*/
0, /*tp_clear*/
0, /*tp_richcompare*/
offsetof(rlockobject, in_weakreflist), /*tp_weaklistoffset*/
0, /*tp_iter*/
0, /*tp_iternext*/
rlock_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 */
rlock_new /* tp_new */
};
static lockobject *
newlockobject(void)
{
lockobject *self;
self = PyObject_New(lockobject, &Locktype);
if (self == NULL)
return NULL;
self->lock_lock = PyThread_allocate_lock();
self->locked = 0;
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 */
#include "third_party/python/Include/structmember.h"
/* Quick overview:
We need to be able to reclaim reference cycles as soon as possible
(both when a thread is being terminated, or a thread-local object
becomes unreachable from user data). Constraints:
- it must not be possible for thread-state dicts to be involved in
reference cycles (otherwise the cyclic GC will refuse to consider
objects referenced from a reachable thread-state dict, even though
local_dealloc would clear them)
- the death of a thread-state dict must still imply destruction of the
corresponding local dicts in all thread-local objects.
Our implementation uses small "localdummy" objects in order to break
the reference chain. These trivial objects are hashable (using the
default scheme of identity hashing) and weakrefable.
Each thread-state holds a separate localdummy for each local object
(as a /strong reference/),
and each thread-local object holds a dict mapping /weak references/
of localdummies to local dicts.
Therefore:
- only the thread-state dict holds a strong reference to the dummies
- only the thread-local object holds a strong reference to the local dicts
- only outside objects (application- or library-level) hold strong
references to the thread-local objects
- as soon as a thread-state dict is destroyed, the weakref callbacks of all
dummies attached to that thread are called, and destroy the corresponding
local dicts from thread-local objects
- as soon as a thread-local object is destroyed, its local dicts are
destroyed and its dummies are manually removed from all thread states
- the GC can do its work correctly when a thread-local object is dangling,
without any interference from the thread-state dicts
As an additional optimization, each localdummy holds a borrowed reference
to the corresponding localdict. This borrowed reference is only used
by the thread-local object which has created the localdummy, which should
guarantee that the localdict still exists when accessed.
*/
typedef struct {
PyObject_HEAD
PyObject *localdict; /* Borrowed reference! */
PyObject *weakreflist; /* List of weak references to self */
} localdummyobject;
static void
localdummy_dealloc(localdummyobject *self)
{
if (self->weakreflist != NULL)
PyObject_ClearWeakRefs((PyObject *) self);
Py_TYPE(self)->tp_free((PyObject*)self);
}
static PyTypeObject localdummytype = {
PyVarObject_HEAD_INIT(NULL, 0)
/* tp_name */ "_thread._localdummy",
/* tp_basicsize */ sizeof(localdummyobject),
/* tp_itemsize */ 0,
/* tp_dealloc */ (destructor)localdummy_dealloc,
/* tp_print */ 0,
/* tp_getattr */ 0,
/* tp_setattr */ 0,
/* tp_reserved */ 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,
/* tp_doc */ "Thread-local dummy",
/* tp_traverse */ 0,
/* tp_clear */ 0,
/* tp_richcompare */ 0,
/* tp_weaklistoffset */ offsetof(localdummyobject, weakreflist)
};
typedef struct {
PyObject_HEAD
PyObject *key;
PyObject *args;
PyObject *kw;
PyObject *weakreflist; /* List of weak references to self */
/* A {localdummy weakref -> localdict} dict */
PyObject *dummies;
/* The callback for weakrefs to localdummies */
PyObject *wr_callback;
} localobject;
/* Forward declaration */
static PyObject *_ldict(localobject *self);
static PyObject *_localdummy_destroyed(PyObject *meth_self, PyObject *dummyweakref);
/* Create and register the dummy for the current thread.
Returns a borrowed reference of the corresponding local dict */
static PyObject *
_local_create_dummy(localobject *self)
{
PyObject *tdict, *ldict = NULL, *wr = NULL;
localdummyobject *dummy = NULL;
int r;
tdict = PyThreadState_GetDict();
if (tdict == NULL) {
PyErr_SetString(PyExc_SystemError,
"Couldn't get thread-state dictionary");
goto err;
}
ldict = PyDict_New();
if (ldict == NULL)
goto err;
dummy = (localdummyobject *) localdummytype.tp_alloc(&localdummytype, 0);
if (dummy == NULL)
goto err;
dummy->localdict = ldict;
wr = PyWeakref_NewRef((PyObject *) dummy, self->wr_callback);
if (wr == NULL)
goto err;
/* As a side-effect, this will cache the weakref's hash before the
dummy gets deleted */
r = PyDict_SetItem(self->dummies, wr, ldict);
if (r < 0)
goto err;
Py_CLEAR(wr);
r = PyDict_SetItem(tdict, self->key, (PyObject *) dummy);
if (r < 0)
goto err;
Py_CLEAR(dummy);
Py_DECREF(ldict);
return ldict;
err:
Py_XDECREF(ldict);
Py_XDECREF(wr);
Py_XDECREF(dummy);
return NULL;
}
static PyObject *
local_new(PyTypeObject *type, PyObject *args, PyObject *kw)
{
localobject *self;
PyObject *wr;
static PyMethodDef wr_callback_def = {
"_localdummy_destroyed", (PyCFunction) _localdummy_destroyed, METH_O
};
if (type->tp_init == PyBaseObject_Type.tp_init) {
int rc = 0;
if (args != NULL)
rc = PyObject_IsTrue(args);
if (rc == 0 && kw != NULL)
rc = PyObject_IsTrue(kw);
if (rc != 0) {
if (rc > 0)
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->key = PyUnicode_FromFormat("thread.local.%p", self);
if (self->key == NULL)
goto err;
self->dummies = PyDict_New();
if (self->dummies == NULL)
goto err;
/* We use a weak reference to self in the callback closure
in order to avoid spurious reference cycles */
wr = PyWeakref_NewRef((PyObject *) self, NULL);
if (wr == NULL)
goto err;
self->wr_callback = PyCFunction_NewEx(&wr_callback_def, wr, NULL);
Py_DECREF(wr);
if (self->wr_callback == NULL)
goto err;
if (_local_create_dummy(self) == NULL)
goto err;
return (PyObject *)self;
err:
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->dummies);
return 0;
}
static int
local_clear(localobject *self)
{
PyThreadState *tstate;
Py_CLEAR(self->args);
Py_CLEAR(self->kw);
Py_CLEAR(self->dummies);
Py_CLEAR(self->wr_callback);
/* Remove all strong references to dummies from the thread states */
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)) {
if (PyDict_DelItem(tstate->dict, self->key)) {
PyErr_Clear();
}
}
}
return 0;
}
static void
local_dealloc(localobject *self)
{
/* Weakrefs must be invalidated right now, otherwise they can be used
from code called below, which is very dangerous since Py_REFCNT(self) == 0 */
if (self->weakreflist != NULL)
PyObject_ClearWeakRefs((PyObject *) self);
PyObject_GC_UnTrack(self);
local_clear(self);
Py_XDECREF(self->key);
Py_TYPE(self)->tp_free((PyObject*)self);
}
/* Returns a borrowed reference to the local dict, creating it if necessary */
static PyObject *
_ldict(localobject *self)
{
PyObject *tdict, *ldict, *dummy;
tdict = PyThreadState_GetDict();
if (tdict == NULL) {
PyErr_SetString(PyExc_SystemError,
"Couldn't get thread-state dictionary");
return NULL;
}
dummy = PyDict_GetItem(tdict, self->key);
if (dummy == NULL) {
ldict = _local_create_dummy(self);
if (ldict == NULL)
return NULL;
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
access */
PyDict_DelItem(tdict, self->key);
return NULL;
}
}
else {
assert(Py_TYPE(dummy) == &localdummytype);
ldict = ((localdummyobject *) dummy)->localdict;
}
return ldict;
}
static int
local_setattro(localobject *self, PyObject *name, PyObject *v)
{
PyObject *ldict;
int r;
ldict = _ldict(self);
if (ldict == NULL)
return -1;
r = PyObject_RichCompareBool(name, str_dict, Py_EQ);
if (r == 1) {
PyErr_Format(PyExc_AttributeError,
"'%.50s' object attribute '%U' is read-only",
Py_TYPE(self)->tp_name, name);
return -1;
}
if (r == -1)
return -1;
return _PyObject_GenericSetAttrWithDict((PyObject *)self, name, v, ldict);
}
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_reserved */ 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
| Py_TPFLAGS_HAVE_GC,
/* tp_doc */ "Thread-local data",
/* tp_traverse */ (traverseproc)local_traverse,
/* tp_clear */ (inquiry)local_clear,
/* tp_richcompare */ 0,
/* tp_weaklistoffset */ offsetof(localobject, weakreflist),
/* tp_iter */ 0,
/* tp_iternext */ 0,
/* tp_methods */ 0,
/* tp_members */ 0,
/* tp_getset */ 0,
/* tp_base */ 0,
/* tp_dict */ 0, /* internal use */
/* tp_descr_get */ 0,
/* tp_descr_set */ 0,
/* tp_dictoffset */ 0,
/* 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;
int r;
ldict = _ldict(self);
if (ldict == NULL)
return NULL;
r = PyObject_RichCompareBool(name, str_dict, Py_EQ);
if (r == 1) {
Py_INCREF(ldict);
return ldict;
}
if (r == -1)
return NULL;
if (Py_TYPE(self) != &localtype)
/* use generic lookup for subtypes */
return _PyObject_GenericGetAttrWithDict((PyObject *)self, name, ldict);
/* 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_GenericGetAttrWithDict((PyObject *)self, name, ldict);
Py_INCREF(value);
return value;
}
/* Called when a dummy is destroyed. */
static PyObject *
_localdummy_destroyed(PyObject *localweakref, PyObject *dummyweakref)
{
PyObject *obj;
localobject *self;
assert(PyWeakref_CheckRef(localweakref));
obj = PyWeakref_GET_OBJECT(localweakref);
if (obj == Py_None)
Py_RETURN_NONE;
Py_INCREF(obj);
assert(PyObject_TypeCheck(obj, &localtype));
/* If the thread-local object is still alive and not being cleared,
remove the corresponding local dict */
self = (localobject *) obj;
if (self->dummies != NULL) {
PyObject *ldict;
ldict = PyDict_GetItem(self->dummies, dummyweakref);
if (ldict != NULL) {
PyDict_DelItem(self->dummies, dummyweakref);
}
if (PyErr_Occurred())
PyErr_WriteUnraisable(obj);
}
Py_DECREF(obj);
Py_RETURN_NONE;
}
/* Module functions */
struct bootstate {
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;
PyObject *exc, *value, *tb;
PySys_FormatStderr(
"Unhandled exception in thread started by ");
PyErr_Fetch(&exc, &value, &tb);
file = _PySys_GetObjectId(&PyId_stderr);
if (file != NULL && file != Py_None)
PyFile_WriteObject(boot->func, file, 0);
else
PyObject_Print(boot->func, stderr, 0);
PySys_FormatStderr("\n");
PyErr_Restore(exc, value, tb);
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 PyLong_FromLong(ident);
}
PyDoc_STRVAR(start_new_doc,
"start_new_thread(function, args[, kwargs])\n\
(start_new() is an obsolete synonym)\n\
\n\
Start a new thread and return its identifier. The thread will call the\n\
function with positional arguments from the tuple args and keyword arguments\n\
taken from the optional dictionary kwargs. The thread exits when the\n\
function returns; the return value is ignored. The thread will also exit\n\
when the function raises an unhandled exception; a stack trace will be\n\
printed unless the exception is SystemExit.\n");
static PyObject *
thread_PyThread_exit_thread(PyObject *self)
{
PyErr_SetNone(PyExc_SystemExit);
return NULL;
}
PyDoc_STRVAR(exit_doc,
"exit()\n\
(exit_thread() is an obsolete synonym)\n\
\n\
This is synonymous to ``raise SystemExit''. It will cause the current\n\
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;
}
PyDoc_STRVAR(interrupt_doc,
"interrupt_main()\n\
\n\
Raise a KeyboardInterrupt in the main thread.\n\
A subthread can use this function to interrupt the main thread."
);
static lockobject *newlockobject(void);
static PyObject *
thread_PyThread_allocate_lock(PyObject *self)
{
return (PyObject *) newlockobject();
}
PyDoc_STRVAR(allocate_doc,
"allocate_lock() -> lock object\n\
(allocate() is an obsolete synonym)\n\
\n\
Create a new lock object. See help(type(threading.Lock())) for\n\
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 PyLong_FromLong(ident);
}
PyDoc_STRVAR(get_ident_doc,
"get_ident() -> integer\n\
\n\
Return a non-zero integer that uniquely identifies the current thread\n\
amongst other threads that exist simultaneously.\n\
This may be used to identify per-thread resources.\n\
Even though on some platforms threads identities may appear to be\n\
allocated consecutive numbers starting at 1, this behavior should not\n\
be relied upon, and the number should be seen purely as a magic cookie.\n\
A thread's identity may be reused for another thread after it exits.");
static PyObject *
thread__count(PyObject *self)
{
return PyLong_FromLong(nb_threads);
}
PyDoc_STRVAR(_count_doc,
"_count() -> integer\n\
\n\
\
Return the number of currently running Python threads, excluding \n\
the main thread. The returned number comprises all threads created\n\
through `start_new_thread()` as well as `threading.Thread`, and not\n\
yet finished.\n\
\n\
This function is meant for internal and specialized purposes only.\n\
In most applications `threading.enumerate()` should be used instead.");
static void
release_sentinel(void *wr)
{
/* Tricky: this function is called when the current thread state
is being deleted. Therefore, only simple C code can safely
execute here. */
PyObject *obj = PyWeakref_GET_OBJECT(wr);
lockobject *lock;
if (obj != Py_None) {
assert(Py_TYPE(obj) == &Locktype);
lock = (lockobject *) obj;
if (lock->locked) {
PyThread_release_lock(lock->lock_lock);
lock->locked = 0;
}
}
/* Deallocating a weakref with a NULL callback only calls
PyObject_GC_Del(), which can't call any Python code. */
Py_DECREF(wr);
}
static PyObject *
thread__set_sentinel(PyObject *self)
{
PyObject *wr;
PyThreadState *tstate = PyThreadState_Get();
lockobject *lock;
if (tstate->on_delete_data != NULL) {
/* We must support the re-creation of the lock from a
fork()ed child. */
assert(tstate->on_delete == &release_sentinel);
wr = (PyObject *) tstate->on_delete_data;
tstate->on_delete = NULL;
tstate->on_delete_data = NULL;
Py_DECREF(wr);
}
lock = newlockobject();
if (lock == NULL)
return NULL;
/* The lock is owned by whoever called _set_sentinel(), but the weakref
hangs to the thread state. */
wr = PyWeakref_NewRef((PyObject *) lock, NULL);
if (wr == NULL) {
Py_DECREF(lock);
return NULL;
}
tstate->on_delete_data = (void *) wr;
tstate->on_delete = &release_sentinel;
return (PyObject *) lock;
}
PyDoc_STRVAR(_set_sentinel_doc,
"_set_sentinel() -> lock\n\
\n\
Set a sentinel lock that will be released when the current thread\n\
state is finalized (after it is untied from the interpreter).\n\
\n\
This is a private API for the threading module.");
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 PyLong_FromSsize_t((Py_ssize_t) old_size);
}
PyDoc_STRVAR(stack_size_doc,
"stack_size([size]) -> size\n\
\n\
Return the thread stack size used when creating new threads. The\n\
optional size argument specifies the stack size (in bytes) to be used\n\
for subsequently created threads, and must be 0 (use platform or\n\
configured default) or a positive integer value of at least 32,768 (32k).\n\
If changing the thread stack size is unsupported, a ThreadError\n\
exception is raised. If the specified size is invalid, a ValueError\n\
exception is raised, and the stack size is unmodified. 32k bytes\n\
currently the minimum supported stack size value to guarantee\n\
sufficient stack space for the interpreter itself.\n\
\n\
Note that some platforms may have particular restrictions on values for\n\
the stack size, such as requiring a minimum stack size larger than 32kB or\n\
requiring allocation in multiples of the system memory page size\n\
- platform documentation should be referred to for more information\n\
(4kB pages are common; using multiples of 4096 for the stack size is\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},
{"_set_sentinel", (PyCFunction)thread__set_sentinel,
METH_NOARGS, _set_sentinel_doc},
{NULL, NULL} /* sentinel */
};
/* Initialization function */
PyDoc_STRVAR(thread_doc,
"This module provides primitive operations to write multi-threaded programs.\n\
The 'threading' module provides a more convenient interface.");
PyDoc_STRVAR(lock_doc,
"A lock object is a synchronization primitive. To create a lock,\n\
call threading.Lock(). Methods are:\n\
\n\
acquire() -- lock the lock, possibly blocking until it can be obtained\n\
release() -- unlock of the lock\n\
locked() -- test whether the lock is currently locked\n\
\n\
A lock is not owned by the thread that locked it; another thread may\n\
unlock it. A thread attempting to lock a lock that it has already locked\n\
will block until another thread unlocks it. Deadlocks may ensue.");
static struct PyModuleDef threadmodule = {
PyModuleDef_HEAD_INIT,
"_thread",
thread_doc,
-1,
thread_methods,
NULL,
NULL,
NULL,
NULL
};
PyMODINIT_FUNC
PyInit__thread(void)
{
PyObject *m, *d, *v;
double time_max;
double timeout_max;
/* Initialize types: */
if (PyType_Ready(&localdummytype) < 0)
return NULL;
if (PyType_Ready(&localtype) < 0)
return NULL;
if (PyType_Ready(&Locktype) < 0)
return NULL;
if (PyType_Ready(&RLocktype) < 0)
return NULL;
/* Create the module and add the functions */
m = PyModule_Create(&threadmodule);
if (m == NULL)
return NULL;
timeout_max = PY_TIMEOUT_MAX / 1000000;
time_max = floor(_PyTime_AsSecondsDouble(_PyTime_MAX));
timeout_max = Py_MIN(timeout_max, time_max);
v = PyFloat_FromDouble(timeout_max);
if (!v)
return NULL;
if (PyModule_AddObject(m, "TIMEOUT_MAX", v) < 0)
return NULL;
/* Add a symbolic constant */
d = PyModule_GetDict(m);
ThreadError = PyExc_RuntimeError;
Py_INCREF(ThreadError);
PyDict_SetItemString(d, "error", ThreadError);
Locktype.tp_doc = lock_doc;
Py_INCREF(&Locktype);
PyDict_SetItemString(d, "LockType", (PyObject *)&Locktype);
Py_INCREF(&RLocktype);
if (PyModule_AddObject(m, "RLock", (PyObject *)&RLocktype) < 0)
return NULL;
Py_INCREF(&localtype);
if (PyModule_AddObject(m, "_local", (PyObject *)&localtype) < 0)
return NULL;
nb_threads = 0;
str_dict = PyUnicode_InternFromString("__dict__");
if (str_dict == NULL)
return NULL;
/* Initialize the C thread library */
PyThread_init_thread();
return m;
}
| 49,292 | 1,522 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Modules/unicodedata_3.2.0.c | #include "libc/nexgen32e/kompressor.h"
#include "third_party/python/Modules/unicodedata.h"
/* clang-format off */
/* GENERATED BY third_party/python/Tools/unicode/makeunicodedata.py 3.2 */
const _PyUnicode_ChangeRecord _PyUnicode_ChangeRecords_3_2_0[] = {
{ 255, 255, 255, 255, 255, 0 },
{ 11, 255, 255, 255, 255, 0 },
{ 10, 255, 255, 255, 255, 0 },
{ 255, 30, 255, 255, 255, 0 },
{ 255, 2, 255, 255, 255, 0 },
{ 19, 21, 255, 255, 255, 0 },
{ 255, 255, 2, 255, 255, 0 },
{ 255, 255, 3, 255, 255, 0 },
{ 255, 255, 1, 255, 255, 0 },
{ 255, 0, 255, 255, 255, 0 },
{ 255, 29, 255, 255, 255, 0 },
{ 255, 26, 255, 255, 255, 0 },
{ 5, 255, 255, 255, 255, 0 },
{ 14, 6, 255, 255, 255, 0 },
{ 15, 255, 255, 255, 255, 0 },
{ 255, 255, 255, 255, 255, 1.0 },
{ 255, 255, 255, 255, 255, 2.0 },
{ 255, 255, 255, 255, 255, 3.0 },
{ 255, 255, 255, 255, 255, 4.0 },
{ 255, 255, 255, 255, 255, -1 },
{ 14, 255, 255, 255, 255, 0 },
{ 255, 255, 255, 0, 255, 0 },
{ 255, 19, 255, 255, 255, 0 },
{ 255, 7, 1, 255, 255, 0 },
{ 255, 7, 2, 255, 255, 0 },
{ 255, 7, 3, 255, 255, 0 },
{ 255, 7, 4, 255, 255, 0 },
{ 255, 7, 5, 255, 255, 0 },
{ 255, 7, 6, 255, 255, 0 },
{ 255, 7, 7, 255, 255, 0 },
{ 255, 7, 8, 255, 255, 0 },
{ 255, 7, 9, 255, 255, 0 },
{ 1, 5, 255, 255, 255, 0 },
{ 1, 19, 255, 255, 255, 0 },
{ 255, 10, 255, 255, 255, 0 },
{ 18, 255, 255, 255, 255, 0 },
{ 19, 255, 255, 255, 255, 0 },
{ 255, 255, 0, 255, 255, 0 },
{ 255, 255, 4, 255, 255, 0 },
{ 255, 255, 5, 255, 255, 0 },
{ 255, 255, 6, 255, 255, 0 },
{ 255, 255, 7, 255, 255, 0 },
{ 255, 255, 8, 255, 255, 0 },
{ 255, 255, 9, 255, 255, 0 },
{ 19, 30, 255, 255, 255, 0 },
{ 255, 8, 255, 255, 255, 0 },
{ 255, 27, 255, 255, 255, 0 },
{ 255, 255, 255, 255, 5, 0 },
{ 255, 22, 255, 255, 255, 0 },
{ 255, 23, 255, 255, 255, 0 },
{ 9, 255, 255, 255, 255, 0 },
{ 255, 255, 255, 1, 255, 0 },
{ 14, 4, 255, 255, 255, 0 },
{ 255, 20, 255, 255, 255, 0 },
{ 255, 255, 255, 255, 255, 1e+16 },
{ 255, 255, 255, 255, 255, 1e+20 },
{ 255, 19, 255, 255, 255, -1 },
{ 1, 255, 255, 0, 255, 0 },
};
unsigned char _PyUnicode_ChangeIndex_3_2_0[8704];
static const unsigned char _PyUnicode_ChangeIndex_3_2_0_rodata[365+1][2] = { /* 8.38695% profit */
{ 1, 0x00},
{ 1, 0x01},
{ 2, 0x02},
{ 1, 0x03},
{ 1, 0x04},
{ 1, 0x05},
{ 1, 0x06},
{ 1, 0x02},
{ 1, 0x07},
{ 1, 0x08},
{ 1, 0x09},
{ 1, 0x0a},
{ 1, 0x0b},
{ 1, 0x0c},
{ 1, 0x0d},
{ 1, 0x0e},
{ 1, 0x0f},
{ 1, 0x10},
{ 1, 0x11},
{ 1, 0x12},
{ 1, 0x13},
{ 1, 0x14},
{ 1, 0x15},
{ 1, 0x16},
{ 1, 0x17},
{ 1, 0x18},
{ 1, 0x19},
{ 1, 0x02},
{ 1, 0x1a},
{ 1, 0x1b},
{ 1, 0x1c},
{ 1, 0x1d},
{ 1, 0x1e},
{ 1, 0x1f},
{ 1, 0x20},
{ 1, 0x21},
{ 1, 0x22},
{ 1, 0x23},
{ 1, 0x24},
{ 1, 0x25},
{ 3, 0x02},
{ 1, 0x26},
{ 1, 0x27},
{ 1, 0x02},
{ 1, 0x28},
{ 1, 0x29},
{ 1, 0x2a},
{ 1, 0x2b},
{ 1, 0x2c},
{ 1, 0x2d},
{ 1, 0x2e},
{ 1, 0x2f},
{ 1, 0x30},
{ 1, 0x31},
{ 1, 0x32},
{ 1, 0x33},
{ 1, 0x34},
{ 1, 0x02},
{ 1, 0x35},
{ 2, 0x02},
{ 1, 0x36},
{ 1, 0x37},
{ 1, 0x38},
{ 1, 0x39},
{ 1, 0x3a},
{ 1, 0x02},
{ 1, 0x3b},
{ 1, 0x3c},
{ 1, 0x3d},
{ 1, 0x3e},
{ 1, 0x02},
{ 1, 0x3f},
{ 1, 0x40},
{ 1, 0x41},
{ 1, 0x42},
{ 1, 0x43},
{ 2, 0x44},
{ 1, 0x02},
{ 1, 0x45},
{ 2, 0x02},
{ 1, 0x46},
{ 1, 0x47},
{ 1, 0x48},
{ 1, 0x49},
{ 1, 0x4a},
{ 1, 0x4b},
{ 1, 0x4c},
{ 3, 0x02},
{ 1, 0x4d},
{ 1, 0x4e},
{ 1, 0x4f},
{ 1, 0x50},
{ 1, 0x51},
{ 1, 0x52},
{ 1, 0x53},
{ 1, 0x54},
{ 1, 0x55},
{ 1, 0x56},
{ 6, 0x02},
{ 1, 0x57},
{ 5, 0x02},
{ 1, 0x58},
{ 36, 0x02},
{ 1, 0x59},
{ 1, 0x02},
{ 1, 0x5a},
{ 8, 0x02},
{ 1, 0x5b},
{ 1, 0x5c},
{ 7, 0x02},
{ 1, 0x5d},
{ 12, 0x02},
{ 1, 0x5e},
{ 1, 0x5f},
{ 32, 0x02},
{ 1, 0x60},
{ 58, 0x02},
{ 1, 0x61},
{ 18, 0x02},
{ 1, 0x62},
{ 18, 0x02},
{ 1, 0x63},
{ 1, 0x64},
{ 8, 0x02},
{ 1, 0x65},
{ 2, 0x33},
{ 1, 0x66},
{ 1, 0x67},
{ 1, 0x33},
{ 1, 0x68},
{ 1, 0x69},
{ 1, 0x6a},
{ 1, 0x6b},
{ 1, 0x6c},
{ 1, 0x6d},
{ 1, 0x6e},
{ 1, 0x6f},
{ 1, 0x70},
{ 87, 0x02},
{ 1, 0x71},
{ 66, 0x02},
{ 1, 0x72},
{ 1, 0x73},
{ 1, 0x74},
{ 1, 0x75},
{ 1, 0x76},
{ 1, 0x77},
{ 2, 0x02},
{ 1, 0x78},
{ 1, 0x79},
{ 1, 0x7a},
{ 1, 0x02},
{ 1, 0x7b},
{ 1, 0x7c},
{ 1, 0x7d},
{ 1, 0x7e},
{ 1, 0x7f},
{ 1, 0x80},
{ 1, 0x02},
{ 1, 0x81},
{ 1, 0x82},
{ 1, 0x83},
{ 1, 0x84},
{ 1, 0x85},
{ 1, 0x86},
{ 1, 0x02},
{ 2, 0x33},
{ 1, 0x87},
{ 1, 0x02},
{ 1, 0x88},
{ 1, 0x89},
{ 1, 0x8a},
{ 1, 0x8b},
{ 1, 0x8c},
{ 1, 0x8d},
{ 1, 0x8e},
{ 1, 0x8f},
{ 1, 0x90},
{ 1, 0x91},
{ 1, 0x92},
{ 1, 0x02},
{ 1, 0x93},
{ 1, 0x94},
{ 1, 0x95},
{ 1, 0x96},
{ 1, 0x97},
{ 1, 0x98},
{ 1, 0x99},
{ 1, 0x9a},
{ 1, 0x9b},
{ 1, 0x9c},
{ 1, 0x9d},
{ 1, 0x02},
{ 1, 0x9e},
{ 1, 0x9f},
{ 1, 0x02},
{ 1, 0xa0},
{ 1, 0xa1},
{ 1, 0xa2},
{ 1, 0xa3},
{ 1, 0x02},
{ 1, 0xa4},
{ 1, 0xa5},
{ 1, 0xa6},
{ 1, 0xa7},
{ 1, 0xa8},
{ 1, 0xa9},
{ 2, 0x02},
{ 1, 0xaa},
{ 1, 0xab},
{ 1, 0xac},
{ 1, 0xad},
{ 1, 0x02},
{ 1, 0xae},
{ 1, 0x02},
{ 1, 0xaf},
{ 7, 0x33},
{ 1, 0xb0},
{ 1, 0xb1},
{ 1, 0x33},
{ 1, 0xb2},
{ 21, 0x02},
{ 8, 0x33},
{ 1, 0xb3},
{ 31, 0x02},
{ 4, 0x33},
{ 1, 0xb4},
{ 67, 0x02},
{ 4, 0x33},
{ 1, 0xb5},
{ 1, 0xb6},
{ 1, 0xb7},
{ 1, 0xb8},
{ 4, 0x02},
{ 1, 0xb9},
{ 1, 0xba},
{ 1, 0xbb},
{ 1, 0xbc},
{ 47, 0x33},
{ 1, 0x67},
{ 9, 0x33},
{ 1, 0xbd},
{ 1, 0xbe},
{ 69, 0x02},
{ 2, 0x33},
{ 1, 0xbf},
{ 2, 0x33},
{ 1, 0xc0},
{ 18, 0x02},
{ 1, 0xc1},
{ 1, 0xc2},
{ 40, 0x02},
{ 1, 0xc3},
{ 1, 0xc4},
{ 1, 0xc5},
{ 1, 0xc6},
{ 1, 0xc7},
{ 2, 0x02},
{ 1, 0xc8},
{ 3, 0x02},
{ 1, 0xc9},
{ 1, 0xca},
{ 1, 0xcb},
{ 5, 0x33},
{ 1, 0xcc},
{ 10, 0x02},
{ 1, 0xcd},
{ 1, 0x02},
{ 1, 0xce},
{ 2, 0x02},
{ 1, 0xcf},
{ 10, 0x02},
{ 1, 0x33},
{ 1, 0xd0},
{ 1, 0xd1},
{ 5, 0x02},
{ 1, 0xd2},
{ 1, 0xd3},
{ 1, 0xd4},
{ 1, 0x02},
{ 1, 0xd5},
{ 1, 0xd6},
{ 2, 0x02},
{ 1, 0xd7},
{ 1, 0xd8},
{ 1, 0x33},
{ 1, 0xd9},
{ 1, 0xda},
{ 1, 0x02},
{ 7, 0x33},
{ 1, 0xdb},
{ 1, 0xdc},
{ 1, 0xdd},
{ 1, 0xde},
{ 1, 0xdf},
{ 1, 0xe0},
{ 1, 0xe1},
{ 1, 0xe2},
{ 1, 0xe3},
{ 1, 0x33},
{ 1, 0xe4},
{ 8, 0x02},
{ 1, 0xe5},
{ 1, 0xe6},
{ 1, 0x62},
{ 15, 0x02},
{ 1, 0x57},
{ 1, 0xe7},
{ 1, 0x02},
{ 1, 0xe8},
{ 1, 0xe9},
{ 48, 0x02},
{ 1, 0xea},
{ 11, 0x02},
{ 1, 0xeb},
{ 34, 0x02},
{ 1, 0xec},
{ 77, 0x02},
{ 1, 0xed},
{136, 0x02},
{ 1, 0xee},
{ 32, 0x33},
{ 1, 0xef},
{ 1, 0x33},
{ 1, 0xf0},
{ 44, 0x33},
{ 1, 0xf1},
{ 57, 0x33},
{ 1, 0xf2},
{ 25, 0x02},
{ 1, 0xea},
{ 14, 0x02},
{ 38, 0x33},
{ 1, 0xf3},
{255, 0x02},
{255, 0x02},
{255, 0x02},
{255, 0x02},
{255, 0x02},
{255, 0x02},
{255, 0x02},
{255, 0x02},
{255, 0x02},
{255, 0x02},
{255, 0x02},
{255, 0x02},
{255, 0x02},
{255, 0x02},
{255, 0x02},
{255, 0x02},
{255, 0x02},
{255, 0x02},
{255, 0x02},
{255, 0x02},
{255, 0x02},
{240, 0x02},
{ 1, 0x33},
{ 1, 0xf4},
{255, 0x02},
{255, 0x02},
{255, 0x02},
{255, 0x02},
{255, 0x02},
{255, 0x02},
{ 2, 0x02},
{0},
};
static textstartup void _PyUnicode_ChangeIndex_3_2_0_init(void) {
rldecode2(_PyUnicode_ChangeIndex_3_2_0, (void *)_PyUnicode_ChangeIndex_3_2_0_rodata);
}
const void *const _PyUnicode_ChangeIndex_3_2_0_ctor[] initarray = {
_PyUnicode_ChangeIndex_3_2_0_init,
};
unsigned char _PyUnicode_ChangeData_3_2_0[31360];
static const unsigned char _PyUnicode_ChangeData_3_2_0_rodata[1390+1][2] = { /* 8.8648% profit */
{ 43, 0x00},
{ 1, 0x01},
{ 1, 0x00},
{ 1, 0x01},
{ 1, 0x00},
{ 1, 0x02},
{119, 0x00},
{ 1, 0x03},
{ 2, 0x00},
{ 1, 0x04},
{ 2, 0x00},
{ 1, 0x05},
{ 4, 0x00},
{ 1, 0x06},
{ 1, 0x07},
{ 2, 0x00},
{ 1, 0x03},
{ 2, 0x00},
{ 1, 0x08},
{ 1, 0x04},
{230, 0x00},
{ 1, 0x09},
{ 18, 0x00},
{ 28, 0x09},
{ 68, 0x00},
{ 1, 0x04},
{ 25, 0x00},
{ 2, 0x09},
{ 9, 0x00},
{ 2, 0x0a},
{ 11, 0x00},
{ 10, 0x0a},
{ 28, 0x00},
{ 1, 0x0a},
{ 2, 0x00},
{ 17, 0x09},
{ 80, 0x00},
{ 16, 0x09},
{ 16, 0x00},
{ 4, 0x09},
{ 1, 0x0a},
{ 1, 0x00},
{ 2, 0x09},
{ 3, 0x00},
{ 3, 0x09},
{ 1, 0x00},
{ 1, 0x09},
{ 79, 0x00},
{ 1, 0x09},
{ 39, 0x00},
{ 9, 0x09},
{ 7, 0x00},
{ 1, 0x09},
{ 71, 0x00},
{ 1, 0x09},
{ 38, 0x00},
{ 2, 0x09},
{ 2, 0x00},
{ 6, 0x09},
{ 16, 0x00},
{ 32, 0x09},
{ 48, 0x00},
{ 1, 0x09},
{ 39, 0x00},
{ 1, 0x09},
{ 4, 0x00},
{ 3, 0x09},
{ 18, 0x00},
{ 1, 0x09},
{ 23, 0x00},
{ 1, 0x09},
{ 3, 0x00},
{ 1, 0x0b},
{ 6, 0x00},
{ 3, 0x09},
{ 39, 0x00},
{ 1, 0x09},
{ 16, 0x00},
{ 12, 0x09},
{ 1, 0x00},
{ 14, 0x09},
{ 1, 0x00},
{ 1, 0x09},
{ 1, 0x00},
{ 1, 0x09},
{ 1, 0x00},
{ 1, 0x09},
{ 26, 0x00},
{ 5, 0x09},
{ 22, 0x00},
{ 10, 0x09},
{125, 0x00},
{ 1, 0x0c},
{ 1, 0x0d},
{ 15, 0x00},
{ 2, 0x09},
{ 15, 0x00},
{ 1, 0x09},
{ 15, 0x00},
{ 1, 0x0e},
{ 29, 0x00},
{ 3, 0x09},
{ 29, 0x00},
{ 51, 0x09},
{ 64, 0x00},
{ 59, 0x09},
{ 2, 0x00},
{ 49, 0x09},
{ 2, 0x00},
{ 15, 0x09},
{ 1, 0x00},
{ 28, 0x09},
{ 2, 0x00},
{ 1, 0x09},
{ 1, 0x00},
{ 11, 0x09},
{ 53, 0x00},
{ 21, 0x09},
{ 1, 0x00},
{ 18, 0x09},
{ 11, 0x00},
{ 46, 0x09},
{ 3, 0x00},
{ 1, 0x09},
{ 53, 0x00},
{ 2, 0x09},
{ 18, 0x00},
{ 2, 0x09},
{ 5, 0x00},
{ 3, 0x09},
{ 25, 0x00},
{ 16, 0x09},
{ 60, 0x00},
{ 1, 0x09},
{ 16, 0x00},
{ 1, 0x09},
{ 37, 0x00},
{ 1, 0x0f},
{ 1, 0x10},
{ 1, 0x11},
{ 1, 0x12},
{ 1, 0x13},
{ 2, 0x00},
{ 4, 0x09},
{ 2, 0x00},
{ 1, 0x09},
{ 1, 0x00},
{ 1, 0x09},
{ 77, 0x00},
{ 1, 0x09},
{ 35, 0x00},
{ 2, 0x09},
{ 21, 0x00},
{ 1, 0x09},
{ 84, 0x00},
{ 3, 0x09},
{ 12, 0x00},
{ 2, 0x09},
{ 7, 0x00},
{ 7, 0x09},
{ 53, 0x00},
{ 1, 0x09},
{ 14, 0x00},
{ 1, 0x09},
{ 16, 0x00},
{ 1, 0x09},
{ 12, 0x00},
{ 2, 0x09},
{ 13, 0x00},
{ 7, 0x09},
{ 62, 0x00},
{ 1, 0x09},
{ 25, 0x00},
{ 1, 0x09},
{ 21, 0x00},
{ 1, 0x09},
{ 12, 0x00},
{ 8, 0x09},
{ 5, 0x00},
{ 1, 0x09},
{ 3, 0x00},
{ 1, 0x09},
{ 47, 0x00},
{ 1, 0x09},
{ 8, 0x00},
{ 1, 0x09},
{ 26, 0x00},
{ 3, 0x09},
{ 7, 0x00},
{ 2, 0x09},
{ 19, 0x00},
{ 11, 0x09},
{ 2, 0x00},
{ 1, 0x09},
{ 55, 0x00},
{ 2, 0x09},
{ 1, 0x00},
{ 1, 0x14},
{ 6, 0x00},
{ 1, 0x14},
{ 27, 0x00},
{ 2, 0x09},
{ 13, 0x00},
{ 2, 0x09},
{ 13, 0x00},
{ 2, 0x09},
{ 2, 0x00},
{ 1, 0x09},
{ 36, 0x00},
{ 1, 0x09},
{ 16, 0x00},
{ 4, 0x09},
{ 6, 0x00},
{ 1, 0x09},
{ 9, 0x00},
{ 2, 0x09},
{ 4, 0x00},
{ 3, 0x09},
{ 1, 0x00},
{ 8, 0x09},
{ 2, 0x00},
{ 2, 0x09},
{ 12, 0x00},
{ 16, 0x09},
{ 1, 0x00},
{ 1, 0x09},
{100, 0x00},
{ 10, 0x09},
{ 22, 0x00},
{ 1, 0x09},
{ 2, 0x00},
{ 1, 0x09},
{ 2, 0x00},
{ 1, 0x09},
{ 1, 0x00},
{ 6, 0x09},
{ 4, 0x00},
{ 1, 0x09},
{ 7, 0x00},
{ 1, 0x09},
{ 7, 0x00},
{ 2, 0x09},
{ 2, 0x00},
{ 1, 0x09},
{ 13, 0x00},
{ 1, 0x09},
{ 35, 0x00},
{ 2, 0x09},
{ 52, 0x00},
{ 1, 0x03},
{ 37, 0x00},
{ 4, 0x15},
{ 45, 0x00},
{ 2, 0x09},
{ 31, 0x00},
{ 4, 0x09},
{ 62, 0x00},
{ 1, 0x09},
{ 1, 0x00},
{ 11, 0x09},
{ 71, 0x00},
{ 1, 0x09},
{ 5, 0x00},
{ 1, 0x09},
{ 2, 0x00},
{ 1, 0x09},
{ 7, 0x00},
{ 3, 0x09},
{ 4, 0x00},
{ 6, 0x09},
{ 26, 0x00},
{ 70, 0x09},
{ 39, 0x00},
{ 1, 0x09},
{ 5, 0x00},
{ 1, 0x09},
{ 2, 0x00},
{ 41, 0x16},
{ 2, 0x09},
{ 1, 0x00},
{ 4, 0x09},
{ 90, 0x00},
{ 5, 0x09},
{ 68, 0x00},
{ 5, 0x09},
{ 82, 0x00},
{ 6, 0x09},
{ 7, 0x00},
{ 1, 0x09},
{ 63, 0x00},
{ 1, 0x09},
{ 63, 0x00},
{ 1, 0x09},
{ 39, 0x00},
{ 1, 0x09},
{ 31, 0x00},
{ 1, 0x09},
{ 31, 0x00},
{ 1, 0x09},
{ 31, 0x00},
{ 1, 0x09},
{ 15, 0x00},
{ 1, 0x09},
{ 39, 0x00},
{ 1, 0x09},
{ 21, 0x00},
{ 4, 0x09},
{ 8, 0x00},
{ 1, 0x17},
{ 1, 0x18},
{ 1, 0x19},
{ 1, 0x1a},
{ 1, 0x1b},
{ 1, 0x1c},
{ 1, 0x1d},
{ 1, 0x1e},
{ 1, 0x1f},
{ 14, 0x00},
{ 26, 0x09},
{ 6, 0x00},
{ 85, 0x16},
{ 1, 0x09},
{ 2, 0x00},
{ 6, 0x09},
{ 2, 0x00},
{ 1, 0x09},
{236, 0x00},
{ 1, 0x0b},
{ 9, 0x00},
{ 9, 0x09},
{ 27, 0x00},
{ 2, 0x15},
{ 84, 0x00},
{ 8, 0x09},
{ 59, 0x00},
{ 2, 0x20},
{ 39, 0x00},
{ 1, 0x09},
{ 18, 0x00},
{ 10, 0x09},
{126, 0x00},
{ 1, 0x09},
{ 12, 0x00},
{ 2, 0x21},
{ 35, 0x00},
{ 1, 0x09},
{ 5, 0x00},
{ 70, 0x09},
{ 10, 0x00},
{ 31, 0x09},
{ 1, 0x00},
{ 12, 0x09},
{ 4, 0x00},
{ 12, 0x09},
{ 4, 0x00},
{ 1, 0x09},
{ 3, 0x00},
{ 42, 0x09},
{ 2, 0x00},
{ 5, 0x09},
{ 11, 0x00},
{ 44, 0x09},
{ 4, 0x00},
{ 26, 0x09},
{ 6, 0x00},
{ 11, 0x09},
{ 3, 0x00},
{ 62, 0x09},
{ 2, 0x00},
{ 65, 0x09},
{ 1, 0x00},
{ 29, 0x09},
{ 2, 0x00},
{ 11, 0x09},
{ 6, 0x00},
{ 10, 0x09},
{ 6, 0x00},
{ 14, 0x09},
{ 2, 0x00},
{ 17, 0x09},
{ 63, 0x00},
{ 76, 0x09},
{ 4, 0x00},
{ 45, 0x09},
{ 3, 0x00},
{116, 0x09},
{ 8, 0x00},
{ 60, 0x09},
{ 3, 0x00},
{ 15, 0x09},
{ 3, 0x00},
{ 60, 0x09},
{ 7, 0x00},
{ 43, 0x09},
{ 2, 0x00},
{ 11, 0x09},
{ 8, 0x00},
{ 43, 0x09},
{ 5, 0x00},
{250, 0x09},
{ 1, 0x00},
{ 5, 0x09},
{ 28, 0x00},
{ 4, 0x09},
{ 90, 0x00},
{ 6, 0x09},
{ 11, 0x00},
{ 1, 0x22},
{ 35, 0x00},
{ 1, 0x23},
{ 20, 0x00},
{ 1, 0x24},
{ 14, 0x00},
{ 4, 0x09},
{ 1, 0x00},
{ 7, 0x09},
{ 5, 0x00},
{ 1, 0x09},
{ 1, 0x00},
{ 4, 0x09},
{ 6, 0x00},
{ 1, 0x25},
{ 1, 0x04},
{ 2, 0x00},
{ 1, 0x26},
{ 1, 0x27},
{ 1, 0x28},
{ 1, 0x29},
{ 1, 0x2a},
{ 1, 0x2b},
{ 2, 0x01},
{ 3, 0x00},
{ 1, 0x04},
{ 1, 0x25},
{ 1, 0x08},
{ 1, 0x06},
{ 1, 0x07},
{ 1, 0x26},
{ 1, 0x27},
{ 1, 0x28},
{ 1, 0x29},
{ 1, 0x2a},
{ 1, 0x2b},
{ 2, 0x01},
{ 4, 0x00},
{ 13, 0x09},
{ 21, 0x00},
{ 14, 0x09},
{ 43, 0x00},
{ 6, 0x09},
{ 39, 0x00},
{ 1, 0x03},
{ 25, 0x00},
{ 1, 0x2c},
{ 8, 0x00},
{ 2, 0x09},
{ 15, 0x00},
{ 7, 0x09},
{ 48, 0x00},
{ 1, 0x2d},
{ 8, 0x09},
{134, 0x00},
{ 1, 0x01},
{117, 0x00},
{ 4, 0x2e},
{ 14, 0x00},
{ 2, 0x2f},
{152, 0x00},
{ 1, 0x30},
{ 1, 0x31},
{ 1, 0x0b},
{ 24, 0x00},
{ 49, 0x09},
{ 96, 0x00},
{ 40, 0x32},
{ 98, 0x00},
{ 1, 0x32},
{ 20, 0x00},
{ 1, 0x09},
{125, 0x00},
{ 2, 0x2f},
{ 21, 0x00},
{ 2, 0x09},
{ 2, 0x00},
{ 1, 0x09},
{ 47, 0x00},
{ 12, 0x2f},
{ 42, 0x00},
{ 2, 0x09},
{ 10, 0x00},
{119, 0x09},
{ 4, 0x00},
{ 1, 0x09},
{ 4, 0x00},
{ 2, 0x09},
{ 28, 0x00},
{ 1, 0x09},
{ 35, 0x00},
{ 1, 0x09},
{ 1, 0x00},
{ 1, 0x09},
{ 4, 0x00},
{ 3, 0x09},
{ 1, 0x00},
{ 1, 0x09},
{ 7, 0x00},
{ 2, 0x09},
{ 52, 0x00},
{ 3, 0x09},
{ 24, 0x00},
{ 1, 0x09},
{ 14, 0x00},
{ 17, 0x09},
{ 28, 0x00},
{ 4, 0x09},
{ 16, 0x00},
{128, 0x24},
{ 33, 0x00},
{ 1, 0x33},
{ 94, 0x00},
{116, 0x09},
{ 2, 0x00},
{ 32, 0x09},
{ 1, 0x00},
{152, 0x09},
{ 1, 0x00},
{ 47, 0x09},
{ 1, 0x00},
{148, 0x09},
{ 5, 0x00},
{ 45, 0x09},
{ 1, 0x00},
{ 1, 0x09},
{ 5, 0x00},
{ 1, 0x09},
{ 2, 0x00},
{ 56, 0x09},
{ 7, 0x00},
{ 2, 0x09},
{ 14, 0x00},
{ 24, 0x09},
{ 9, 0x00},
{ 7, 0x09},
{ 1, 0x00},
{ 7, 0x09},
{ 1, 0x00},
{ 7, 0x09},
{ 1, 0x00},
{ 7, 0x09},
{ 1, 0x00},
{ 7, 0x09},
{ 1, 0x00},
{ 7, 0x09},
{ 1, 0x00},
{ 7, 0x09},
{ 1, 0x00},
{ 7, 0x09},
{ 1, 0x00},
{115, 0x09},
{ 91, 0x00},
{ 2, 0x34},
{203, 0x00},
{ 1, 0x35},
{ 49, 0x00},
{ 3, 0x09},
{136, 0x00},
{ 44, 0x09},
{ 57, 0x00},
{ 2, 0x09},
{ 37, 0x00},
{ 13, 0x09},
{ 43, 0x00},
{ 3, 0x09},
{ 77, 0x00},
{ 4, 0x09},
{ 47, 0x00},
{ 1, 0x09},
{119, 0x00},
{ 4, 0x09},
{ 99, 0x00},
{ 2, 0x09},
{ 31, 0x00},
{ 1, 0x09},
{ 5, 0x00},
{ 1, 0x13},
{125, 0x00},
{ 1, 0x13},
{166, 0x00},
{ 1, 0x13},
{162, 0x00},
{ 1, 0x13},
{104, 0x00},
{ 74, 0x09},
{ 22, 0x00},
{ 1, 0x13},
{ 21, 0x00},
{ 1, 0x36},
{ 19, 0x00},
{ 1, 0x13},
{ 39, 0x00},
{ 1, 0x13},
{ 91, 0x00},
{ 1, 0x13},
{ 7, 0x00},
{ 1, 0x13},
{119, 0x00},
{ 1, 0x13},
{ 78, 0x00},
{ 1, 0x37},
{230, 0x00},
{ 1, 0x13},
{131, 0x00},
{ 1, 0x13},
{ 7, 0x00},
{ 1, 0x13},
{172, 0x00},
{ 1, 0x13},
{109, 0x00},
{ 1, 0x13},
{132, 0x00},
{ 87, 0x09},
{ 24, 0x00},
{ 1, 0x16},
{186, 0x00},
{ 92, 0x09},
{ 20, 0x00},
{184, 0x09},
{ 8, 0x00},
{ 64, 0x09},
{ 2, 0x00},
{ 9, 0x09},
{ 42, 0x00},
{ 56, 0x09},
{ 3, 0x00},
{ 10, 0x09},
{ 6, 0x00},
{ 56, 0x09},
{ 8, 0x00},
{ 70, 0x09},
{ 8, 0x00},
{ 12, 0x09},
{ 6, 0x00},
{116, 0x09},
{ 11, 0x00},
{ 30, 0x09},
{ 3, 0x00},
{ 78, 0x09},
{ 1, 0x00},
{ 11, 0x09},
{ 4, 0x00},
{ 33, 0x09},
{ 1, 0x00},
{ 55, 0x09},
{ 9, 0x00},
{ 14, 0x09},
{ 2, 0x00},
{ 10, 0x09},
{ 2, 0x00},
{103, 0x09},
{ 24, 0x00},
{ 28, 0x09},
{ 10, 0x00},
{ 6, 0x09},
{ 2, 0x00},
{ 6, 0x09},
{ 2, 0x00},
{ 6, 0x09},
{ 9, 0x00},
{ 7, 0x09},
{ 1, 0x00},
{ 7, 0x09},
{ 1, 0x00},
{ 60, 0x09},
{ 4, 0x00},
{126, 0x09},
{ 2, 0x00},
{ 10, 0x09},
{ 54, 0x00},
{ 23, 0x09},
{ 4, 0x00},
{ 49, 0x09},
{111, 0x00},
{ 1, 0x13},
{ 7, 0x00},
{ 1, 0x13},
{ 4, 0x00},
{ 1, 0x13},
{ 57, 0x00},
{ 1, 0x13},
{ 30, 0x00},
{ 1, 0x13},
{ 1, 0x00},
{ 1, 0x13},
{ 41, 0x00},
{ 1, 0x13},
{ 48, 0x00},
{ 2, 0x09},
{ 59, 0x00},
{ 3, 0x09},
{ 2, 0x00},
{106, 0x09},
{ 79, 0x00},
{ 1, 0x01},
{136, 0x00},
{ 16, 0x09},
{124, 0x00},
{ 1, 0x30},
{ 1, 0x31},
{189, 0x00},
{ 1, 0x09},
{ 18, 0x00},
{ 10, 0x09},
{ 10, 0x00},
{ 12, 0x09},
{ 23, 0x00},
{ 2, 0x09},
{ 16, 0x00},
{ 6, 0x15},
{ 3, 0x00},
{ 2, 0x01},
{ 2, 0x15},
{ 37, 0x00},
{ 1, 0x01},
{ 1, 0x00},
{ 1, 0x01},
{ 1, 0x00},
{ 1, 0x02},
{ 85, 0x00},
{ 1, 0x35},
{147, 0x00},
{ 3, 0x0e},
{ 4, 0x00},
{ 12, 0x09},
{ 1, 0x00},
{ 26, 0x09},
{ 1, 0x00},
{ 19, 0x09},
{ 1, 0x00},
{ 2, 0x09},
{ 1, 0x00},
{ 15, 0x09},
{ 2, 0x00},
{ 14, 0x09},
{ 34, 0x00},
{123, 0x09},
{ 5, 0x00},
{ 3, 0x09},
{ 4, 0x00},
{ 45, 0x09},
{ 3, 0x00},
{ 88, 0x09},
{ 1, 0x00},
{ 13, 0x09},
{ 3, 0x00},
{ 1, 0x09},
{ 47, 0x00},
{ 46, 0x09},
{ 2, 0x00},
{ 29, 0x09},
{ 3, 0x00},
{ 49, 0x09},
{ 15, 0x00},
{ 28, 0x09},
{ 35, 0x00},
{ 1, 0x09},
{ 13, 0x00},
{ 3, 0x09},
{ 17, 0x00},
{ 1, 0x38},
{ 8, 0x00},
{ 1, 0x13},
{ 5, 0x00},
{ 43, 0x09},
{ 5, 0x00},
{ 30, 0x09},
{ 1, 0x00},
{ 37, 0x09},
{ 4, 0x00},
{ 14, 0x09},
{ 80, 0x00},
{ 2, 0x09},
{ 38, 0x00},
{ 80, 0x09},
{ 2, 0x00},
{ 10, 0x09},
{ 6, 0x00},
{ 36, 0x09},
{ 4, 0x00},
{ 36, 0x09},
{ 4, 0x00},
{ 40, 0x09},
{ 8, 0x00},
{ 52, 0x09},
{ 11, 0x00},
{ 1, 0x09},
{ 16, 0x00},
{ 55, 0x09},
{ 9, 0x00},
{ 22, 0x09},
{ 10, 0x00},
{ 8, 0x09},
{ 24, 0x00},
{ 6, 0x09},
{ 2, 0x00},
{ 1, 0x09},
{ 1, 0x00},
{ 44, 0x09},
{ 1, 0x00},
{ 2, 0x09},
{ 3, 0x00},
{ 1, 0x09},
{ 2, 0x00},
{ 23, 0x09},
{ 1, 0x00},
{ 72, 0x09},
{ 8, 0x00},
{ 9, 0x09},
{ 48, 0x00},
{ 19, 0x09},
{ 1, 0x00},
{ 2, 0x09},
{ 5, 0x00},
{ 33, 0x09},
{ 3, 0x00},
{ 27, 0x09},
{ 5, 0x00},
{ 1, 0x09},
{ 64, 0x00},
{ 56, 0x09},
{ 4, 0x00},
{ 20, 0x09},
{ 2, 0x00},
{ 50, 0x09},
{ 1, 0x00},
{ 2, 0x09},
{ 5, 0x00},
{ 8, 0x09},
{ 1, 0x00},
{ 3, 0x09},
{ 1, 0x00},
{ 29, 0x09},
{ 2, 0x00},
{ 3, 0x09},
{ 4, 0x00},
{ 10, 0x09},
{ 7, 0x00},
{ 9, 0x09},
{ 7, 0x00},
{ 64, 0x09},
{ 32, 0x00},
{ 39, 0x09},
{ 4, 0x00},
{ 12, 0x09},
{ 9, 0x00},
{ 54, 0x09},
{ 3, 0x00},
{ 29, 0x09},
{ 2, 0x00},
{ 27, 0x09},
{ 5, 0x00},
{ 26, 0x09},
{ 7, 0x00},
{ 4, 0x09},
{ 12, 0x00},
{ 7, 0x09},
{ 80, 0x00},
{ 73, 0x09},
{ 55, 0x00},
{ 51, 0x09},
{ 13, 0x00},
{ 51, 0x09},
{ 7, 0x00},
{ 46, 0x09},
{ 8, 0x00},
{ 10, 0x09},
{166, 0x00},
{ 31, 0x09},
{ 1, 0x00},
{ 42, 0x09},
{ 1, 0x00},
{ 3, 0x09},
{ 2, 0x00},
{ 2, 0x09},
{ 78, 0x00},
{ 40, 0x09},
{ 8, 0x00},
{ 42, 0x09},
{ 86, 0x00},
{ 28, 0x09},
{ 20, 0x00},
{ 23, 0x09},
{ 9, 0x00},
{ 78, 0x09},
{ 4, 0x00},
{ 30, 0x09},
{ 15, 0x00},
{ 67, 0x09},
{ 11, 0x00},
{ 1, 0x09},
{ 2, 0x00},
{ 25, 0x09},
{ 7, 0x00},
{ 10, 0x09},
{ 6, 0x00},
{ 53, 0x09},
{ 1, 0x00},
{ 18, 0x09},
{ 8, 0x00},
{ 39, 0x09},
{ 9, 0x00},
{ 96, 0x09},
{ 1, 0x00},
{ 20, 0x09},
{ 11, 0x00},
{ 18, 0x09},
{ 1, 0x00},
{ 44, 0x09},
{ 65, 0x00},
{ 7, 0x09},
{ 1, 0x00},
{ 1, 0x09},
{ 1, 0x00},
{ 4, 0x09},
{ 1, 0x00},
{ 15, 0x09},
{ 1, 0x00},
{ 11, 0x09},
{ 6, 0x00},
{ 59, 0x09},
{ 5, 0x00},
{ 10, 0x09},
{ 6, 0x00},
{ 4, 0x09},
{ 1, 0x00},
{ 8, 0x09},
{ 2, 0x00},
{ 2, 0x09},
{ 2, 0x00},
{ 22, 0x09},
{ 1, 0x00},
{ 7, 0x09},
{ 1, 0x00},
{ 2, 0x09},
{ 1, 0x00},
{ 5, 0x09},
{ 1, 0x00},
{ 10, 0x09},
{ 2, 0x00},
{ 2, 0x09},
{ 2, 0x00},
{ 3, 0x09},
{ 2, 0x00},
{ 1, 0x09},
{ 6, 0x00},
{ 1, 0x09},
{ 5, 0x00},
{ 7, 0x09},
{ 2, 0x00},
{ 7, 0x09},
{ 3, 0x00},
{ 5, 0x09},
{ 11, 0x00},
{ 92, 0x09},
{ 1, 0x00},
{ 5, 0x09},
{ 30, 0x00},
{ 72, 0x09},
{ 8, 0x00},
{ 10, 0x09},
{ 38, 0x00},
{ 54, 0x09},
{ 2, 0x00},
{ 38, 0x09},
{ 34, 0x00},
{ 69, 0x09},
{ 11, 0x00},
{ 10, 0x09},
{ 6, 0x00},
{ 13, 0x09},
{ 19, 0x00},
{ 57, 0x09},
{ 7, 0x00},
{ 10, 0x09},
{ 54, 0x00},
{ 27, 0x09},
{ 2, 0x00},
{ 15, 0x09},
{ 4, 0x00},
{ 16, 0x09},
{ 64, 0x00},
{ 60, 0x09},
{100, 0x00},
{ 83, 0x09},
{ 12, 0x00},
{ 8, 0x09},
{ 2, 0x00},
{ 1, 0x09},
{ 2, 0x00},
{ 8, 0x09},
{ 1, 0x00},
{ 2, 0x09},
{ 1, 0x00},
{ 30, 0x09},
{ 1, 0x00},
{ 2, 0x09},
{ 2, 0x00},
{ 12, 0x09},
{ 9, 0x00},
{ 10, 0x09},
{ 70, 0x00},
{ 8, 0x09},
{ 2, 0x00},
{ 46, 0x09},
{ 2, 0x00},
{ 11, 0x09},
{ 27, 0x00},
{ 72, 0x09},
{ 8, 0x00},
{ 83, 0x09},
{ 29, 0x00},
{ 57, 0x09},
{ 7, 0x00},
{ 9, 0x09},
{ 1, 0x00},
{ 45, 0x09},
{ 1, 0x00},
{ 14, 0x09},
{ 10, 0x00},
{ 29, 0x09},
{ 3, 0x00},
{ 32, 0x09},
{ 2, 0x00},
{ 22, 0x09},
{ 1, 0x00},
{ 14, 0x09},
{ 73, 0x00},
{ 7, 0x09},
{ 1, 0x00},
{ 2, 0x09},
{ 1, 0x00},
{ 44, 0x09},
{ 3, 0x00},
{ 1, 0x09},
{ 1, 0x00},
{ 2, 0x09},
{ 1, 0x00},
{ 9, 0x09},
{ 8, 0x00},
{ 10, 0x09},
{ 6, 0x00},
{ 6, 0x09},
{ 1, 0x00},
{ 2, 0x09},
{ 1, 0x00},
{ 37, 0x09},
{ 1, 0x00},
{ 2, 0x09},
{ 1, 0x00},
{ 6, 0x09},
{ 7, 0x00},
{ 10, 0x09},
{182, 0x00},
{ 25, 0x09},
{ 55, 0x00},
{ 1, 0x09},
{ 15, 0x00},
{ 50, 0x09},
{ 13, 0x00},
{ 27, 0x09},
{102, 0x00},
{111, 0x09},
{ 1, 0x00},
{ 5, 0x09},
{ 11, 0x00},
{ 68, 0x09},
{ 60, 0x00},
{ 47, 0x09},
{ 1, 0x00},
{ 9, 0x09},
{ 71, 0x00},
{ 71, 0x09},
{ 57, 0x00},
{ 57, 0x09},
{ 7, 0x00},
{ 31, 0x09},
{ 1, 0x00},
{ 10, 0x09},
{ 4, 0x00},
{ 2, 0x09},
{ 96, 0x00},
{ 30, 0x09},
{ 2, 0x00},
{ 6, 0x09},
{ 10, 0x00},
{ 70, 0x09},
{ 10, 0x00},
{ 10, 0x09},
{ 1, 0x00},
{ 7, 0x09},
{ 1, 0x00},
{ 21, 0x09},
{ 5, 0x00},
{ 19, 0x09},
{176, 0x00},
{ 91, 0x09},
{101, 0x00},
{ 75, 0x09},
{ 4, 0x00},
{ 57, 0x09},
{ 7, 0x00},
{ 17, 0x09},
{ 64, 0x00},
{ 5, 0x09},
{ 11, 0x00},
{ 2, 0x09},
{ 14, 0x00},
{ 86, 0x09},
{ 42, 0x00},
{ 9, 0x09},
{119, 0x00},
{ 31, 0x09},
{ 49, 0x00},
{ 3, 0x09},
{ 17, 0x00},
{ 4, 0x09},
{ 8, 0x00},
{140, 0x09},
{ 4, 0x00},
{107, 0x09},
{ 5, 0x00},
{ 13, 0x09},
{ 3, 0x00},
{ 9, 0x09},
{ 7, 0x00},
{ 10, 0x09},
{ 2, 0x00},
{ 8, 0x09},
{133, 0x00},
{ 1, 0x09},
{180, 0x00},
{ 11, 0x09},
{ 23, 0x00},
{ 70, 0x09},
{154, 0x00},
{ 20, 0x09},
{ 12, 0x00},
{ 87, 0x09},
{ 9, 0x00},
{ 25, 0x09},
{ 72, 0x00},
{ 1, 0x09},
{ 98, 0x00},
{ 2, 0x09},
{ 53, 0x00},
{ 1, 0x39},
{ 57, 0x00},
{ 1, 0x39},
{ 57, 0x00},
{ 1, 0x39},
{ 57, 0x00},
{ 1, 0x39},
{ 57, 0x00},
{ 1, 0x39},
{ 6, 0x00},
{ 2, 0x09},
{ 52, 0x00},
{ 12, 0x09},
{ 15, 0x00},
{ 5, 0x09},
{ 1, 0x00},
{ 15, 0x09},
{ 80, 0x00},
{ 7, 0x09},
{ 1, 0x00},
{ 17, 0x09},
{ 2, 0x00},
{ 7, 0x09},
{ 1, 0x00},
{ 2, 0x09},
{ 1, 0x00},
{ 5, 0x09},
{ 85, 0x00},
{ 45, 0x09},
{ 3, 0x00},
{ 14, 0x09},
{ 2, 0x00},
{ 10, 0x09},
{ 4, 0x00},
{ 2, 0x09},
{112, 0x00},
{ 58, 0x09},
{ 5, 0x00},
{ 70, 0x09},
{ 2, 0x00},
{ 16, 0x09},
{ 41, 0x00},
{ 76, 0x09},
{ 4, 0x00},
{ 10, 0x09},
{ 4, 0x00},
{ 2, 0x09},
{145, 0x00},
{ 68, 0x09},
{ 76, 0x00},
{ 61, 0x09},
{ 66, 0x00},
{ 4, 0x09},
{ 1, 0x00},
{ 27, 0x09},
{ 1, 0x00},
{ 2, 0x09},
{ 1, 0x00},
{ 1, 0x09},
{ 2, 0x00},
{ 1, 0x09},
{ 1, 0x00},
{ 10, 0x09},
{ 1, 0x00},
{ 4, 0x09},
{ 1, 0x00},
{ 1, 0x09},
{ 1, 0x00},
{ 1, 0x09},
{ 6, 0x00},
{ 1, 0x09},
{ 4, 0x00},
{ 1, 0x09},
{ 1, 0x00},
{ 1, 0x09},
{ 1, 0x00},
{ 1, 0x09},
{ 1, 0x00},
{ 3, 0x09},
{ 1, 0x00},
{ 2, 0x09},
{ 1, 0x00},
{ 1, 0x09},
{ 2, 0x00},
{ 1, 0x09},
{ 1, 0x00},
{ 1, 0x09},
{ 1, 0x00},
{ 1, 0x09},
{ 1, 0x00},
{ 1, 0x09},
{ 1, 0x00},
{ 1, 0x09},
{ 1, 0x00},
{ 2, 0x09},
{ 1, 0x00},
{ 1, 0x09},
{ 2, 0x00},
{ 4, 0x09},
{ 1, 0x00},
{ 7, 0x09},
{ 1, 0x00},
{ 4, 0x09},
{ 1, 0x00},
{ 4, 0x09},
{ 1, 0x00},
{ 1, 0x09},
{ 1, 0x00},
{ 10, 0x09},
{ 1, 0x00},
{ 17, 0x09},
{ 5, 0x00},
{ 3, 0x09},
{ 1, 0x00},
{ 5, 0x09},
{ 1, 0x00},
{ 17, 0x09},
{ 52, 0x00},
{ 2, 0x09},
{ 14, 0x00},
{ 44, 0x09},
{ 4, 0x00},
{100, 0x09},
{ 12, 0x00},
{ 15, 0x09},
{ 2, 0x00},
{ 15, 0x09},
{ 1, 0x00},
{ 15, 0x09},
{ 1, 0x00},
{ 37, 0x09},
{ 10, 0x00},
{ 46, 0x09},
{ 56, 0x00},
{ 29, 0x09},
{ 13, 0x00},
{ 44, 0x09},
{ 4, 0x00},
{ 9, 0x09},
{ 7, 0x00},
{ 2, 0x09},
{ 14, 0x00},
{ 6, 0x09},
{ 26, 0x00},
{ 88, 0x09},
{ 8, 0x00},
{ 13, 0x09},
{ 3, 0x00},
{ 13, 0x09},
{ 3, 0x00},
{116, 0x09},
{ 12, 0x00},
{ 89, 0x09},
{ 7, 0x00},
{ 12, 0x09},
{ 20, 0x00},
{ 12, 0x09},
{ 4, 0x00},
{ 56, 0x09},
{ 8, 0x00},
{ 10, 0x09},
{ 6, 0x00},
{ 40, 0x09},
{ 8, 0x00},
{ 30, 0x09},
{ 2, 0x00},
{ 2, 0x09},
{ 78, 0x00},
{121, 0x09},
{ 1, 0x00},
{ 82, 0x09},
{ 1, 0x00},
{135, 0x09},
{ 12, 0x00},
{ 14, 0x09},
{ 2, 0x00},
{ 5, 0x09},
{ 3, 0x00},
{ 3, 0x09},
{ 5, 0x00},
{ 7, 0x09},
{ 9, 0x00},
{ 25, 0x09},
{ 7, 0x00},
{ 7, 0x09},
{ 9, 0x00},
{ 3, 0x09},
{ 13, 0x00},
{ 7, 0x09},
{ 41, 0x00},
{ 19, 0x09},
{ 1, 0x00},
{ 55, 0x09},
{ 37, 0x00},
{ 10, 0x09},
{ 7, 0x00},
{ 1, 0x13},
{ 98, 0x00},
{ 1, 0x13},
{125, 0x00},
{ 1, 0x13},
{ 32, 0x00},
{ 1, 0x13},
{ 8, 0x00},
{ 1, 0x13},
{ 15, 0x00},
{ 1, 0x13},
{205, 0x00},
{ 1, 0x13},
{ 18, 0x00},
{ 1, 0x13},
{ 27, 0x00},
{ 1, 0x13},
{118, 0x00},
{ 1, 0x13},
{135, 0x00},
{ 1, 0x13},
{130, 0x00},
{ 1, 0x13},
{209, 0x00},
{ 1, 0x13},
{105, 0x00},
{ 7, 0x09},
{ 34, 0x00},
{ 53, 0x09},
{ 11, 0x00},
{ 94, 0x09},
{ 2, 0x00},
{130, 0x09},
{ 14, 0x00},
{177, 0x09},
{ 31, 0x00},
{ 75, 0x09},
{ 53, 0x00},
{112, 0x09},
{ 16, 0x00},
{0},
};
static textstartup void _PyUnicode_ChangeData_3_2_0_init(void) {
rldecode2(_PyUnicode_ChangeData_3_2_0, (void *)_PyUnicode_ChangeData_3_2_0_rodata);
}
const void *const _PyUnicode_ChangeData_3_2_0_ctor[] initarray = {
_PyUnicode_ChangeData_3_2_0_init,
};
const _PyUnicode_ChangeRecord *_PyUnicode_GetChange_3_2_0(Py_UCS4 n)
{
int i;
if (n >= 0x110000) {
i = 0;
} else {
i = _PyUnicode_ChangeIndex_3_2_0[n>>7];
i = _PyUnicode_ChangeData_3_2_0[(i<<7)+(n & 127)];
}
return _PyUnicode_ChangeRecords_3_2_0 + i;
}
Py_UCS4 _PyUnicode_Normalization_3_2_0(Py_UCS4 n)
{
switch(n) {
case 0x2f868:
return 0x2136A;
case 0x2f874:
return 0x5F33;
case 0x2f91f:
return 0x43AB;
case 0x2f95f:
return 0x7AAE;
case 0x2f9bf:
return 0x4D57;
default:
return 0;
}
}
| 33,384 | 1,873 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Modules/unicodedata_nfclast.c | #include "libc/nexgen32e/kompressor.h"
#include "third_party/python/Modules/unicodedata.h"
/* clang-format off */
/* GENERATED BY third_party/python/Tools/unicode/makeunicodedata.py 3.2 */
const _PyUnicode_Reindex _PyUnicode_NfcLast[] = {
{0x00300, 4, 0},
{0x00306, 6, 5},
{0x0030f, 0, 12},
{0x00311, 0, 13},
{0x00313, 1, 14},
{0x0031b, 0, 16},
{0x00323, 5, 17},
{0x0032d, 1, 23},
{0x00330, 1, 25},
{0x00338, 0, 27},
{0x00342, 0, 28},
{0x00345, 0, 29},
{0x00653, 2, 30},
{0x0093c, 0, 33},
{0x009be, 0, 34},
{0x009d7, 0, 35},
{0x00b3e, 0, 36},
{0x00b56, 1, 37},
{0x00bbe, 0, 39},
{0x00bd7, 0, 40},
{0x00c56, 0, 41},
{0x00cc2, 0, 42},
{0x00cd5, 1, 43},
{0x00d3e, 0, 45},
{0x00d57, 0, 46},
{0x00dca, 0, 47},
{0x00dcf, 0, 48},
{0x00ddf, 0, 49},
{0x0102e, 0, 50},
{0x01b35, 0, 51},
{0x03099, 1, 52},
{0x110ba, 0, 54},
{0x11127, 0, 55},
{0x1133e, 0, 56},
{0x11357, 0, 57},
{0x114b0, 0, 58},
{0x114ba, 0, 59},
{0x114bd, 0, 60},
{0x115af, 0, 61},
{0x11930, 0, 62},
{0}
};
| 1,252 | 50 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Modules/syslogmodule.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:8;coding:utf-8 -*-â
âvi: set net ft=c ts=4 sts=4 sw=4 fenc=utf-8 :viâ
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ¡
â Python 3 â
â https://docs.python.org/3/license.html â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
#include "libc/sock/syslog.h"
#include "libc/sysv/consts/log.h"
#include "third_party/python/Include/ceval.h"
#include "third_party/python/Include/import.h"
#include "third_party/python/Include/listobject.h"
#include "third_party/python/Include/longobject.h"
#include "third_party/python/Include/modsupport.h"
#include "third_party/python/Include/object.h"
#include "third_party/python/Include/osdefs.h"
#include "third_party/python/Include/pyerrors.h"
#include "third_party/python/Include/sysmodule.h"
#include "third_party/python/Include/tupleobject.h"
#include "third_party/python/Include/unicodeobject.h"
#include "third_party/python/Include/yoink.h"
/* clang-format off */
PYTHON_PROVIDE("syslog");
PYTHON_PROVIDE("syslog.LOG_ALERT");
PYTHON_PROVIDE("syslog.LOG_AUTH");
PYTHON_PROVIDE("syslog.LOG_CONS");
PYTHON_PROVIDE("syslog.LOG_CRIT");
PYTHON_PROVIDE("syslog.LOG_CRON");
PYTHON_PROVIDE("syslog.LOG_DAEMON");
PYTHON_PROVIDE("syslog.LOG_DEBUG");
PYTHON_PROVIDE("syslog.LOG_EMERG");
PYTHON_PROVIDE("syslog.LOG_ERR");
PYTHON_PROVIDE("syslog.LOG_INFO");
PYTHON_PROVIDE("syslog.LOG_KERN");
PYTHON_PROVIDE("syslog.LOG_LOCAL0");
PYTHON_PROVIDE("syslog.LOG_LOCAL1");
PYTHON_PROVIDE("syslog.LOG_LOCAL2");
PYTHON_PROVIDE("syslog.LOG_LOCAL3");
PYTHON_PROVIDE("syslog.LOG_LOCAL4");
PYTHON_PROVIDE("syslog.LOG_LOCAL5");
PYTHON_PROVIDE("syslog.LOG_LOCAL6");
PYTHON_PROVIDE("syslog.LOG_LOCAL7");
PYTHON_PROVIDE("syslog.LOG_LPR");
PYTHON_PROVIDE("syslog.LOG_MAIL");
PYTHON_PROVIDE("syslog.LOG_MASK");
PYTHON_PROVIDE("syslog.LOG_NDELAY");
PYTHON_PROVIDE("syslog.LOG_NEWS");
PYTHON_PROVIDE("syslog.LOG_NOTICE");
PYTHON_PROVIDE("syslog.LOG_NOWAIT");
PYTHON_PROVIDE("syslog.LOG_ODELAY");
PYTHON_PROVIDE("syslog.LOG_PERROR");
PYTHON_PROVIDE("syslog.LOG_PID");
PYTHON_PROVIDE("syslog.LOG_SYSLOG");
PYTHON_PROVIDE("syslog.LOG_UPTO");
PYTHON_PROVIDE("syslog.LOG_USER");
PYTHON_PROVIDE("syslog.LOG_UUCP");
PYTHON_PROVIDE("syslog.LOG_WARNING");
PYTHON_PROVIDE("syslog.closelog");
PYTHON_PROVIDE("syslog.openlog");
PYTHON_PROVIDE("syslog.setlogmask");
PYTHON_PROVIDE("syslog.syslog");
asm(".ident\t\"\\n\\n\
syslogmodule (mit)\\n\
Copyright 1994 by Lance Ellinghouse\\n\
Cathedral City, California Republic, United States of America\"");
asm(".include \"libc/disclaimer.inc\"");
/***********************************************************
Copyright 1994 by Lance Ellinghouse,
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,
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 Lance Ellinghouse
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
WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
******************************************************************/
/******************************************************************
Revision history:
2010/04/20 (Sean Reifschneider)
- Use basename(sys.argv[0]) for the default "ident".
- Arguments to openlog() are now keyword args and are all optional.
- syslog() calls openlog() if it hasn't already been called.
1998/04/28 (Sean Reifschneider)
- When facility not specified to syslog() method, use default from openlog()
(This is how it was claimed to work in the documentation)
- Potential resource leak of o_ident, now cleaned up in closelog()
- Minor comment accuracy fix.
95/06/29 (Steve Clift)
- Changed arg parsing to use PyArg_ParseTuple.
- Added PyErr_Clear() call(s) where needed.
- Fix core dumps if user message contains format specifiers.
- Change openlog arg defaults to match normal syslog behavior.
- Plug memory leak in openlog().
- Fix setlogmask() to return previous mask value.
******************************************************************/
/* syslog module */
/* only one instance, only one syslog, so globals should be ok */
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, scriptlen;
PyObject *scriptobj;
Py_ssize_t slash;
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 (!PyUnicode_Check(scriptobj)) {
return(NULL);
}
scriptlen = PyUnicode_GET_LENGTH(scriptobj);
if (scriptlen == 0) {
return(NULL);
}
slash = PyUnicode_FindChar(scriptobj, SEP, 0, scriptlen, -1);
if (slash == -2)
return NULL;
if (slash != -1) {
return PyUnicode_Substring(scriptobj, slash, scriptlen);
} else {
Py_INCREF(scriptobj);
return(scriptobj);
}
return(NULL);
}
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};
char *ident = NULL;
if (!PyArg_ParseTupleAndKeywords(args, kwds,
"|Ull:openlog", keywords, &new_S_ident_o, &logopt, &facility))
return NULL;
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();
}
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]).
*/
if (S_ident_o) {
ident = PyUnicode_AsUTF8(S_ident_o);
if (ident == NULL)
return NULL;
}
openlog(ident, logopt, facility);
S_log_open = 1;
Py_INCREF(Py_None);
return Py_None;
}
static PyObject *
syslog_syslog(PyObject * self, PyObject * args)
{
PyObject *message_object;
const char *message;
int priority = LOG_INFO;
if (!PyArg_ParseTuple(args, "iU;[priority,] message string",
&priority, &message_object)) {
PyErr_Clear();
if (!PyArg_ParseTuple(args, "U;[priority,] message string",
&message_object))
return NULL;
}
message = PyUnicode_AsUTF8(message_object);
if (message == NULL)
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_RETURN_NONE;
}
static PyObject *
syslog_closelog(PyObject *self, PyObject *unused)
{
if (S_log_open) {
closelog();
Py_CLEAR(S_ident_o);
S_log_open = 0;
}
Py_INCREF(Py_None);
return Py_None;
}
static PyObject *
syslog_setlogmask(PyObject *self, PyObject *args)
{
long maskpri, omaskpri;
if (!PyArg_ParseTuple(args, "l;mask for priority", &maskpri))
return NULL;
omaskpri = setlogmask(maskpri);
return PyLong_FromLong(omaskpri);
}
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 PyLong_FromLong(mask);
}
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 PyLong_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}
};
/* Initialization function for the module */
static struct PyModuleDef syslogmodule = {
PyModuleDef_HEAD_INIT,
"syslog",
NULL,
-1,
syslog_methods,
NULL,
NULL,
NULL,
NULL
};
PyMODINIT_FUNC
PyInit_syslog(void)
{
PyObject *m;
/* Create the module and add the functions */
m = PyModule_Create(&syslogmodule);
if (m == NULL)
return NULL;
/* Add some symbolic constants to the module */
/* Priorities */
PyModule_AddIntMacro(m, LOG_EMERG);
PyModule_AddIntMacro(m, LOG_ALERT);
PyModule_AddIntMacro(m, LOG_CRIT);
PyModule_AddIntMacro(m, LOG_ERR);
PyModule_AddIntMacro(m, LOG_WARNING);
PyModule_AddIntMacro(m, LOG_NOTICE);
PyModule_AddIntMacro(m, LOG_INFO);
PyModule_AddIntMacro(m, LOG_DEBUG);
/* openlog() option flags */
PyModule_AddIntMacro(m, LOG_PID);
PyModule_AddIntMacro(m, LOG_CONS);
PyModule_AddIntMacro(m, LOG_NDELAY);
#ifdef LOG_ODELAY
PyModule_AddIntMacro(m, LOG_ODELAY);
#endif
#ifdef LOG_NOWAIT
PyModule_AddIntMacro(m, LOG_NOWAIT);
#endif
#ifdef LOG_PERROR
PyModule_AddIntMacro(m, LOG_PERROR);
#endif
/* Facilities */
PyModule_AddIntMacro(m, LOG_KERN);
PyModule_AddIntMacro(m, LOG_USER);
PyModule_AddIntMacro(m, LOG_MAIL);
PyModule_AddIntMacro(m, LOG_DAEMON);
PyModule_AddIntMacro(m, LOG_AUTH);
PyModule_AddIntMacro(m, LOG_LPR);
PyModule_AddIntMacro(m, LOG_LOCAL0);
PyModule_AddIntMacro(m, LOG_LOCAL1);
PyModule_AddIntMacro(m, LOG_LOCAL2);
PyModule_AddIntMacro(m, LOG_LOCAL3);
PyModule_AddIntMacro(m, LOG_LOCAL4);
PyModule_AddIntMacro(m, LOG_LOCAL5);
PyModule_AddIntMacro(m, LOG_LOCAL6);
PyModule_AddIntMacro(m, LOG_LOCAL7);
#ifndef LOG_SYSLOG
#define LOG_SYSLOG LOG_DAEMON
#endif
#ifndef LOG_NEWS
#define LOG_NEWS LOG_MAIL
#endif
#ifndef LOG_UUCP
#define LOG_UUCP LOG_MAIL
#endif
#ifndef LOG_CRON
#define LOG_CRON LOG_DAEMON
#endif
PyModule_AddIntMacro(m, LOG_SYSLOG);
PyModule_AddIntMacro(m, LOG_CRON);
PyModule_AddIntMacro(m, LOG_UUCP);
PyModule_AddIntMacro(m, LOG_NEWS);
#ifdef LOG_AUTHPRIV
PyModule_AddIntMacro(m, LOG_AUTHPRIV);
#endif
return m;
}
_Section(".rodata.pytab.1") const struct _inittab _PyImport_Inittab_syslog = {
"syslog",
PyInit_syslog,
};
| 12,797 | 411 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Modules/tkinter.h | #ifndef TKINTER_H
#define TKINTER_H
/* clang-format off */
/* This header is used to share some macros between _tkinter.c and
* tkappinit.c.
* Be sure to include tk.h before including this header so
* TK_HEX_VERSION is properly defined. */
/* TK_RELEASE_LEVEL is always one of the following:
* TCL_ALPHA_RELEASE 0
* TCL_BETA_RELEASE 1
* TCL_FINAL_RELEASE 2
*/
#define TK_HEX_VERSION ((TK_MAJOR_VERSION << 24) | \
(TK_MINOR_VERSION << 16) | \
(TK_RELEASE_LEVEL << 8) | \
(TK_RELEASE_SERIAL << 0))
/* Protect Tk 8.4.13 and older from a deadlock that happens when trying
* to load tk after a failed attempt. */
#if TK_HEX_VERSION < 0x0804020e
#define TKINTER_PROTECT_LOADTK
#define TKINTER_LOADTK_ERRMSG \
"Calling Tk_Init again after a previous call failed might deadlock"
#endif
#endif /* !TKINTER_H */
| 904 | 29 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Modules/ossaudiodev.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:8;coding:utf-8 -*-â
âvi: set net ft=c ts=4 sts=4 sw=4 fenc=utf-8 :viâ
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ¡
â Python 3 â
â https://docs.python.org/3/license.html â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
#define PY_SSIZE_T_CLEAN
#include "libc/sysv/consts/o.h"
#include "third_party/python/Include/structmember.h"
#include "third_party/python/Include/yoink.h"
/* clang-format off */
PYTHON_PROVIDE("ossaudiodev");
PYTHON_PROVIDE("ossaudiodev.AFMT_AC3");
PYTHON_PROVIDE("ossaudiodev.AFMT_A_LAW");
PYTHON_PROVIDE("ossaudiodev.AFMT_IMA_ADPCM");
PYTHON_PROVIDE("ossaudiodev.AFMT_MPEG");
PYTHON_PROVIDE("ossaudiodev.AFMT_MU_LAW");
PYTHON_PROVIDE("ossaudiodev.AFMT_QUERY");
PYTHON_PROVIDE("ossaudiodev.AFMT_S16_BE");
PYTHON_PROVIDE("ossaudiodev.AFMT_S16_LE");
PYTHON_PROVIDE("ossaudiodev.AFMT_S16_NE");
PYTHON_PROVIDE("ossaudiodev.AFMT_S8");
PYTHON_PROVIDE("ossaudiodev.AFMT_U16_BE");
PYTHON_PROVIDE("ossaudiodev.AFMT_U16_LE");
PYTHON_PROVIDE("ossaudiodev.AFMT_U8");
PYTHON_PROVIDE("ossaudiodev.OSSAudioError");
PYTHON_PROVIDE("ossaudiodev.SNDCTL_COPR_HALT");
PYTHON_PROVIDE("ossaudiodev.SNDCTL_COPR_LOAD");
PYTHON_PROVIDE("ossaudiodev.SNDCTL_COPR_RCODE");
PYTHON_PROVIDE("ossaudiodev.SNDCTL_COPR_RCVMSG");
PYTHON_PROVIDE("ossaudiodev.SNDCTL_COPR_RDATA");
PYTHON_PROVIDE("ossaudiodev.SNDCTL_COPR_RESET");
PYTHON_PROVIDE("ossaudiodev.SNDCTL_COPR_RUN");
PYTHON_PROVIDE("ossaudiodev.SNDCTL_COPR_SENDMSG");
PYTHON_PROVIDE("ossaudiodev.SNDCTL_COPR_WCODE");
PYTHON_PROVIDE("ossaudiodev.SNDCTL_COPR_WDATA");
PYTHON_PROVIDE("ossaudiodev.SNDCTL_DSP_BIND_CHANNEL");
PYTHON_PROVIDE("ossaudiodev.SNDCTL_DSP_CHANNELS");
PYTHON_PROVIDE("ossaudiodev.SNDCTL_DSP_GETBLKSIZE");
PYTHON_PROVIDE("ossaudiodev.SNDCTL_DSP_GETCAPS");
PYTHON_PROVIDE("ossaudiodev.SNDCTL_DSP_GETCHANNELMASK");
PYTHON_PROVIDE("ossaudiodev.SNDCTL_DSP_GETFMTS");
PYTHON_PROVIDE("ossaudiodev.SNDCTL_DSP_GETIPTR");
PYTHON_PROVIDE("ossaudiodev.SNDCTL_DSP_GETISPACE");
PYTHON_PROVIDE("ossaudiodev.SNDCTL_DSP_GETODELAY");
PYTHON_PROVIDE("ossaudiodev.SNDCTL_DSP_GETOPTR");
PYTHON_PROVIDE("ossaudiodev.SNDCTL_DSP_GETOSPACE");
PYTHON_PROVIDE("ossaudiodev.SNDCTL_DSP_GETSPDIF");
PYTHON_PROVIDE("ossaudiodev.SNDCTL_DSP_GETTRIGGER");
PYTHON_PROVIDE("ossaudiodev.SNDCTL_DSP_MAPINBUF");
PYTHON_PROVIDE("ossaudiodev.SNDCTL_DSP_MAPOUTBUF");
PYTHON_PROVIDE("ossaudiodev.SNDCTL_DSP_NONBLOCK");
PYTHON_PROVIDE("ossaudiodev.SNDCTL_DSP_POST");
PYTHON_PROVIDE("ossaudiodev.SNDCTL_DSP_PROFILE");
PYTHON_PROVIDE("ossaudiodev.SNDCTL_DSP_RESET");
PYTHON_PROVIDE("ossaudiodev.SNDCTL_DSP_SAMPLESIZE");
PYTHON_PROVIDE("ossaudiodev.SNDCTL_DSP_SETDUPLEX");
PYTHON_PROVIDE("ossaudiodev.SNDCTL_DSP_SETFMT");
PYTHON_PROVIDE("ossaudiodev.SNDCTL_DSP_SETFRAGMENT");
PYTHON_PROVIDE("ossaudiodev.SNDCTL_DSP_SETSPDIF");
PYTHON_PROVIDE("ossaudiodev.SNDCTL_DSP_SETSYNCRO");
PYTHON_PROVIDE("ossaudiodev.SNDCTL_DSP_SETTRIGGER");
PYTHON_PROVIDE("ossaudiodev.SNDCTL_DSP_SPEED");
PYTHON_PROVIDE("ossaudiodev.SNDCTL_DSP_STEREO");
PYTHON_PROVIDE("ossaudiodev.SNDCTL_DSP_SUBDIVIDE");
PYTHON_PROVIDE("ossaudiodev.SNDCTL_DSP_SYNC");
PYTHON_PROVIDE("ossaudiodev.SNDCTL_FM_4OP_ENABLE");
PYTHON_PROVIDE("ossaudiodev.SNDCTL_FM_LOAD_INSTR");
PYTHON_PROVIDE("ossaudiodev.SNDCTL_MIDI_INFO");
PYTHON_PROVIDE("ossaudiodev.SNDCTL_MIDI_MPUCMD");
PYTHON_PROVIDE("ossaudiodev.SNDCTL_MIDI_MPUMODE");
PYTHON_PROVIDE("ossaudiodev.SNDCTL_MIDI_PRETIME");
PYTHON_PROVIDE("ossaudiodev.SNDCTL_SEQ_CTRLRATE");
PYTHON_PROVIDE("ossaudiodev.SNDCTL_SEQ_GETINCOUNT");
PYTHON_PROVIDE("ossaudiodev.SNDCTL_SEQ_GETOUTCOUNT");
PYTHON_PROVIDE("ossaudiodev.SNDCTL_SEQ_GETTIME");
PYTHON_PROVIDE("ossaudiodev.SNDCTL_SEQ_NRMIDIS");
PYTHON_PROVIDE("ossaudiodev.SNDCTL_SEQ_NRSYNTHS");
PYTHON_PROVIDE("ossaudiodev.SNDCTL_SEQ_OUTOFBAND");
PYTHON_PROVIDE("ossaudiodev.SNDCTL_SEQ_PANIC");
PYTHON_PROVIDE("ossaudiodev.SNDCTL_SEQ_PERCMODE");
PYTHON_PROVIDE("ossaudiodev.SNDCTL_SEQ_RESET");
PYTHON_PROVIDE("ossaudiodev.SNDCTL_SEQ_RESETSAMPLES");
PYTHON_PROVIDE("ossaudiodev.SNDCTL_SEQ_SYNC");
PYTHON_PROVIDE("ossaudiodev.SNDCTL_SEQ_TESTMIDI");
PYTHON_PROVIDE("ossaudiodev.SNDCTL_SEQ_THRESHOLD");
PYTHON_PROVIDE("ossaudiodev.SNDCTL_SYNTH_CONTROL");
PYTHON_PROVIDE("ossaudiodev.SNDCTL_SYNTH_ID");
PYTHON_PROVIDE("ossaudiodev.SNDCTL_SYNTH_INFO");
PYTHON_PROVIDE("ossaudiodev.SNDCTL_SYNTH_MEMAVL");
PYTHON_PROVIDE("ossaudiodev.SNDCTL_SYNTH_REMOVESAMPLE");
PYTHON_PROVIDE("ossaudiodev.SNDCTL_TMR_CONTINUE");
PYTHON_PROVIDE("ossaudiodev.SNDCTL_TMR_METRONOME");
PYTHON_PROVIDE("ossaudiodev.SNDCTL_TMR_SELECT");
PYTHON_PROVIDE("ossaudiodev.SNDCTL_TMR_SOURCE");
PYTHON_PROVIDE("ossaudiodev.SNDCTL_TMR_START");
PYTHON_PROVIDE("ossaudiodev.SNDCTL_TMR_STOP");
PYTHON_PROVIDE("ossaudiodev.SNDCTL_TMR_TEMPO");
PYTHON_PROVIDE("ossaudiodev.SNDCTL_TMR_TIMEBASE");
PYTHON_PROVIDE("ossaudiodev.SOUND_MIXER_ALTPCM");
PYTHON_PROVIDE("ossaudiodev.SOUND_MIXER_BASS");
PYTHON_PROVIDE("ossaudiodev.SOUND_MIXER_CD");
PYTHON_PROVIDE("ossaudiodev.SOUND_MIXER_DIGITAL1");
PYTHON_PROVIDE("ossaudiodev.SOUND_MIXER_DIGITAL2");
PYTHON_PROVIDE("ossaudiodev.SOUND_MIXER_DIGITAL3");
PYTHON_PROVIDE("ossaudiodev.SOUND_MIXER_IGAIN");
PYTHON_PROVIDE("ossaudiodev.SOUND_MIXER_IMIX");
PYTHON_PROVIDE("ossaudiodev.SOUND_MIXER_LINE");
PYTHON_PROVIDE("ossaudiodev.SOUND_MIXER_LINE1");
PYTHON_PROVIDE("ossaudiodev.SOUND_MIXER_LINE2");
PYTHON_PROVIDE("ossaudiodev.SOUND_MIXER_LINE3");
PYTHON_PROVIDE("ossaudiodev.SOUND_MIXER_MIC");
PYTHON_PROVIDE("ossaudiodev.SOUND_MIXER_MONITOR");
PYTHON_PROVIDE("ossaudiodev.SOUND_MIXER_NRDEVICES");
PYTHON_PROVIDE("ossaudiodev.SOUND_MIXER_OGAIN");
PYTHON_PROVIDE("ossaudiodev.SOUND_MIXER_PCM");
PYTHON_PROVIDE("ossaudiodev.SOUND_MIXER_PHONEIN");
PYTHON_PROVIDE("ossaudiodev.SOUND_MIXER_PHONEOUT");
PYTHON_PROVIDE("ossaudiodev.SOUND_MIXER_RADIO");
PYTHON_PROVIDE("ossaudiodev.SOUND_MIXER_RECLEV");
PYTHON_PROVIDE("ossaudiodev.SOUND_MIXER_SPEAKER");
PYTHON_PROVIDE("ossaudiodev.SOUND_MIXER_SYNTH");
PYTHON_PROVIDE("ossaudiodev.SOUND_MIXER_TREBLE");
PYTHON_PROVIDE("ossaudiodev.SOUND_MIXER_VIDEO");
PYTHON_PROVIDE("ossaudiodev.SOUND_MIXER_VOLUME");
PYTHON_PROVIDE("ossaudiodev.control_labels");
PYTHON_PROVIDE("ossaudiodev.control_names");
PYTHON_PROVIDE("ossaudiodev.error");
PYTHON_PROVIDE("ossaudiodev.open");
PYTHON_PROVIDE("ossaudiodev.openmixer");
/*
* ossaudiodev -- Python interface to the OSS (Open Sound System) API.
* This is the standard audio API for Linux and some
* flavours of BSD [XXX which ones?]; it is also available
* for a wide range of commercial Unices.
*
* Originally written by Peter Bosch, March 2000, as linuxaudiodev.
*
* Renamed to ossaudiodev and rearranged/revised/hacked up
* by Greg Ward <[email protected]>, November 2002.
* Mixer interface by Nicholas FitzRoy-Dale <[email protected]>, Dec 2002.
*
* (c) 2000 Peter Bosch. All Rights Reserved.
* (c) 2002 Gregory P. Ward. All Rights Reserved.
* (c) 2002 Python Software Foundation. All Rights Reserved.
*
* XXX need a license statement
*
* $Id$
*/
#ifndef SNDCTL_DSP_CHANNELS
#define SNDCTL_DSP_CHANNELS SOUND_PCM_WRITE_CHANNELS
#endif
typedef struct {
PyObject_HEAD
char *devicename; /* name of the device file */
int fd; /* file descriptor */
int mode; /* file mode (O_RDONLY, etc.) */
Py_ssize_t icount; /* input count */
Py_ssize_t ocount; /* output count */
uint32_t afmts; /* audio formats supported by hardware */
} oss_audio_t;
typedef struct {
PyObject_HEAD
int fd; /* The open mixer device */
} oss_mixer_t;
static PyTypeObject OSSAudioType;
static PyTypeObject OSSMixerType;
static PyObject *OSSAudioError;
/* ----------------------------------------------------------------------
* DSP object initialization/deallocation
*/
static oss_audio_t *
newossobject(PyObject *arg)
{
oss_audio_t *self;
int fd, afmts, imode;
char *devicename = NULL;
char *mode = NULL;
/* Two ways to call open():
open(device, mode) (for consistency with builtin open())
open(mode) (for backwards compatibility)
because the *first* argument is optional, parsing args is
a wee bit tricky. */
if (!PyArg_ParseTuple(arg, "s|s:open", &devicename, &mode))
return NULL;
if (mode == NULL) { /* only one arg supplied */
mode = devicename;
devicename = NULL;
}
if (strcmp(mode, "r") == 0)
imode = O_RDONLY;
else if (strcmp(mode, "w") == 0)
imode = O_WRONLY;
else if (strcmp(mode, "rw") == 0)
imode = O_RDWR;
else {
PyErr_SetString(OSSAudioError, "mode must be 'r', 'w', or 'rw'");
return NULL;
}
/* Open the correct device: either the 'device' argument,
or the AUDIODEV environment variable, or "/dev/dsp". */
if (devicename == NULL) { /* called with one arg */
devicename = getenv("AUDIODEV");
if (devicename == NULL) /* $AUDIODEV not set */
devicename = "/dev/dsp";
}
/* Open with O_NONBLOCK to avoid hanging on devices that only allow
one open at a time. This does *not* affect later I/O; OSS
provides a special ioctl() for non-blocking read/write, which is
exposed via oss_nonblock() below. */
fd = _Py_open(devicename, imode|O_NONBLOCK);
if (fd == -1)
return NULL;
/* And (try to) put it back in blocking mode so we get the
expected write() semantics. */
if (fcntl(fd, F_SETFL, 0) == -1) {
close(fd);
PyErr_SetFromErrnoWithFilename(PyExc_IOError, devicename);
return NULL;
}
if (ioctl(fd, SNDCTL_DSP_GETFMTS, &afmts) == -1) {
close(fd);
PyErr_SetFromErrnoWithFilename(PyExc_IOError, devicename);
return NULL;
}
/* Create and initialize the object */
if ((self = PyObject_New(oss_audio_t, &OSSAudioType)) == NULL) {
close(fd);
return NULL;
}
self->devicename = devicename;
self->fd = fd;
self->mode = imode;
self->icount = self->ocount = 0;
self->afmts = afmts;
return self;
}
static void
oss_dealloc(oss_audio_t *self)
{
/* if already closed, don't reclose it */
if (self->fd != -1)
close(self->fd);
PyObject_Del(self);
}
/* ----------------------------------------------------------------------
* Mixer object initialization/deallocation
*/
static oss_mixer_t *
newossmixerobject(PyObject *arg)
{
char *devicename = NULL;
int fd;
oss_mixer_t *self;
if (!PyArg_ParseTuple(arg, "|s", &devicename)) {
return NULL;
}
if (devicename == NULL) {
devicename = getenv("MIXERDEV");
if (devicename == NULL) /* MIXERDEV not set */
devicename = "/dev/mixer";
}
fd = _Py_open(devicename, O_RDWR);
if (fd == -1)
return NULL;
if ((self = PyObject_New(oss_mixer_t, &OSSMixerType)) == NULL) {
close(fd);
return NULL;
}
self->fd = fd;
return self;
}
static void
oss_mixer_dealloc(oss_mixer_t *self)
{
/* if already closed, don't reclose it */
if (self->fd != -1)
close(self->fd);
PyObject_Del(self);
}
/* Methods to wrap the OSS ioctls. The calling convention is pretty
simple:
nonblock() -> ioctl(fd, SNDCTL_DSP_NONBLOCK)
fmt = setfmt(fmt) -> ioctl(fd, SNDCTL_DSP_SETFMT, &fmt)
etc.
*/
/* ----------------------------------------------------------------------
* Helper functions
*/
/* Check if a given file descriptor is valid (i.e. hasn't been closed).
* If true, return 1. Otherwise, raise ValueError and return 0.
*/
static int _is_fd_valid(int fd)
{
/* the FD is set to -1 in oss_close()/oss_mixer_close() */
if (fd >= 0) {
return 1;
} else {
PyErr_SetString(PyExc_ValueError,
"Operation on closed OSS device.");
return 0;
}
}
/* _do_ioctl_1() is a private helper function used for the OSS ioctls --
SNDCTL_DSP_{SETFMT,CHANNELS,SPEED} -- that are called from C
like this:
ioctl(fd, SNDCTL_DSP_cmd, &arg)
where arg is the value to set, and on return the driver sets arg to
the value that was actually set. Mapping this to Python is obvious:
arg = dsp.xxx(arg)
*/
static PyObject *
_do_ioctl_1(int fd, PyObject *args, char *fname, int cmd)
{
char argfmt[33] = "i:";
int arg;
assert(strlen(fname) <= 30);
strncat(argfmt, fname, 30);
if (!PyArg_ParseTuple(args, argfmt, &arg))
return NULL;
if (ioctl(fd, cmd, &arg) == -1)
return PyErr_SetFromErrno(PyExc_IOError);
return PyLong_FromLong(arg);
}
/* _do_ioctl_1_internal() is a wrapper for ioctls that take no inputs
but return an output -- ie. we need to pass a pointer to a local C
variable so the driver can write its output there, but from Python
all we see is the return value. For example,
SOUND_MIXER_READ_DEVMASK returns a bitmask of available mixer
devices, but does not use the value of the parameter passed-in in any
way.
*/
static PyObject *
_do_ioctl_1_internal(int fd, PyObject *args, char *fname, int cmd)
{
char argfmt[32] = ":";
int arg = 0;
assert(strlen(fname) <= 30);
strncat(argfmt, fname, 30);
if (!PyArg_ParseTuple(args, argfmt, &arg))
return NULL;
if (ioctl(fd, cmd, &arg) == -1)
return PyErr_SetFromErrno(PyExc_IOError);
return PyLong_FromLong(arg);
}
/* _do_ioctl_0() is a private helper for the no-argument ioctls:
SNDCTL_DSP_{SYNC,RESET,POST}. */
static PyObject *
_do_ioctl_0(int fd, PyObject *args, char *fname, int cmd)
{
char argfmt[32] = ":";
int rv;
assert(strlen(fname) <= 30);
strncat(argfmt, fname, 30);
if (!PyArg_ParseTuple(args, argfmt))
return NULL;
/* According to [email protected], all three of the ioctls that
use this function can block, so release the GIL. This is
especially important for SYNC, which can block for several
seconds. */
Py_BEGIN_ALLOW_THREADS
rv = ioctl(fd, cmd, 0);
Py_END_ALLOW_THREADS
if (rv == -1)
return PyErr_SetFromErrno(PyExc_IOError);
Py_INCREF(Py_None);
return Py_None;
}
/* ----------------------------------------------------------------------
* Methods of DSP objects (OSSAudioType)
*/
static PyObject *
oss_nonblock(oss_audio_t *self, PyObject *unused)
{
if (!_is_fd_valid(self->fd))
return NULL;
/* Hmmm: it doesn't appear to be possible to return to blocking
mode once we're in non-blocking mode! */
if (ioctl(self->fd, SNDCTL_DSP_NONBLOCK, NULL) == -1)
return PyErr_SetFromErrno(PyExc_IOError);
Py_INCREF(Py_None);
return Py_None;
}
static PyObject *
oss_setfmt(oss_audio_t *self, PyObject *args)
{
if (!_is_fd_valid(self->fd))
return NULL;
return _do_ioctl_1(self->fd, args, "setfmt", SNDCTL_DSP_SETFMT);
}
static PyObject *
oss_getfmts(oss_audio_t *self, PyObject *unused)
{
int mask;
if (!_is_fd_valid(self->fd))
return NULL;
if (ioctl(self->fd, SNDCTL_DSP_GETFMTS, &mask) == -1)
return PyErr_SetFromErrno(PyExc_IOError);
return PyLong_FromLong(mask);
}
static PyObject *
oss_channels(oss_audio_t *self, PyObject *args)
{
if (!_is_fd_valid(self->fd))
return NULL;
return _do_ioctl_1(self->fd, args, "channels", SNDCTL_DSP_CHANNELS);
}
static PyObject *
oss_speed(oss_audio_t *self, PyObject *args)
{
if (!_is_fd_valid(self->fd))
return NULL;
return _do_ioctl_1(self->fd, args, "speed", SNDCTL_DSP_SPEED);
}
static PyObject *
oss_sync(oss_audio_t *self, PyObject *args)
{
if (!_is_fd_valid(self->fd))
return NULL;
return _do_ioctl_0(self->fd, args, "sync", SNDCTL_DSP_SYNC);
}
static PyObject *
oss_reset(oss_audio_t *self, PyObject *args)
{
if (!_is_fd_valid(self->fd))
return NULL;
return _do_ioctl_0(self->fd, args, "reset", SNDCTL_DSP_RESET);
}
static PyObject *
oss_post(oss_audio_t *self, PyObject *args)
{
if (!_is_fd_valid(self->fd))
return NULL;
return _do_ioctl_0(self->fd, args, "post", SNDCTL_DSP_POST);
}
/* Regular file methods: read(), write(), close(), etc. as well
as one convenience method, writeall(). */
static PyObject *
oss_read(oss_audio_t *self, PyObject *args)
{
Py_ssize_t size, count;
PyObject *rv;
if (!_is_fd_valid(self->fd))
return NULL;
if (!PyArg_ParseTuple(args, "n:read", &size))
return NULL;
rv = PyBytes_FromStringAndSize(NULL, size);
if (rv == NULL)
return NULL;
count = _Py_read(self->fd, PyBytes_AS_STRING(rv), size);
if (count == -1) {
Py_DECREF(rv);
return NULL;
}
self->icount += count;
_PyBytes_Resize(&rv, count);
return rv;
}
static PyObject *
oss_write(oss_audio_t *self, PyObject *args)
{
Py_buffer data;
Py_ssize_t rv;
if (!_is_fd_valid(self->fd))
return NULL;
if (!PyArg_ParseTuple(args, "y*:write", &data)) {
return NULL;
}
rv = _Py_write(self->fd, data.buf, data.len);
PyBuffer_Release(&data);
if (rv == -1)
return NULL;
self->ocount += rv;
return PyLong_FromLong(rv);
}
static PyObject *
oss_writeall(oss_audio_t *self, PyObject *args)
{
Py_buffer data;
const char *cp;
Py_ssize_t size;
Py_ssize_t rv;
fd_set write_set_fds;
int select_rv;
/* NB. writeall() is only useful in non-blocking mode: according to
Guenter Geiger <[email protected]> on the linux-audio-dev list
(http://eca.cx/lad/2002/11/0380.html), OSS guarantees that
write() in blocking mode consumes the whole buffer. In blocking
mode, the behaviour of write() and writeall() from Python is
indistinguishable. */
if (!_is_fd_valid(self->fd))
return NULL;
if (!PyArg_ParseTuple(args, "y*:writeall", &data))
return NULL;
if (!_PyIsSelectable_fd(self->fd)) {
PyErr_SetString(PyExc_ValueError,
"file descriptor out of range for select");
PyBuffer_Release(&data);
return NULL;
}
/* use select to wait for audio device to be available */
FD_ZERO(&write_set_fds);
FD_SET(self->fd, &write_set_fds);
cp = (const char *)data.buf;
size = data.len;
while (size > 0) {
Py_BEGIN_ALLOW_THREADS
select_rv = select(self->fd+1, NULL, &write_set_fds, NULL, NULL);
Py_END_ALLOW_THREADS
assert(select_rv != 0); /* no timeout, can't expire */
if (select_rv == -1) {
PyBuffer_Release(&data);
return PyErr_SetFromErrno(PyExc_IOError);
}
rv = _Py_write(self->fd, cp, Py_MIN(size, INT_MAX));
if (rv == -1) {
/* buffer is full, try again */
if (errno == EAGAIN) {
PyErr_Clear();
continue;
}
/* it's a real error */
PyBuffer_Release(&data);
return NULL;
}
/* wrote rv bytes */
self->ocount += rv;
size -= rv;
cp += rv;
}
PyBuffer_Release(&data);
Py_INCREF(Py_None);
return Py_None;
}
static PyObject *
oss_close(oss_audio_t *self, PyObject *unused)
{
if (self->fd >= 0) {
Py_BEGIN_ALLOW_THREADS
close(self->fd);
Py_END_ALLOW_THREADS
self->fd = -1;
}
Py_INCREF(Py_None);
return Py_None;
}
static PyObject *
oss_self(PyObject *self, PyObject *unused)
{
Py_INCREF(self);
return self;
}
static PyObject *
oss_exit(PyObject *self, PyObject *unused)
{
_Py_IDENTIFIER(close);
PyObject *ret = _PyObject_CallMethodId(self, &PyId_close, NULL);
if (!ret)
return NULL;
Py_DECREF(ret);
Py_RETURN_NONE;
}
static PyObject *
oss_fileno(oss_audio_t *self, PyObject *unused)
{
if (!_is_fd_valid(self->fd))
return NULL;
return PyLong_FromLong(self->fd);
}
/* Convenience methods: these generally wrap a couple of ioctls into one
common task. */
static PyObject *
oss_setparameters(oss_audio_t *self, PyObject *args)
{
int wanted_fmt, wanted_channels, wanted_rate, strict=0;
int fmt, channels, rate;
if (!_is_fd_valid(self->fd))
return NULL;
if (!PyArg_ParseTuple(args, "iii|i:setparameters",
&wanted_fmt, &wanted_channels, &wanted_rate,
&strict))
return NULL;
fmt = wanted_fmt;
if (ioctl(self->fd, SNDCTL_DSP_SETFMT, &fmt) == -1) {
return PyErr_SetFromErrno(PyExc_IOError);
}
if (strict && fmt != wanted_fmt) {
return PyErr_Format
(OSSAudioError,
"unable to set requested format (wanted %d, got %d)",
wanted_fmt, fmt);
}
channels = wanted_channels;
if (ioctl(self->fd, SNDCTL_DSP_CHANNELS, &channels) == -1) {
return PyErr_SetFromErrno(PyExc_IOError);
}
if (strict && channels != wanted_channels) {
return PyErr_Format
(OSSAudioError,
"unable to set requested channels (wanted %d, got %d)",
wanted_channels, channels);
}
rate = wanted_rate;
if (ioctl(self->fd, SNDCTL_DSP_SPEED, &rate) == -1) {
return PyErr_SetFromErrno(PyExc_IOError);
}
if (strict && rate != wanted_rate) {
return PyErr_Format
(OSSAudioError,
"unable to set requested rate (wanted %d, got %d)",
wanted_rate, rate);
}
/* Construct the return value: a (fmt, channels, rate) tuple that
tells what the audio hardware was actually set to. */
return Py_BuildValue("(iii)", fmt, channels, rate);
}
static int
_ssize(oss_audio_t *self, int *nchannels, int *ssize)
{
int fmt;
fmt = 0;
if (ioctl(self->fd, SNDCTL_DSP_SETFMT, &fmt) < 0)
return -errno;
switch (fmt) {
case AFMT_MU_LAW:
case AFMT_A_LAW:
case AFMT_U8:
case AFMT_S8:
*ssize = 1; /* 8 bit formats: 1 byte */
break;
case AFMT_S16_LE:
case AFMT_S16_BE:
case AFMT_U16_LE:
case AFMT_U16_BE:
*ssize = 2; /* 16 bit formats: 2 byte */
break;
case AFMT_MPEG:
case AFMT_IMA_ADPCM:
default:
return -EOPNOTSUPP;
}
if (ioctl(self->fd, SNDCTL_DSP_CHANNELS, nchannels) < 0)
return -errno;
return 0;
}
/* bufsize returns the size of the hardware audio buffer in number
of samples */
static PyObject *
oss_bufsize(oss_audio_t *self, PyObject *unused)
{
audio_buf_info ai;
int nchannels=0, ssize=0;
if (!_is_fd_valid(self->fd))
return NULL;
if (_ssize(self, &nchannels, &ssize) < 0 || !nchannels || !ssize) {
PyErr_SetFromErrno(PyExc_IOError);
return NULL;
}
if (ioctl(self->fd, SNDCTL_DSP_GETOSPACE, &ai) < 0) {
PyErr_SetFromErrno(PyExc_IOError);
return NULL;
}
return PyLong_FromLong((ai.fragstotal * ai.fragsize) / (nchannels * ssize));
}
/* obufcount returns the number of samples that are available in the
hardware for playing */
static PyObject *
oss_obufcount(oss_audio_t *self, PyObject *unused)
{
audio_buf_info ai;
int nchannels=0, ssize=0;
if (!_is_fd_valid(self->fd))
return NULL;
if (_ssize(self, &nchannels, &ssize) < 0 || !nchannels || !ssize) {
PyErr_SetFromErrno(PyExc_IOError);
return NULL;
}
if (ioctl(self->fd, SNDCTL_DSP_GETOSPACE, &ai) < 0) {
PyErr_SetFromErrno(PyExc_IOError);
return NULL;
}
return PyLong_FromLong((ai.fragstotal * ai.fragsize - ai.bytes) /
(ssize * nchannels));
}
/* obufcount returns the number of samples that can be played without
blocking */
static PyObject *
oss_obuffree(oss_audio_t *self, PyObject *unused)
{
audio_buf_info ai;
int nchannels=0, ssize=0;
if (!_is_fd_valid(self->fd))
return NULL;
if (_ssize(self, &nchannels, &ssize) < 0 || !nchannels || !ssize) {
PyErr_SetFromErrno(PyExc_IOError);
return NULL;
}
if (ioctl(self->fd, SNDCTL_DSP_GETOSPACE, &ai) < 0) {
PyErr_SetFromErrno(PyExc_IOError);
return NULL;
}
return PyLong_FromLong(ai.bytes / (ssize * nchannels));
}
static PyObject *
oss_getptr(oss_audio_t *self, PyObject *unused)
{
count_info info;
int req;
if (!_is_fd_valid(self->fd))
return NULL;
if (self->mode == O_RDONLY)
req = SNDCTL_DSP_GETIPTR;
else
req = SNDCTL_DSP_GETOPTR;
if (ioctl(self->fd, req, &info) == -1) {
PyErr_SetFromErrno(PyExc_IOError);
return NULL;
}
return Py_BuildValue("iii", info.bytes, info.blocks, info.ptr);
}
/* ----------------------------------------------------------------------
* Methods of mixer objects (OSSMixerType)
*/
static PyObject *
oss_mixer_close(oss_mixer_t *self, PyObject *unused)
{
if (self->fd >= 0) {
close(self->fd);
self->fd = -1;
}
Py_INCREF(Py_None);
return Py_None;
}
static PyObject *
oss_mixer_fileno(oss_mixer_t *self, PyObject *unused)
{
if (!_is_fd_valid(self->fd))
return NULL;
return PyLong_FromLong(self->fd);
}
/* Simple mixer interface methods */
static PyObject *
oss_mixer_controls(oss_mixer_t *self, PyObject *args)
{
if (!_is_fd_valid(self->fd))
return NULL;
return _do_ioctl_1_internal(self->fd, args, "controls",
SOUND_MIXER_READ_DEVMASK);
}
static PyObject *
oss_mixer_stereocontrols(oss_mixer_t *self, PyObject *args)
{
if (!_is_fd_valid(self->fd))
return NULL;
return _do_ioctl_1_internal(self->fd, args, "stereocontrols",
SOUND_MIXER_READ_STEREODEVS);
}
static PyObject *
oss_mixer_reccontrols(oss_mixer_t *self, PyObject *args)
{
if (!_is_fd_valid(self->fd))
return NULL;
return _do_ioctl_1_internal(self->fd, args, "reccontrols",
SOUND_MIXER_READ_RECMASK);
}
static PyObject *
oss_mixer_get(oss_mixer_t *self, PyObject *args)
{
int channel, volume;
if (!_is_fd_valid(self->fd))
return NULL;
/* Can't use _do_ioctl_1 because of encoded arg thingy. */
if (!PyArg_ParseTuple(args, "i:get", &channel))
return NULL;
if (channel < 0 || channel > SOUND_MIXER_NRDEVICES) {
PyErr_SetString(OSSAudioError, "Invalid mixer channel specified.");
return NULL;
}
if (ioctl(self->fd, MIXER_READ(channel), &volume) == -1)
return PyErr_SetFromErrno(PyExc_IOError);
return Py_BuildValue("(ii)", volume & 0xff, (volume & 0xff00) >> 8);
}
static PyObject *
oss_mixer_set(oss_mixer_t *self, PyObject *args)
{
int channel, volume, leftVol, rightVol;
if (!_is_fd_valid(self->fd))
return NULL;
/* Can't use _do_ioctl_1 because of encoded arg thingy. */
if (!PyArg_ParseTuple(args, "i(ii):set", &channel, &leftVol, &rightVol))
return NULL;
if (channel < 0 || channel > SOUND_MIXER_NRDEVICES) {
PyErr_SetString(OSSAudioError, "Invalid mixer channel specified.");
return NULL;
}
if (leftVol < 0 || rightVol < 0 || leftVol > 100 || rightVol > 100) {
PyErr_SetString(OSSAudioError, "Volumes must be between 0 and 100.");
return NULL;
}
volume = (rightVol << 8) | leftVol;
if (ioctl(self->fd, MIXER_WRITE(channel), &volume) == -1)
return PyErr_SetFromErrno(PyExc_IOError);
return Py_BuildValue("(ii)", volume & 0xff, (volume & 0xff00) >> 8);
}
static PyObject *
oss_mixer_get_recsrc(oss_mixer_t *self, PyObject *args)
{
if (!_is_fd_valid(self->fd))
return NULL;
return _do_ioctl_1_internal(self->fd, args, "get_recsrc",
SOUND_MIXER_READ_RECSRC);
}
static PyObject *
oss_mixer_set_recsrc(oss_mixer_t *self, PyObject *args)
{
if (!_is_fd_valid(self->fd))
return NULL;
return _do_ioctl_1(self->fd, args, "set_recsrc",
SOUND_MIXER_WRITE_RECSRC);
}
/* ----------------------------------------------------------------------
* Method tables and other bureaucracy
*/
static PyMethodDef oss_methods[] = {
/* Regular file methods */
{ "read", (PyCFunction)oss_read, METH_VARARGS },
{ "write", (PyCFunction)oss_write, METH_VARARGS },
{ "writeall", (PyCFunction)oss_writeall, METH_VARARGS },
{ "close", (PyCFunction)oss_close, METH_NOARGS },
{ "fileno", (PyCFunction)oss_fileno, METH_NOARGS },
/* Simple ioctl wrappers */
{ "nonblock", (PyCFunction)oss_nonblock, METH_NOARGS },
{ "setfmt", (PyCFunction)oss_setfmt, METH_VARARGS },
{ "getfmts", (PyCFunction)oss_getfmts, METH_NOARGS },
{ "channels", (PyCFunction)oss_channels, METH_VARARGS },
{ "speed", (PyCFunction)oss_speed, METH_VARARGS },
{ "sync", (PyCFunction)oss_sync, METH_VARARGS },
{ "reset", (PyCFunction)oss_reset, METH_VARARGS },
{ "post", (PyCFunction)oss_post, METH_VARARGS },
/* Convenience methods -- wrap a couple of ioctls together */
{ "setparameters", (PyCFunction)oss_setparameters, METH_VARARGS },
{ "bufsize", (PyCFunction)oss_bufsize, METH_NOARGS },
{ "obufcount", (PyCFunction)oss_obufcount, METH_NOARGS },
{ "obuffree", (PyCFunction)oss_obuffree, METH_NOARGS },
{ "getptr", (PyCFunction)oss_getptr, METH_NOARGS },
/* Aliases for backwards compatibility */
{ "flush", (PyCFunction)oss_sync, METH_VARARGS },
/* Support for the context management protocol */
{ "__enter__", oss_self, METH_NOARGS },
{ "__exit__", oss_exit, METH_VARARGS },
{ NULL, NULL} /* sentinel */
};
static PyMethodDef oss_mixer_methods[] = {
/* Regular file method - OSS mixers are ioctl-only interface */
{ "close", (PyCFunction)oss_mixer_close, METH_NOARGS },
{ "fileno", (PyCFunction)oss_mixer_fileno, METH_NOARGS },
/* Support for the context management protocol */
{ "__enter__", oss_self, METH_NOARGS },
{ "__exit__", oss_exit, METH_VARARGS },
/* Simple ioctl wrappers */
{ "controls", (PyCFunction)oss_mixer_controls, METH_VARARGS },
{ "stereocontrols", (PyCFunction)oss_mixer_stereocontrols, METH_VARARGS},
{ "reccontrols", (PyCFunction)oss_mixer_reccontrols, METH_VARARGS},
{ "get", (PyCFunction)oss_mixer_get, METH_VARARGS },
{ "set", (PyCFunction)oss_mixer_set, METH_VARARGS },
{ "get_recsrc", (PyCFunction)oss_mixer_get_recsrc, METH_VARARGS },
{ "set_recsrc", (PyCFunction)oss_mixer_set_recsrc, METH_VARARGS },
{ NULL, NULL}
};
static PyObject *
oss_getattro(oss_audio_t *self, PyObject *nameobj)
{
const char *name = "";
PyObject * rval = NULL;
if (PyUnicode_Check(nameobj)) {
name = PyUnicode_AsUTF8(nameobj);
if (name == NULL)
return NULL;
}
if (strcmp(name, "closed") == 0) {
rval = (self->fd == -1) ? Py_True : Py_False;
Py_INCREF(rval);
}
else if (strcmp(name, "name") == 0) {
rval = PyUnicode_FromString(self->devicename);
}
else if (strcmp(name, "mode") == 0) {
/* No need for a "default" in this switch: from newossobject(),
self->mode can only be one of these three values. */
switch(self->mode) {
case O_RDONLY:
rval = PyUnicode_FromString("r");
break;
case O_RDWR:
rval = PyUnicode_FromString("rw");
break;
case O_WRONLY:
rval = PyUnicode_FromString("w");
break;
}
}
else {
rval = PyObject_GenericGetAttr((PyObject *)self, nameobj);
}
return rval;
}
static PyTypeObject OSSAudioType = {
PyVarObject_HEAD_INIT(&PyType_Type, 0)
"ossaudiodev.oss_audio_device", /*tp_name*/
sizeof(oss_audio_t), /*tp_basicsize*/
0, /*tp_itemsize*/
/* methods */
(destructor)oss_dealloc, /*tp_dealloc*/
0, /*tp_print*/
0, /*tp_getattr*/
0, /*tp_setattr*/
0, /*tp_reserved*/
0, /*tp_repr*/
0, /*tp_as_number*/
0, /*tp_as_sequence*/
0, /*tp_as_mapping*/
0, /*tp_hash*/
0, /*tp_call*/
0, /*tp_str*/
(getattrofunc)oss_getattro, /*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*/
oss_methods, /*tp_methods*/
};
static PyTypeObject OSSMixerType = {
PyVarObject_HEAD_INIT(&PyType_Type, 0)
"ossaudiodev.oss_mixer_device", /*tp_name*/
sizeof(oss_mixer_t), /*tp_basicsize*/
0, /*tp_itemsize*/
/* methods */
(destructor)oss_mixer_dealloc, /*tp_dealloc*/
0, /*tp_print*/
0, /*tp_getattr*/
0, /*tp_setattr*/
0, /*tp_reserved*/
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*/
oss_mixer_methods, /*tp_methods*/
};
static PyObject *
ossopen(PyObject *self, PyObject *args)
{
return (PyObject *)newossobject(args);
}
static PyObject *
ossopenmixer(PyObject *self, PyObject *args)
{
return (PyObject *)newossmixerobject(args);
}
static PyMethodDef ossaudiodev_methods[] = {
{ "open", ossopen, METH_VARARGS },
{ "openmixer", ossopenmixer, METH_VARARGS },
{ 0, 0 },
};
#define _EXPORT_INT(mod, name) \
if (PyModule_AddIntConstant(mod, #name, (long) (name)) == -1) return NULL;
static char *control_labels[] = SOUND_DEVICE_LABELS;
static char *control_names[] = SOUND_DEVICE_NAMES;
static int
build_namelists (PyObject *module)
{
PyObject *labels;
PyObject *names;
PyObject *s;
int num_controls;
int i;
num_controls = Py_ARRAY_LENGTH(control_labels);
assert(num_controls == Py_ARRAY_LENGTH(control_names));
labels = PyList_New(num_controls);
names = PyList_New(num_controls);
if (labels == NULL || names == NULL)
goto error2;
for (i = 0; i < num_controls; i++) {
s = PyUnicode_FromString(control_labels[i]);
if (s == NULL)
goto error2;
PyList_SET_ITEM(labels, i, s);
s = PyUnicode_FromString(control_names[i]);
if (s == NULL)
goto error2;
PyList_SET_ITEM(names, i, s);
}
if (PyModule_AddObject(module, "control_labels", labels) == -1)
goto error2;
if (PyModule_AddObject(module, "control_names", names) == -1)
goto error1;
return 0;
error2:
Py_XDECREF(labels);
error1:
Py_XDECREF(names);
return -1;
}
static struct PyModuleDef ossaudiodevmodule = {
PyModuleDef_HEAD_INIT,
"ossaudiodev",
NULL,
-1,
ossaudiodev_methods,
NULL,
NULL,
NULL,
NULL
};
PyMODINIT_FUNC
PyInit_ossaudiodev(void)
{
PyObject *m;
if (PyType_Ready(&OSSAudioType) < 0)
return NULL;
if (PyType_Ready(&OSSMixerType) < 0)
return NULL;
m = PyModule_Create(&ossaudiodevmodule);
if (m == NULL)
return NULL;
OSSAudioError = PyErr_NewException("ossaudiodev.OSSAudioError",
NULL, NULL);
if (OSSAudioError) {
/* Each call to PyModule_AddObject decrefs it; compensate: */
Py_INCREF(OSSAudioError);
Py_INCREF(OSSAudioError);
PyModule_AddObject(m, "error", OSSAudioError);
PyModule_AddObject(m, "OSSAudioError", OSSAudioError);
}
/* Build 'control_labels' and 'control_names' lists and add them
to the module. */
if (build_namelists(m) == -1) /* XXX what to do here? */
return NULL;
/* Expose the audio format numbers -- essential! */
_EXPORT_INT(m, AFMT_QUERY);
_EXPORT_INT(m, AFMT_MU_LAW);
_EXPORT_INT(m, AFMT_A_LAW);
_EXPORT_INT(m, AFMT_IMA_ADPCM);
_EXPORT_INT(m, AFMT_U8);
_EXPORT_INT(m, AFMT_S16_LE);
_EXPORT_INT(m, AFMT_S16_BE);
_EXPORT_INT(m, AFMT_S8);
_EXPORT_INT(m, AFMT_U16_LE);
_EXPORT_INT(m, AFMT_U16_BE);
_EXPORT_INT(m, AFMT_MPEG);
#ifdef AFMT_AC3
_EXPORT_INT(m, AFMT_AC3);
#endif
#ifdef AFMT_S16_NE
_EXPORT_INT(m, AFMT_S16_NE);
#endif
#ifdef AFMT_U16_NE
_EXPORT_INT(m, AFMT_U16_NE);
#endif
#ifdef AFMT_S32_LE
_EXPORT_INT(m, AFMT_S32_LE);
#endif
#ifdef AFMT_S32_BE
_EXPORT_INT(m, AFMT_S32_BE);
#endif
#ifdef AFMT_MPEG
_EXPORT_INT(m, AFMT_MPEG);
#endif
/* Expose the sound mixer device numbers. */
_EXPORT_INT(m, SOUND_MIXER_NRDEVICES);
_EXPORT_INT(m, SOUND_MIXER_VOLUME);
_EXPORT_INT(m, SOUND_MIXER_BASS);
_EXPORT_INT(m, SOUND_MIXER_TREBLE);
_EXPORT_INT(m, SOUND_MIXER_SYNTH);
_EXPORT_INT(m, SOUND_MIXER_PCM);
_EXPORT_INT(m, SOUND_MIXER_SPEAKER);
_EXPORT_INT(m, SOUND_MIXER_LINE);
_EXPORT_INT(m, SOUND_MIXER_MIC);
_EXPORT_INT(m, SOUND_MIXER_CD);
_EXPORT_INT(m, SOUND_MIXER_IMIX);
_EXPORT_INT(m, SOUND_MIXER_ALTPCM);
_EXPORT_INT(m, SOUND_MIXER_RECLEV);
_EXPORT_INT(m, SOUND_MIXER_IGAIN);
_EXPORT_INT(m, SOUND_MIXER_OGAIN);
_EXPORT_INT(m, SOUND_MIXER_LINE1);
_EXPORT_INT(m, SOUND_MIXER_LINE2);
_EXPORT_INT(m, SOUND_MIXER_LINE3);
#ifdef SOUND_MIXER_DIGITAL1
_EXPORT_INT(m, SOUND_MIXER_DIGITAL1);
#endif
#ifdef SOUND_MIXER_DIGITAL2
_EXPORT_INT(m, SOUND_MIXER_DIGITAL2);
#endif
#ifdef SOUND_MIXER_DIGITAL3
_EXPORT_INT(m, SOUND_MIXER_DIGITAL3);
#endif
#ifdef SOUND_MIXER_PHONEIN
_EXPORT_INT(m, SOUND_MIXER_PHONEIN);
#endif
#ifdef SOUND_MIXER_PHONEOUT
_EXPORT_INT(m, SOUND_MIXER_PHONEOUT);
#endif
#ifdef SOUND_MIXER_VIDEO
_EXPORT_INT(m, SOUND_MIXER_VIDEO);
#endif
#ifdef SOUND_MIXER_RADIO
_EXPORT_INT(m, SOUND_MIXER_RADIO);
#endif
#ifdef SOUND_MIXER_MONITOR
_EXPORT_INT(m, SOUND_MIXER_MONITOR);
#endif
/* Expose all the ioctl numbers for masochists who like to do this
stuff directly. */
_EXPORT_INT(m, SNDCTL_COPR_HALT);
_EXPORT_INT(m, SNDCTL_COPR_LOAD);
_EXPORT_INT(m, SNDCTL_COPR_RCODE);
_EXPORT_INT(m, SNDCTL_COPR_RCVMSG);
_EXPORT_INT(m, SNDCTL_COPR_RDATA);
_EXPORT_INT(m, SNDCTL_COPR_RESET);
_EXPORT_INT(m, SNDCTL_COPR_RUN);
_EXPORT_INT(m, SNDCTL_COPR_SENDMSG);
_EXPORT_INT(m, SNDCTL_COPR_WCODE);
_EXPORT_INT(m, SNDCTL_COPR_WDATA);
#ifdef SNDCTL_DSP_BIND_CHANNEL
_EXPORT_INT(m, SNDCTL_DSP_BIND_CHANNEL);
#endif
_EXPORT_INT(m, SNDCTL_DSP_CHANNELS);
_EXPORT_INT(m, SNDCTL_DSP_GETBLKSIZE);
_EXPORT_INT(m, SNDCTL_DSP_GETCAPS);
#ifdef SNDCTL_DSP_GETCHANNELMASK
_EXPORT_INT(m, SNDCTL_DSP_GETCHANNELMASK);
#endif
_EXPORT_INT(m, SNDCTL_DSP_GETFMTS);
_EXPORT_INT(m, SNDCTL_DSP_GETIPTR);
_EXPORT_INT(m, SNDCTL_DSP_GETISPACE);
#ifdef SNDCTL_DSP_GETODELAY
_EXPORT_INT(m, SNDCTL_DSP_GETODELAY);
#endif
_EXPORT_INT(m, SNDCTL_DSP_GETOPTR);
_EXPORT_INT(m, SNDCTL_DSP_GETOSPACE);
#ifdef SNDCTL_DSP_GETSPDIF
_EXPORT_INT(m, SNDCTL_DSP_GETSPDIF);
#endif
_EXPORT_INT(m, SNDCTL_DSP_GETTRIGGER);
_EXPORT_INT(m, SNDCTL_DSP_MAPINBUF);
_EXPORT_INT(m, SNDCTL_DSP_MAPOUTBUF);
_EXPORT_INT(m, SNDCTL_DSP_NONBLOCK);
_EXPORT_INT(m, SNDCTL_DSP_POST);
#ifdef SNDCTL_DSP_PROFILE
_EXPORT_INT(m, SNDCTL_DSP_PROFILE);
#endif
_EXPORT_INT(m, SNDCTL_DSP_RESET);
_EXPORT_INT(m, SNDCTL_DSP_SAMPLESIZE);
_EXPORT_INT(m, SNDCTL_DSP_SETDUPLEX);
_EXPORT_INT(m, SNDCTL_DSP_SETFMT);
_EXPORT_INT(m, SNDCTL_DSP_SETFRAGMENT);
#ifdef SNDCTL_DSP_SETSPDIF
_EXPORT_INT(m, SNDCTL_DSP_SETSPDIF);
#endif
_EXPORT_INT(m, SNDCTL_DSP_SETSYNCRO);
_EXPORT_INT(m, SNDCTL_DSP_SETTRIGGER);
_EXPORT_INT(m, SNDCTL_DSP_SPEED);
_EXPORT_INT(m, SNDCTL_DSP_STEREO);
_EXPORT_INT(m, SNDCTL_DSP_SUBDIVIDE);
_EXPORT_INT(m, SNDCTL_DSP_SYNC);
_EXPORT_INT(m, SNDCTL_FM_4OP_ENABLE);
_EXPORT_INT(m, SNDCTL_FM_LOAD_INSTR);
_EXPORT_INT(m, SNDCTL_MIDI_INFO);
_EXPORT_INT(m, SNDCTL_MIDI_MPUCMD);
_EXPORT_INT(m, SNDCTL_MIDI_MPUMODE);
_EXPORT_INT(m, SNDCTL_MIDI_PRETIME);
_EXPORT_INT(m, SNDCTL_SEQ_CTRLRATE);
_EXPORT_INT(m, SNDCTL_SEQ_GETINCOUNT);
_EXPORT_INT(m, SNDCTL_SEQ_GETOUTCOUNT);
#ifdef SNDCTL_SEQ_GETTIME
_EXPORT_INT(m, SNDCTL_SEQ_GETTIME);
#endif
_EXPORT_INT(m, SNDCTL_SEQ_NRMIDIS);
_EXPORT_INT(m, SNDCTL_SEQ_NRSYNTHS);
_EXPORT_INT(m, SNDCTL_SEQ_OUTOFBAND);
_EXPORT_INT(m, SNDCTL_SEQ_PANIC);
_EXPORT_INT(m, SNDCTL_SEQ_PERCMODE);
_EXPORT_INT(m, SNDCTL_SEQ_RESET);
_EXPORT_INT(m, SNDCTL_SEQ_RESETSAMPLES);
_EXPORT_INT(m, SNDCTL_SEQ_SYNC);
_EXPORT_INT(m, SNDCTL_SEQ_TESTMIDI);
_EXPORT_INT(m, SNDCTL_SEQ_THRESHOLD);
#ifdef SNDCTL_SYNTH_CONTROL
_EXPORT_INT(m, SNDCTL_SYNTH_CONTROL);
#endif
#ifdef SNDCTL_SYNTH_ID
_EXPORT_INT(m, SNDCTL_SYNTH_ID);
#endif
_EXPORT_INT(m, SNDCTL_SYNTH_INFO);
_EXPORT_INT(m, SNDCTL_SYNTH_MEMAVL);
#ifdef SNDCTL_SYNTH_REMOVESAMPLE
_EXPORT_INT(m, SNDCTL_SYNTH_REMOVESAMPLE);
#endif
_EXPORT_INT(m, SNDCTL_TMR_CONTINUE);
_EXPORT_INT(m, SNDCTL_TMR_METRONOME);
_EXPORT_INT(m, SNDCTL_TMR_SELECT);
_EXPORT_INT(m, SNDCTL_TMR_SOURCE);
_EXPORT_INT(m, SNDCTL_TMR_START);
_EXPORT_INT(m, SNDCTL_TMR_STOP);
_EXPORT_INT(m, SNDCTL_TMR_TEMPO);
_EXPORT_INT(m, SNDCTL_TMR_TIMEBASE);
return m;
}
| 43,558 | 1,403 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Modules/posixmodule.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:8;coding:utf-8 -*-â
âvi: set net ft=c ts=4 sts=4 sw=4 fenc=utf-8 :viâ
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ¡
â Python 3 â
â https://docs.python.org/3/license.html â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
#define PY_SSIZE_T_CLEAN
#include "libc/assert.h"
#include "libc/calls/calls.h"
#include "libc/calls/internal.h"
#include "libc/calls/makedev.h"
#include "libc/calls/struct/dirent.h"
#include "libc/calls/struct/iovec.h"
#include "libc/calls/struct/rusage.h"
#include "libc/calls/struct/sched_param.h"
#include "libc/calls/struct/stat.macros.h"
#include "libc/calls/struct/statvfs.h"
#include "libc/calls/struct/timespec.h"
#include "libc/calls/struct/timeval.h"
#include "libc/calls/struct/tms.h"
#include "libc/calls/struct/utsname.h"
#include "libc/calls/struct/winsize.h"
#include "libc/calls/syscall-sysv.internal.h"
#include "libc/calls/sysparam.h"
#include "libc/calls/termios.h"
#include "libc/calls/weirdtypes.h"
#include "libc/dce.h"
#include "libc/errno.h"
#include "libc/log/log.h"
#include "libc/mem/alg.h"
#include "libc/mem/gc.internal.h"
#include "libc/nt/createfile.h"
#include "libc/nt/dll.h"
#include "libc/nt/enum/creationdisposition.h"
#include "libc/nt/enum/fileflagandattributes.h"
#include "libc/nt/enum/sw.h"
#include "libc/nt/files.h"
#include "libc/nt/runtime.h"
#include "libc/runtime/dlfcn.h"
#include "libc/runtime/pathconf.h"
#include "libc/runtime/sysconf.h"
#include "libc/sock/sendfile.internal.h"
#include "libc/sock/sock.h"
#include "libc/stdio/stdio.h"
#include "libc/sysv/consts/at.h"
#include "libc/sysv/consts/dt.h"
#include "libc/sysv/consts/ex.h"
#include "libc/sysv/consts/f.h"
#include "libc/sysv/consts/grnd.h"
#include "libc/sysv/consts/o.h"
#include "libc/sysv/consts/posix.h"
#include "libc/sysv/consts/prio.h"
#include "libc/sysv/consts/s.h"
#include "libc/sysv/consts/sched.h"
#include "libc/sysv/consts/seek.h"
#include "libc/sysv/consts/sf.h"
#include "libc/sysv/consts/sicode.h"
#include "libc/sysv/consts/st.h"
#include "libc/sysv/consts/w.h"
#include "libc/sysv/consts/waitid.h"
#include "libc/sysv/errfuns.h"
#include "libc/time/struct/utimbuf.h"
#include "libc/time/time.h"
#include "libc/x/x.h"
#include "third_party/musl/lockf.h"
#include "third_party/musl/passwd.h"
#include "third_party/python/Include/abstract.h"
#include "third_party/python/Include/boolobject.h"
#include "third_party/python/Include/ceval.h"
#include "third_party/python/Include/dictobject.h"
#include "third_party/python/Include/fileobject.h"
#include "third_party/python/Include/fileutils.h"
#include "third_party/python/Include/floatobject.h"
#include "third_party/python/Include/import.h"
#include "third_party/python/Include/intrcheck.h"
#include "third_party/python/Include/longobject.h"
#include "third_party/python/Include/modsupport.h"
#include "third_party/python/Include/objimpl.h"
#include "third_party/python/Include/osmodule.h"
#include "third_party/python/Include/pyerrors.h"
#include "third_party/python/Include/pylifecycle.h"
#include "third_party/python/Include/pymacro.h"
#include "third_party/python/Include/pymem.h"
#include "third_party/python/Include/pytime.h"
#include "third_party/python/Include/structmember.h"
#include "third_party/python/Include/structseq.h"
#include "third_party/python/Include/warnings.h"
#include "third_party/python/Include/yoink.h"
#include "third_party/python/Modules/_multiprocessing/multiprocessing.h"
#include "third_party/python/Modules/posixmodule.h"
#include "third_party/python/pyconfig.h"
/* clang-format off */
PYTHON_PROVIDE("posix");
PYTHON_PROVIDE("posix._getfinalpathname");
PYTHON_PROVIDE("posix._exit");
PYTHON_PROVIDE("posix._have_functions");
/* POSIX module implementation */
/* This file is also used for Windows NT/MS-Win. In that case the
module actually calls itself 'nt', not 'posix', and a few
functions are either unimplemented or implemented differently. The source
assumes that for Windows NT, the macro 'MS_WINDOWS' is defined independent
of the compiler used. Different compilers define their own feature
test macro, e.g. '_MSC_VER'. */
PyDoc_STRVAR(posix__doc__,
"This module provides access to operating system functionality that is\n\
standardized by the C Standard and the POSIX standard (a thinly\n\
disguised Unix interface). Refer to the library manual and\n\
corresponding Unix manual entries for more information on calls.");
#if !defined(CPU_ALLOC) && defined(HAVE_SCHED_SETAFFINITY)
#undef HAVE_SCHED_SETAFFINITY
#endif
#if defined(__GLIBC__) && !defined(__FreeBSD_kernel__) && !defined(__GNU__)
#define USE_XATTRS
#endif
/*[clinic input]
# one of the few times we lie about this name!
module os
[clinic start generated code]*/
/*[clinic end generated code: output=da39a3ee5e6b4b0d input=94a0f0f978acae17]*/
#define NAMLEN(dirent) strlen((dirent)->d_name)
#ifdef UNION_WAIT
/* Emulate some macros on systems that have a union instead of macros */
#define WAIT_TYPE union wait
#define WAIT_STATUS_INT(s) (s.w_status)
#else /* !UNION_WAIT */
#define WAIT_TYPE int
#define WAIT_STATUS_INT(s) (s)
#endif /* UNION_WAIT */
/* Don't use the "_r" form if we don't need it (also, won't have a
prototype for it, at least on Solaris -- maybe others as well?). */
#if defined(HAVE_CTERMID_R) && defined(WITH_THREAD)
#define USE_CTERMID_R
#endif
/* choose the appropriate stat and fstat functions and return structs */
#undef STAT
#undef FSTAT
#undef STRUCT_STAT
#ifdef MS_WINDOWS
# define STAT win32_stat
# define LSTAT win32_lstat
# define FSTAT _Py_fstat_noraise
# define STRUCT_STAT struct _Py_stat_struct
#else
# define STAT stat
# define LSTAT lstat
# define FSTAT fstat
# define STRUCT_STAT struct stat
#endif
#define DWORD_MAX 4294967295U
#ifdef MS_WINDOWS
#define INITFUNC PyInit_nt
#define MODNAME "nt"
#else
#define INITFUNC PyInit_posix
#define MODNAME "posix"
#endif
#ifdef MS_WINDOWS
/* defined in fileutils.c */
void _Py_time_t_to_FILE_TIME(time_t, int, FILETIME *);
void _Py_attribute_data_to_stat(BY_HANDLE_FILE_INFORMATION *,
ULONG, struct _Py_stat_struct *);
#endif
#ifdef MS_WINDOWS
static int
win32_warn_bytes_api()
{
return PyErr_WarnEx(PyExc_DeprecationWarning,
"The Windows bytes API has been deprecated, "
"use Unicode filenames instead",
1);
}
#endif
#ifndef MS_WINDOWS
PyObject *
_PyLong_FromUid(uid_t uid)
{
if (uid == (uid_t)-1)
return PyLong_FromLong(-1);
return PyLong_FromUnsignedLong(uid);
}
PyObject *
_PyLong_FromGid(gid_t gid)
{
if (gid == (gid_t)-1)
return PyLong_FromLong(-1);
return PyLong_FromUnsignedLong(gid);
}
int
_Py_Uid_Converter(PyObject *obj, void *p)
{
uid_t uid;
PyObject *index;
int overflow;
long result;
unsigned long uresult;
index = PyNumber_Index(obj);
if (index == NULL) {
PyErr_Format(PyExc_TypeError,
"uid should be integer, not %.200s",
Py_TYPE(obj)->tp_name);
return 0;
}
/*
* Handling uid_t is complicated for two reasons:
* * Although uid_t is (always?) unsigned, it still
* accepts -1.
* * We don't know its size in advance--it may be
* bigger than an int, or it may be smaller than
* a long.
*
* So a bit of defensive programming is in order.
* Start with interpreting the value passed
* in as a signed long and see if it works.
*/
result = PyLong_AsLongAndOverflow(index, &overflow);
if (!overflow) {
uid = (uid_t)result;
if (result == -1) {
if (PyErr_Occurred())
goto fail;
/* It's a legitimate -1, we're done. */
goto success;
}
/* Any other negative number is disallowed. */
if (result < 0)
goto underflow;
/* Ensure the value wasn't truncated. */
if (sizeof(uid_t) < sizeof(long) &&
(long)uid != result)
goto underflow;
goto success;
}
if (overflow < 0)
goto underflow;
/*
* Okay, the value overflowed a signed long. If it
* fits in an *unsigned* long, it may still be okay,
* as uid_t may be unsigned long on this platform.
*/
uresult = PyLong_AsUnsignedLong(index);
if (PyErr_Occurred()) {
if (PyErr_ExceptionMatches(PyExc_OverflowError))
goto overflow;
goto fail;
}
uid = (uid_t)uresult;
/*
* If uid == (uid_t)-1, the user actually passed in ULONG_MAX,
* but this value would get interpreted as (uid_t)-1 by chown
* and its siblings. That's not what the user meant! So we
* throw an overflow exception instead. (We already
* handled a real -1 with PyLong_AsLongAndOverflow() above.)
*/
if (uid == (uid_t)-1)
goto overflow;
/* Ensure the value wasn't truncated. */
if (sizeof(uid_t) < sizeof(long) &&
(unsigned long)uid != uresult)
goto overflow;
/* fallthrough */
success:
Py_DECREF(index);
*(uid_t *)p = uid;
return 1;
underflow:
PyErr_SetString(PyExc_OverflowError,
"uid is less than minimum");
goto fail;
overflow:
PyErr_SetString(PyExc_OverflowError,
"uid is greater than maximum");
/* fallthrough */
fail:
Py_DECREF(index);
return 0;
}
int
_Py_Gid_Converter(PyObject *obj, void *p)
{
gid_t gid;
PyObject *index;
int overflow;
long result;
unsigned long uresult;
index = PyNumber_Index(obj);
if (index == NULL) {
PyErr_Format(PyExc_TypeError,
"gid should be integer, not %.200s",
Py_TYPE(obj)->tp_name);
return 0;
}
/*
* Handling gid_t is complicated for two reasons:
* * Although gid_t is (always?) unsigned, it still
* accepts -1.
* * We don't know its size in advance--it may be
* bigger than an int, or it may be smaller than
* a long.
*
* So a bit of defensive programming is in order.
* Start with interpreting the value passed
* in as a signed long and see if it works.
*/
result = PyLong_AsLongAndOverflow(index, &overflow);
if (!overflow) {
gid = (gid_t)result;
if (result == -1) {
if (PyErr_Occurred())
goto fail;
/* It's a legitimate -1, we're done. */
goto success;
}
/* Any other negative number is disallowed. */
if (result < 0) {
goto underflow;
}
/* Ensure the value wasn't truncated. */
if (sizeof(gid_t) < sizeof(long) &&
(long)gid != result)
goto underflow;
goto success;
}
if (overflow < 0)
goto underflow;
/*
* Okay, the value overflowed a signed long. If it
* fits in an *unsigned* long, it may still be okay,
* as gid_t may be unsigned long on this platform.
*/
uresult = PyLong_AsUnsignedLong(index);
if (PyErr_Occurred()) {
if (PyErr_ExceptionMatches(PyExc_OverflowError))
goto overflow;
goto fail;
}
gid = (gid_t)uresult;
/*
* If gid == (gid_t)-1, the user actually passed in ULONG_MAX,
* but this value would get interpreted as (gid_t)-1 by chown
* and its siblings. That's not what the user meant! So we
* throw an overflow exception instead. (We already
* handled a real -1 with PyLong_AsLongAndOverflow() above.)
*/
if (gid == (gid_t)-1)
goto overflow;
/* Ensure the value wasn't truncated. */
if (sizeof(gid_t) < sizeof(long) &&
(unsigned long)gid != uresult)
goto overflow;
/* fallthrough */
success:
Py_DECREF(index);
*(gid_t *)p = gid;
return 1;
underflow:
PyErr_SetString(PyExc_OverflowError,
"gid is less than minimum");
goto fail;
overflow:
PyErr_SetString(PyExc_OverflowError,
"gid is greater than maximum");
/* fallthrough */
fail:
Py_DECREF(index);
return 0;
}
#endif /* MS_WINDOWS */
#define _PyLong_FromDev PyLong_FromLongLong
#if defined(HAVE_MKNOD) && defined(HAVE_MAKEDEV)
static int
_Py_Dev_Converter(PyObject *obj, void *p)
{
*((dev_t *)p) = PyLong_AsUnsignedLongLong(obj);
if (PyErr_Occurred())
return 0;
return 1;
}
#endif /* HAVE_MKNOD && HAVE_MAKEDEV */
#ifdef AT_FDCWD
/*
* Why the (int) cast? Solaris 10 defines AT_FDCWD as 0xffd19553 (-3041965);
* without the int cast, the value gets interpreted as uint (4291925331),
* which doesn't play nicely with all the initializer lines in this file that
* look like this:
* int dir_fd = DEFAULT_DIR_FD;
*/
#define DEFAULT_DIR_FD (int)AT_FDCWD
#else
#define DEFAULT_DIR_FD (-100)
#endif
static int
_fd_converter(PyObject *o, int *p)
{
int overflow;
long long_value;
PyObject *index = PyNumber_Index(o);
if (index == NULL) {
return 0;
}
assert(PyLong_Check(index));
long_value = PyLong_AsLongAndOverflow(index, &overflow);
Py_DECREF(index);
assert(!PyErr_Occurred());
if (overflow > 0 || long_value > INT_MAX) {
PyErr_SetString(PyExc_OverflowError,
"fd is greater than maximum");
return 0;
}
if (overflow < 0 || long_value < INT_MIN) {
PyErr_SetString(PyExc_OverflowError,
"fd is less than minimum");
return 0;
}
*p = (int)long_value;
return 1;
}
static int
dir_fd_converter(PyObject *o, void *p)
{
if (o == Py_None) {
*(int *)p = DEFAULT_DIR_FD;
return 1;
}
else if (PyIndex_Check(o)) {
return _fd_converter(o, (int *)p);
}
else {
PyErr_Format(PyExc_TypeError,
"argument should be integer or None, not %.200s",
Py_TYPE(o)->tp_name);
return 0;
}
}
/*
* A PyArg_ParseTuple "converter" function
* that handles filesystem paths in the manner
* preferred by the os module.
*
* path_converter accepts (Unicode) strings and their
* subclasses, and bytes and their subclasses. What
* it does with the argument depends on the platform:
*
* * On Windows, if we get a (Unicode) string we
* extract the wchar_t * and return it; if we get
* bytes we decode to wchar_t * and return that.
*
* * On all other platforms, strings are encoded
* to bytes using PyUnicode_FSConverter, then we
* extract the char * from the bytes object and
* return that.
*
* path_converter also optionally accepts signed
* integers (representing open file descriptors) instead
* of path strings.
*
* Input fields:
* path.nullable
* If nonzero, the path is permitted to be None.
* path.allow_fd
* If nonzero, the path is permitted to be a file handle
* (a signed int) instead of a string.
* path.function_name
* If non-NULL, path_converter will use that as the name
* of the function in error messages.
* (If path.function_name is NULL it omits the function name.)
* path.argument_name
* If non-NULL, path_converter will use that as the name
* of the parameter in error messages.
* (If path.argument_name is NULL it uses "path".)
*
* Output fields:
* path.wide
* Points to the path if it was expressed as Unicode
* and was not encoded. (Only used on Windows.)
* path.narrow
* Points to the path if it was expressed as bytes,
* or it was Unicode and was encoded to bytes. (On Windows,
* is a non-zero integer if the path was expressed as bytes.
* The type is deliberately incompatible to prevent misuse.)
* path.fd
* Contains a file descriptor if path.accept_fd was true
* and the caller provided a signed integer instead of any
* sort of string.
*
* WARNING: if your "path" parameter is optional, and is
* unspecified, path_converter will never get called.
* So if you set allow_fd, you *MUST* initialize path.fd = -1
* yourself!
* path.length
* The length of the path in characters, if specified as
* a string.
* path.object
* The original object passed in (if get a PathLike object,
* the result of PyOS_FSPath() is treated as the original object).
* Own a reference to the object.
* path.cleanup
* For internal use only. May point to a temporary object.
* (Pay no attention to the man behind the curtain.)
*
* At most one of path.wide or path.narrow will be non-NULL.
* If path was None and path.nullable was set,
* or if path was an integer and path.allow_fd was set,
* both path.wide and path.narrow will be NULL
* and path.length will be 0.
*
* path_converter takes care to not write to the path_t
* unless it's successful. However it must reset the
* "cleanup" field each time it's called.
*
* Use as follows:
* path_t path;
* bzero(&path, sizeof(path));
* PyArg_ParseTuple(args, "O&", path_converter, &path);
* // ... use values from path ...
* path_cleanup(&path);
*
* (Note that if PyArg_Parse fails you don't need to call
* path_cleanup(). However it is safe to do so.)
*/
typedef struct {
const char *function_name;
const char *argument_name;
int nullable;
int allow_fd;
const wchar_t *wide;
#ifdef MS_WINDOWS
BOOL narrow;
#else
const char *narrow;
#endif
int fd;
Py_ssize_t length;
PyObject *object;
PyObject *cleanup;
} path_t;
#ifdef MS_WINDOWS
#define PATH_T_INITIALIZE(function_name, argument_name, nullable, allow_fd) \
{function_name, argument_name, nullable, allow_fd, NULL, FALSE, -1, 0, NULL, NULL}
#else
#define PATH_T_INITIALIZE(function_name, argument_name, nullable, allow_fd) \
{function_name, argument_name, nullable, allow_fd, NULL, NULL, -1, 0, NULL, NULL}
#endif
static void
path_cleanup(path_t *path)
{
Py_CLEAR(path->object);
Py_CLEAR(path->cleanup);
}
static int
path_converter(PyObject *o, void *p)
{
path_t *path = (path_t *)p;
PyObject *bytes = NULL;
Py_ssize_t length = 0;
int is_index, is_buffer, is_bytes, is_unicode;
const char *narrow;
#ifdef MS_WINDOWS
PyObject *wo = NULL;
const wchar_t *wide;
#endif
#define FORMAT_EXCEPTION(exc, fmt) \
PyErr_Format(exc, "%s%s" fmt, \
path->function_name ? path->function_name : "", \
path->function_name ? ": " : "", \
path->argument_name ? path->argument_name : "path")
/* Py_CLEANUP_SUPPORTED support */
if (o == NULL) {
path_cleanup(path);
return 1;
}
/* Ensure it's always safe to call path_cleanup(). */
path->object = path->cleanup = NULL;
/* path->object owns a reference to the original object */
Py_INCREF(o);
if ((o == Py_None) && path->nullable) {
path->wide = NULL;
#ifdef MS_WINDOWS
path->narrow = FALSE;
#else
path->narrow = NULL;
#endif
path->fd = -1;
goto success_exit;
}
/* Only call this here so that we don't treat the return value of
os.fspath() as an fd or buffer. */
is_index = path->allow_fd && PyIndex_Check(o);
is_buffer = PyObject_CheckBuffer(o);
is_bytes = PyBytes_Check(o);
is_unicode = PyUnicode_Check(o);
if (!is_index && !is_buffer && !is_unicode && !is_bytes) {
/* Inline PyOS_FSPath() for better error messages. */
_Py_IDENTIFIER(__fspath__);
PyObject *func = NULL;
func = _PyObject_LookupSpecial(o, &PyId___fspath__);
if (NULL == func) {
goto error_format;
}
/* still owns a reference to the original object */
Py_DECREF(o);
o = _PyObject_CallNoArg(func);
Py_DECREF(func);
if (NULL == o) {
goto error_exit;
}
else if (PyUnicode_Check(o)) {
is_unicode = 1;
}
else if (PyBytes_Check(o)) {
is_bytes = 1;
}
else {
goto error_format;
}
}
if (is_unicode) {
#ifdef MS_WINDOWS
wide = PyUnicode_AsUnicodeAndSize(o, &length);
if (!wide) {
goto error_exit;
}
if (length > 32767) {
FORMAT_EXCEPTION(PyExc_ValueError, "%s too long for Windows");
goto error_exit;
}
if (wcslen(wide) != length) {
FORMAT_EXCEPTION(PyExc_ValueError, "embedded null character in %s");
goto error_exit;
}
path->wide = wide;
path->narrow = FALSE;
path->fd = -1;
goto success_exit;
#else
if (!PyUnicode_FSConverter(o, &bytes)) {
goto error_exit;
}
#endif
}
else if (is_bytes) {
bytes = o;
Py_INCREF(bytes);
}
else if (is_buffer) {
/* XXX Replace PyObject_CheckBuffer with PyBytes_Check in other code
after removing suport of non-bytes buffer objects. */
if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
"%s%s%s should be %s, not %.200s",
path->function_name ? path->function_name : "",
path->function_name ? ": " : "",
path->argument_name ? path->argument_name : "path",
path->allow_fd && path->nullable ? "string, bytes, os.PathLike, "
"integer or None" :
path->allow_fd ? "string, bytes, os.PathLike or integer" :
path->nullable ? "string, bytes, os.PathLike or None" :
"string, bytes or os.PathLike",
Py_TYPE(o)->tp_name)) {
goto error_exit;
}
bytes = PyBytes_FromObject(o);
if (!bytes) {
goto error_exit;
}
}
else if (is_index) {
if (!_fd_converter(o, &path->fd)) {
goto error_exit;
}
path->wide = NULL;
#ifdef MS_WINDOWS
path->narrow = FALSE;
#else
path->narrow = NULL;
#endif
goto success_exit;
}
else {
error_format:
PyErr_Format(PyExc_TypeError, "%s%s%s should be %s, not %.200s",
path->function_name ? path->function_name : "",
path->function_name ? ": " : "",
path->argument_name ? path->argument_name : "path",
path->allow_fd && path->nullable ? "string, bytes, os.PathLike, "
"integer or None" :
path->allow_fd ? "string, bytes, os.PathLike or integer" :
path->nullable ? "string, bytes, os.PathLike or None" :
"string, bytes or os.PathLike",
Py_TYPE(o)->tp_name);
goto error_exit;
}
length = PyBytes_GET_SIZE(bytes);
narrow = PyBytes_AS_STRING(bytes);
if ((size_t)length != strlen(narrow)) {
FORMAT_EXCEPTION(PyExc_ValueError, "embedded null character in %s");
goto error_exit;
}
#ifdef MS_WINDOWS
wo = PyUnicode_DecodeFSDefaultAndSize(
narrow,
length
);
if (!wo) {
goto error_exit;
}
wide = PyUnicode_AsUnicodeAndSize(wo, &length);
if (!wide) {
goto error_exit;
}
if (length > 32767) {
FORMAT_EXCEPTION(PyExc_ValueError, "%s too long for Windows");
goto error_exit;
}
if (wcslen(wide) != length) {
FORMAT_EXCEPTION(PyExc_ValueError, "embedded null character in %s");
goto error_exit;
}
path->wide = wide;
path->narrow = TRUE;
path->cleanup = wo;
Py_DECREF(bytes);
#else
path->wide = NULL;
path->narrow = narrow;
if (bytes == o) {
/* Still a reference owned by path->object, don't have to
worry about path->narrow is used after free. */
Py_DECREF(bytes);
}
else {
path->cleanup = bytes;
}
#endif
path->fd = -1;
success_exit:
path->length = length;
path->object = o;
return Py_CLEANUP_SUPPORTED;
error_exit:
Py_XDECREF(o);
Py_XDECREF(bytes);
#ifdef MS_WINDOWS
Py_XDECREF(wo);
#endif
return 0;
}
static void
argument_unavailable_error(const char *function_name, const char *argument_name)
{
PyErr_Format(PyExc_NotImplementedError,
"%s%s%s unavailable on this platform",
(function_name != NULL) ? function_name : "",
(function_name != NULL) ? ": ": "",
argument_name);
}
static int
dir_fd_unavailable(PyObject *o, void *p)
{
int dir_fd;
if (!dir_fd_converter(o, &dir_fd))
return 0;
if (dir_fd != DEFAULT_DIR_FD) {
argument_unavailable_error(NULL, "dir_fd");
return 0;
}
*(int *)p = dir_fd;
return 1;
}
static int
fd_specified(const char *function_name, int fd)
{
if (fd == -1)
return 0;
argument_unavailable_error(function_name, "fd");
return 1;
}
static int
follow_symlinks_specified(const char *function_name, int follow_symlinks)
{
if (follow_symlinks)
return 0;
argument_unavailable_error(function_name, "follow_symlinks");
return 1;
}
static int
path_and_dir_fd_invalid(const char *function_name, path_t *path, int dir_fd)
{
if (!path->wide && (dir_fd != DEFAULT_DIR_FD)
#ifndef MS_WINDOWS
&& !path->narrow
#endif
) {
PyErr_Format(PyExc_ValueError,
"%s: can't specify dir_fd without matching path",
function_name);
return 1;
}
return 0;
}
static int
dir_fd_and_fd_invalid(const char *function_name, int dir_fd, int fd)
{
if ((dir_fd != DEFAULT_DIR_FD) && (fd != -1)) {
PyErr_Format(PyExc_ValueError,
"%s: can't specify both dir_fd and fd",
function_name);
return 1;
}
return 0;
}
static int
fd_and_follow_symlinks_invalid(const char *function_name, int fd,
int follow_symlinks)
{
if ((fd > 0) && (!follow_symlinks)) {
PyErr_Format(PyExc_ValueError,
"%s: cannot use fd and follow_symlinks together",
function_name);
return 1;
}
return 0;
}
static int
dir_fd_and_follow_symlinks_invalid(const char *function_name, int dir_fd,
int follow_symlinks)
{
if ((dir_fd != DEFAULT_DIR_FD) && (!follow_symlinks)) {
PyErr_Format(PyExc_ValueError,
"%s: cannot use dir_fd and follow_symlinks together",
function_name);
return 1;
}
return 0;
}
#ifdef MS_WINDOWS
typedef long long Py_off_t;
#else
typedef off_t Py_off_t;
#endif
static int
Py_off_t_converter(PyObject *arg, void *addr)
{
#ifdef HAVE_LARGEFILE_SUPPORT
*((Py_off_t *)addr) = PyLong_AsLongLong(arg);
#else
*((Py_off_t *)addr) = PyLong_AsLong(arg);
#endif
if (PyErr_Occurred())
return 0;
return 1;
}
static PyObject *
PyLong_FromPy_off_t(Py_off_t offset)
{
#ifdef HAVE_LARGEFILE_SUPPORT
return PyLong_FromLongLong(offset);
#else
return PyLong_FromLong(offset);
#endif
}
#ifdef MS_WINDOWS
static int
win32_get_reparse_tag(HANDLE reparse_point_handle, ULONG *reparse_tag)
{
char target_buffer[_Py_MAXIMUM_REPARSE_DATA_BUFFER_SIZE];
_Py_REPARSE_DATA_BUFFER *rdb = (_Py_REPARSE_DATA_BUFFER *)target_buffer;
DWORD n_bytes_returned;
if (0 == DeviceIoControl(
reparse_point_handle,
FSCTL_GET_REPARSE_POINT,
NULL, 0, /* in buffer */
target_buffer, sizeof(target_buffer),
&n_bytes_returned,
NULL)) /* we're not using OVERLAPPED_IO */
return FALSE;
if (reparse_tag)
*reparse_tag = rdb->ReparseTag;
return TRUE;
}
#endif /* MS_WINDOWS */
static PyObject *
convertenviron(void)
{
PyObject *d;
#ifdef MS_WINDOWS
wchar_t **e;
#else
char **e;
#endif
d = PyDict_New();
if (d == NULL)
return NULL;
#if defined(WITH_NEXT_FRAMEWORK) || (defined(__APPLE__) && defined(Py_ENABLE_SHARED))
if (environ == NULL)
environ = *_NSGetEnviron();
#endif
#ifdef MS_WINDOWS
/* _wenviron must be initialized in this way if the program is started
through main() instead of wmain(). */
_wgetenv(L"");
if (_wenviron == NULL)
return d;
/* This part ignores errors */
for (e = _wenviron; *e != NULL; e++) {
PyObject *k;
PyObject *v;
const wchar_t *p = wcschr(*e, L'=');
if (p == NULL)
continue;
k = PyUnicode_FromWideChar(*e, (Py_ssize_t)(p-*e));
if (k == NULL) {
PyErr_Clear();
continue;
}
v = PyUnicode_FromWideChar(p+1, wcslen(p+1));
if (v == NULL) {
PyErr_Clear();
Py_DECREF(k);
continue;
}
if (PyDict_GetItem(d, k) == NULL) {
if (PyDict_SetItem(d, k, v) != 0)
PyErr_Clear();
}
Py_DECREF(k);
Py_DECREF(v);
}
#else
if (environ == NULL)
return d;
/* This part ignores errors */
for (e = environ; *e != NULL; e++) {
PyObject *k;
PyObject *v;
const char *p = strchr(*e, '=');
if (p == NULL)
continue;
k = PyBytes_FromStringAndSize(*e, (int)(p-*e));
if (k == NULL) {
PyErr_Clear();
continue;
}
v = PyBytes_FromStringAndSize(p+1, strlen(p+1));
if (v == NULL) {
PyErr_Clear();
Py_DECREF(k);
continue;
}
if (PyDict_GetItem(d, k) == NULL) {
if (PyDict_SetItem(d, k, v) != 0)
PyErr_Clear();
}
Py_DECREF(k);
Py_DECREF(v);
}
#endif
return d;
}
/* Set a POSIX-specific error from errno, and return NULL */
static PyObject *
posix_error(void)
{
return PyErr_SetFromErrno(PyExc_OSError);
}
static PyObject *
win32_error(const char* function, const char* filename)
{
/* XXX We should pass the function name along in the future.
(winreg.c also wants to pass the function name.)
This would however require an additional param to the
Windows error object, which is non-trivial.
*/
errno = GetLastError();
if (filename)
return PyErr_SetFromWindowsErrWithFilename(errno, filename);
else
return PyErr_SetFromWindowsErr(errno);
}
static PyObject *
win32_error_object(const char* function, PyObject* filename)
{
/* XXX - see win32_error for comments on 'function' */
errno = GetLastError();
if (filename)
return PyErr_SetExcFromWindowsErrWithFilenameObject(
PyExc_OSError,
errno,
filename);
else
return PyErr_SetFromWindowsErr(errno);
}
static PyObject *
posix_path_object_error(PyObject *path)
{
return PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, path);
}
static PyObject *
path_object_error(PyObject *path)
{
#ifdef MS_WINDOWS
return PyErr_SetExcFromWindowsErrWithFilenameObject(
PyExc_OSError, 0, path);
#else
return posix_path_object_error(path);
#endif
}
static PyObject *
path_object_error2(PyObject *path, PyObject *path2)
{
#ifdef MS_WINDOWS
return PyErr_SetExcFromWindowsErrWithFilenameObjects(
PyExc_OSError, 0, path, path2);
#else
return PyErr_SetFromErrnoWithFilenameObjects(PyExc_OSError, path, path2);
#endif
}
static PyObject *
path_error(path_t *path)
{
return path_object_error(path->object);
}
static PyObject *
posix_path_error(path_t *path)
{
return posix_path_object_error(path->object);
}
static PyObject *
path_error2(path_t *path, path_t *path2)
{
return path_object_error2(path->object, path2->object);
}
/* POSIX generic methods */
static int
fildes_converter(PyObject *o, void *p)
{
int fd;
int *pointer = (int *)p;
fd = PyObject_AsFileDescriptor(o);
if (fd < 0)
return 0;
*pointer = fd;
return 1;
}
static PyObject *
posix_fildes_fd(int fd, int (*func)(int))
{
int res;
int async_err = 0;
do {
Py_BEGIN_ALLOW_THREADS
_Py_BEGIN_SUPPRESS_IPH
res = (*func)(fd);
_Py_END_SUPPRESS_IPH
Py_END_ALLOW_THREADS
} while (res != 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
if (res != 0)
return (!async_err) ? posix_error() : NULL;
Py_RETURN_NONE;
}
#ifdef MS_WINDOWS
/* This is a reimplementation of the C library's chdir function,
but one that produces Win32 errors instead of DOS error codes.
chdir is essentially a wrapper around SetCurrentDirectory; however,
it also needs to set "magic" environment variables indicating
the per-drive current directory, which are of the form =<drive>: */
static BOOL __stdcall
win32_wchdir(const char16_t * path)
{
wchar_t path_buf[MAX_PATH], *new_path = path_buf;
int result;
wchar_t env[4] = L"=x:";
if(!SetCurrentDirectoryW(path))
return FALSE;
result = GetCurrentDirectoryW(Py_ARRAY_LENGTH(path_buf), new_path);
if (!result)
return FALSE;
if (result > Py_ARRAY_LENGTH(path_buf)) {
new_path = PyMem_RawMalloc(result * sizeof(wchar_t));
if (!new_path) {
SetLastError(ERROR_OUTOFMEMORY);
return FALSE;
}
result = GetCurrentDirectoryW(result, new_path);
if (!result) {
PyMem_RawFree(new_path);
return FALSE;
}
}
int is_unc_like_path = (wcsncmp(new_path, L"\\\\", 2) == 0 ||
wcsncmp(new_path, L"//", 2) == 0);
if (!is_unc_like_path) {
env[1] = new_path[0];
result = SetEnvironmentVariableW(env, new_path);
}
if (new_path != path_buf)
PyMem_RawFree(new_path);
return result ? TRUE : FALSE;
}
#endif
#ifdef MS_WINDOWS
/* The CRT of Windows has a number of flaws wrt. its stat() implementation:
- time stamps are restricted to second resolution
- file modification times suffer from forth-and-back conversions between
UTC and local time
Therefore, we implement our own stat, based on the Win32 API directly.
*/
#define HAVE_STAT_NSEC 1
#define HAVE_STRUCT_STAT_ST_FILE_ATTRIBUTES 1
static void
find_data_to_file_info(WIN32_FIND_DATAW *pFileData,
BY_HANDLE_FILE_INFORMATION *info,
ULONG *reparse_tag)
{
bzero(info, sizeof(*info));
info->dwFileAttributes = pFileData->dwFileAttributes;
info->ftCreationTime = pFileData->ftCreationTime;
info->ftLastAccessTime = pFileData->ftLastAccessTime;
info->ftLastWriteTime = pFileData->ftLastWriteTime;
info->nFileSizeHigh = pFileData->nFileSizeHigh;
info->nFileSizeLow = pFileData->nFileSizeLow;
/* info->nNumberOfLinks = 1; */
if (pFileData->dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT)
*reparse_tag = pFileData->dwReserved0;
else
*reparse_tag = 0;
}
static BOOL
attributes_from_dir(const char16_t * pszFile, BY_HANDLE_FILE_INFORMATION *info, ULONG *reparse_tag)
{
HANDLE hFindFile;
WIN32_FIND_DATAW FileData;
hFindFile = FindFirstFileW(pszFile, &FileData);
if (hFindFile == INVALID_HANDLE_VALUE)
return FALSE;
FindClose(hFindFile);
find_data_to_file_info(&FileData, info, reparse_tag);
return TRUE;
}
static BOOL
get_target_path(HANDLE hdl, wchar_t **target_path)
{
int buf_size, result_length;
wchar_t *buf;
/* We have a good handle to the target, use it to determine
the target path name (then we'll call lstat on it). */
buf_size = GetFinalPathNameByHandle(hdl, 0, 0, kNtVolumeNameDos);
if(!buf_size)
return FALSE;
buf = (wchar_t *)PyMem_RawMalloc((buf_size + 1) * sizeof(wchar_t));
if (!buf) {
SetLastError(ERROR_OUTOFMEMORY);
return FALSE;
}
result_length = GetFinalPathNameByHandleW(hdl,
buf, buf_size, VOLUME_NAME_DOS);
if(!result_length) {
PyMem_RawFree(buf);
return FALSE;
}
if(!CloseHandle(hdl)) {
PyMem_RawFree(buf);
return FALSE;
}
buf[result_length] = 0;
*target_path = buf;
return TRUE;
}
static int
win32_xstat_impl(const wchar_t *path, struct _Py_stat_struct *result,
BOOL traverse)
{
int code;
HANDLE hFile, hFile2;
BY_HANDLE_FILE_INFORMATION info;
ULONG reparse_tag = 0;
wchar_t *target_path;
const wchar_t *dot;
hFile = CreateFileW(
path,
FILE_READ_ATTRIBUTES, /* desired access */
0, /* share mode */
NULL, /* security attributes */
OPEN_EXISTING,
/* FILE_FLAG_BACKUP_SEMANTICS is required to open a directory */
/* FILE_FLAG_OPEN_REPARSE_POINT does not follow the symlink.
Because of this, calls like GetFinalPathNameByHandle will return
the symlink path again and not the actual final path. */
FILE_ATTRIBUTE_NORMAL|FILE_FLAG_BACKUP_SEMANTICS|
FILE_FLAG_OPEN_REPARSE_POINT,
NULL);
if (hFile == INVALID_HANDLE_VALUE) {
/* Either the target doesn't exist, or we don't have access to
get a handle to it. If the former, we need to return an error.
If the latter, we can use attributes_from_dir. */
DWORD lastError = GetLastError();
if (lastError != ERROR_ACCESS_DENIED &&
lastError != ERROR_SHARING_VIOLATION)
return -1;
/* Could not get attributes on open file. Fall back to
reading the directory. */
if (!attributes_from_dir(path, &info, &reparse_tag))
/* Very strange. This should not fail now */
return -1;
if (info.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) {
if (traverse) {
/* Should traverse, but could not open reparse point handle */
SetLastError(lastError);
return -1;
}
}
} else {
if (!GetFileInformationByHandle(hFile, &info)) {
CloseHandle(hFile);
return -1;
}
if (info.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) {
if (!win32_get_reparse_tag(hFile, &reparse_tag))
return -1;
/* Close the outer open file handle now that we're about to
reopen it with different flags. */
if (!CloseHandle(hFile))
return -1;
if (traverse) {
/* In order to call GetFinalPathNameByHandle we need to open
the file without the reparse handling flag set. */
hFile2 = CreateFileW(
path, FILE_READ_ATTRIBUTES, FILE_SHARE_READ,
NULL, OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL|FILE_FLAG_BACKUP_SEMANTICS,
NULL);
if (hFile2 == INVALID_HANDLE_VALUE)
return -1;
if (!get_target_path(hFile2, &target_path))
return -1;
code = win32_xstat_impl(target_path, result, FALSE);
PyMem_RawFree(target_path);
return code;
}
} else
CloseHandle(hFile);
}
_Py_attribute_data_to_stat(&info, reparse_tag, result);
/* Set S_IEXEC if it is an .exe, .bat, ... */
dot = wcsrchr(path, '.');
if (dot) {
if (_wcsicmp(dot, L".bat") == 0 || _wcsicmp(dot, L".cmd") == 0 ||
_wcsicmp(dot, L".exe") == 0 || _wcsicmp(dot, L".com") == 0)
result->st_mode |= 0111;
}
return 0;
}
static int
win32_xstat(const wchar_t *path, struct _Py_stat_struct *result, BOOL traverse)
{
/* Protocol violation: we explicitly clear errno, instead of
setting it to a POSIX error. Callers should use GetLastError. */
int code = win32_xstat_impl(path, result, traverse);
errno = 0;
return code;
}
/* About the following functions: win32_lstat_w, win32_stat, win32_stat_w
In Posix, stat automatically traverses symlinks and returns the stat
structure for the target. In Windows, the equivalent GetFileAttributes by
default does not traverse symlinks and instead returns attributes for
the symlink.
Therefore, win32_lstat will get the attributes traditionally, and
win32_stat will first explicitly resolve the symlink target and then will
call win32_lstat on that result. */
static int
win32_lstat(const wchar_t* path, struct _Py_stat_struct *result)
{
return win32_xstat(path, result, FALSE);
}
static int
win32_stat(const wchar_t* path, struct _Py_stat_struct *result)
{
return win32_xstat(path, result, TRUE);
}
#endif /* MS_WINDOWS */
PyDoc_STRVAR(stat_result__doc__,
"stat_result: Result from stat, fstat, or lstat.\n\n\
This object may be accessed either as a tuple of\n\
(mode, ino, dev, nlink, uid, gid, size, atime, mtime, ctime)\n\
or via the attributes st_mode, st_ino, st_dev, st_nlink, st_uid, and so on.\n\
\n\
Posix/windows: If your platform supports st_blksize, st_blocks, st_rdev,\n\
or st_flags, they are available as attributes only.\n\
\n\
See os.stat for more information.");
static PyStructSequence_Field stat_result_fields[] = {
{"st_mode", PyDoc_STR("protection bits")},
{"st_ino", PyDoc_STR("inode")},
{"st_dev", PyDoc_STR("device")},
{"st_nlink", PyDoc_STR("number of hard links")},
{"st_uid", PyDoc_STR("user ID of owner")},
{"st_gid", PyDoc_STR("group ID of owner")},
{"st_size", PyDoc_STR("total size, in bytes")},
/* The NULL is replaced with PyStructSequence_UnnamedField later. */
{NULL, PyDoc_STR("integer time of last access")},
{NULL, PyDoc_STR("integer time of last modification")},
{NULL, PyDoc_STR("integer time of last change")},
{"st_atime", PyDoc_STR("time of last access")},
{"st_mtime", PyDoc_STR("time of last modification")},
{"st_ctime", PyDoc_STR("time of last change")},
{"st_atime_ns", PyDoc_STR("time of last access in nanoseconds")},
{"st_mtime_ns", PyDoc_STR("time of last modification in nanoseconds")},
{"st_ctime_ns", PyDoc_STR("time of last change in nanoseconds")},
#ifdef HAVE_STRUCT_STAT_ST_BLKSIZE
{"st_blksize", PyDoc_STR("blocksize for filesystem I/O")},
#endif
#ifdef HAVE_STRUCT_STAT_ST_BLOCKS
{"st_blocks", PyDoc_STR("number of blocks allocated")},
#endif
#ifdef HAVE_STRUCT_STAT_ST_RDEV
{"st_rdev", PyDoc_STR("device type (if inode device)")},
#endif
#ifdef HAVE_STRUCT_STAT_ST_FLAGS
{"st_flags", PyDoc_STR("user defined flags for file")},
#endif
#ifdef HAVE_STRUCT_STAT_ST_GEN
{"st_gen", PyDoc_STR("generation number")},
#endif
#ifdef HAVE_STRUCT_STAT_ST_BIRTHTIME
{"st_birthtime", PyDoc_STR("time of creation")},
#endif
#ifdef HAVE_STRUCT_STAT_ST_FILE_ATTRIBUTES
{"st_file_attributes", PyDoc_STR("Windows file attribute bits")},
#endif
{0}
};
#ifdef HAVE_STRUCT_STAT_ST_BLKSIZE
#define ST_BLKSIZE_IDX 16
#else
#define ST_BLKSIZE_IDX 15
#endif
#ifdef HAVE_STRUCT_STAT_ST_BLOCKS
#define ST_BLOCKS_IDX (ST_BLKSIZE_IDX+1)
#else
#define ST_BLOCKS_IDX ST_BLKSIZE_IDX
#endif
#ifdef HAVE_STRUCT_STAT_ST_RDEV
#define ST_RDEV_IDX (ST_BLOCKS_IDX+1)
#else
#define ST_RDEV_IDX ST_BLOCKS_IDX
#endif
#ifdef HAVE_STRUCT_STAT_ST_FLAGS
#define ST_FLAGS_IDX (ST_RDEV_IDX+1)
#else
#define ST_FLAGS_IDX ST_RDEV_IDX
#endif
#ifdef HAVE_STRUCT_STAT_ST_GEN
#define ST_GEN_IDX (ST_FLAGS_IDX+1)
#else
#define ST_GEN_IDX ST_FLAGS_IDX
#endif
#ifdef HAVE_STRUCT_STAT_ST_BIRTHTIME
#define ST_BIRTHTIME_IDX (ST_GEN_IDX+1)
#else
#define ST_BIRTHTIME_IDX ST_GEN_IDX
#endif
#ifdef HAVE_STRUCT_STAT_ST_FILE_ATTRIBUTES
#define ST_FILE_ATTRIBUTES_IDX (ST_BIRTHTIME_IDX+1)
#else
#define ST_FILE_ATTRIBUTES_IDX ST_BIRTHTIME_IDX
#endif
static PyStructSequence_Desc stat_result_desc = {
"stat_result", /* name */
stat_result__doc__, /* doc */
stat_result_fields,
10
};
PyDoc_STRVAR(statvfs_result__doc__,
"statvfs_result: Result from statvfs or fstatvfs.\n\n\
This object may be accessed either as a tuple of\n\
(bsize, frsize, blocks, bfree, bavail, files, ffree, favail, flag, namemax),\n\
or via the attributes f_bsize, f_frsize, f_blocks, f_bfree, and so on.\n\
\n\
See os.statvfs for more information.");
static PyStructSequence_Field statvfs_result_fields[] = {
{"f_bsize", },
{"f_frsize", },
{"f_blocks", },
{"f_bfree", },
{"f_bavail", },
{"f_files", },
{"f_ffree", },
{"f_favail", },
{"f_flag", },
{"f_namemax",},
{0}
};
static PyStructSequence_Desc statvfs_result_desc = {
"statvfs_result", /* name */
statvfs_result__doc__, /* doc */
statvfs_result_fields,
10
};
#if defined(HAVE_WAITID) && !defined(__APPLE__)
PyDoc_STRVAR(waitid_result__doc__,
"waitid_result: Result from waitid.\n\n\
This object may be accessed either as a tuple of\n\
(si_pid, si_uid, si_signo, si_status, si_code),\n\
or via the attributes si_pid, si_uid, and so on.\n\
\n\
See os.waitid for more information.");
static PyStructSequence_Field waitid_result_fields[] = {
{"si_pid", },
{"si_uid", },
{"si_signo", },
{"si_status", },
{"si_code", },
{0}
};
static PyStructSequence_Desc waitid_result_desc = {
"waitid_result", /* name */
waitid_result__doc__, /* doc */
waitid_result_fields,
5
};
static PyTypeObject WaitidResultType;
#endif
static int initialized;
static PyTypeObject StatResultType;
static PyTypeObject StatVFSResultType;
#if defined(HAVE_SCHED_SETPARAM) || defined(HAVE_SCHED_SETSCHEDULER)
static PyTypeObject SchedParamType;
#endif
static newfunc structseq_new;
static PyObject *
statresult_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
PyStructSequence *result;
int i;
result = (PyStructSequence*)structseq_new(type, args, kwds);
if (!result)
return NULL;
/* If we have been initialized from a tuple,
st_?time might be set to None. Initialize it
from the int slots. */
for (i = 7; i <= 9; i++) {
if (result->ob_item[i+3] == Py_None) {
Py_DECREF(Py_None);
Py_INCREF(result->ob_item[i]);
result->ob_item[i+3] = result->ob_item[i];
}
}
return (PyObject*)result;
}
/* If true, st_?time is float. */
static int _stat_float_times = 1;
PyDoc_STRVAR(stat_float_times__doc__,
"stat_float_times([newval]) -> oldval\n\n\
Determine whether os.[lf]stat represents time stamps as float objects.\n\
\n\
If value is True, future calls to stat() return floats; if it is False,\n\
future calls return ints.\n\
If value is omitted, return the current setting.\n");
/* AC 3.5: the public default value should be None, not ready for that yet */
static PyObject*
stat_float_times(PyObject* self, PyObject *args)
{
int newval = -1;
if (!PyArg_ParseTuple(args, "|i:stat_float_times", &newval))
return NULL;
if (PyErr_WarnEx(PyExc_DeprecationWarning,
"stat_float_times() is deprecated",
1))
return NULL;
if (newval == -1)
/* Return old value */
return PyBool_FromLong(_stat_float_times);
_stat_float_times = newval;
Py_INCREF(Py_None);
return Py_None;
}
static PyObject *billion = NULL;
static void
fill_time(PyObject *v, int index, time_t sec, unsigned long nsec)
{
PyObject *s = _PyLong_FromTime_t(sec);
PyObject *ns_fractional = PyLong_FromUnsignedLong(nsec);
PyObject *s_in_ns = NULL;
PyObject *ns_total = NULL;
PyObject *float_s = NULL;
if (!(s && ns_fractional))
goto exit;
s_in_ns = PyNumber_Multiply(s, billion);
if (!s_in_ns)
goto exit;
ns_total = PyNumber_Add(s_in_ns, ns_fractional);
if (!ns_total)
goto exit;
if (_stat_float_times) {
float_s = PyFloat_FromDouble(sec + 1e-9*nsec);
if (!float_s)
goto exit;
}
else {
float_s = s;
Py_INCREF(float_s);
}
PyStructSequence_SET_ITEM(v, index, s);
PyStructSequence_SET_ITEM(v, index+3, float_s);
PyStructSequence_SET_ITEM(v, index+6, ns_total);
s = NULL;
float_s = NULL;
ns_total = NULL;
exit:
Py_XDECREF(s);
Py_XDECREF(ns_fractional);
Py_XDECREF(s_in_ns);
Py_XDECREF(ns_total);
Py_XDECREF(float_s);
}
/* pack a system stat C structure into the Python stat tuple
(used by posix_stat() and posix_fstat()) */
static PyObject*
_pystat_fromstructstat(STRUCT_STAT *st)
{
unsigned long ansec, mnsec, cnsec;
PyObject *v = PyStructSequence_New(&StatResultType);
if (v == NULL)
return NULL;
PyStructSequence_SET_ITEM(v, 0, PyLong_FromLong((long)st->st_mode));
Py_BUILD_ASSERT(sizeof(unsigned long long) >= sizeof(st->st_ino));
PyStructSequence_SET_ITEM(v, 1, PyLong_FromUnsignedLongLong(st->st_ino));
#ifdef MS_WINDOWS
PyStructSequence_SET_ITEM(v, 2, PyLong_FromUnsignedLong(st->st_dev));
#else
PyStructSequence_SET_ITEM(v, 2, _PyLong_FromDev(st->st_dev));
#endif
PyStructSequence_SET_ITEM(v, 3, PyLong_FromLong((long)st->st_nlink));
#if defined(MS_WINDOWS)
PyStructSequence_SET_ITEM(v, 4, PyLong_FromLong(0));
PyStructSequence_SET_ITEM(v, 5, PyLong_FromLong(0));
#else
PyStructSequence_SET_ITEM(v, 4, _PyLong_FromUid(st->st_uid));
PyStructSequence_SET_ITEM(v, 5, _PyLong_FromGid(st->st_gid));
#endif
Py_BUILD_ASSERT(sizeof(long long) >= sizeof(st->st_size));
PyStructSequence_SET_ITEM(v, 6, PyLong_FromLongLong(st->st_size));
#if defined(HAVE_STAT_TV_NSEC)
ansec = st->st_atim.tv_nsec;
mnsec = st->st_mtim.tv_nsec;
cnsec = st->st_ctim.tv_nsec;
#elif defined(HAVE_STAT_TV_NSEC2)
ansec = st->st_atimespec.tv_nsec;
mnsec = st->st_mtimespec.tv_nsec;
cnsec = st->st_ctimespec.tv_nsec;
#elif defined(HAVE_STAT_NSEC)
ansec = st->st_atime_nsec;
mnsec = st->st_mtime_nsec;
cnsec = st->st_ctime_nsec;
#else
ansec = mnsec = cnsec = 0;
#endif
fill_time(v, 7, st->st_atime, ansec);
fill_time(v, 8, st->st_mtime, mnsec);
fill_time(v, 9, st->st_ctime, cnsec);
#ifdef HAVE_STRUCT_STAT_ST_BLKSIZE
PyStructSequence_SET_ITEM(v, ST_BLKSIZE_IDX,
PyLong_FromLong((long)st->st_blksize));
#endif
#ifdef HAVE_STRUCT_STAT_ST_BLOCKS
PyStructSequence_SET_ITEM(v, ST_BLOCKS_IDX,
PyLong_FromLong((long)st->st_blocks));
#endif
#ifdef HAVE_STRUCT_STAT_ST_RDEV
PyStructSequence_SET_ITEM(v, ST_RDEV_IDX,
PyLong_FromLong((long)st->st_rdev));
#endif
#ifdef HAVE_STRUCT_STAT_ST_GEN
PyStructSequence_SET_ITEM(v, ST_GEN_IDX,
PyLong_FromLong((long)st->st_gen));
#endif
#ifdef HAVE_STRUCT_STAT_ST_BIRTHTIME
{
PyObject *val;
unsigned long bsec,bnsec;
bsec = (long)st->st_birthtime;
#ifdef HAVE_STAT_TV_NSEC2
bnsec = st->st_birthtimespec.tv_nsec;
#else
bnsec = 0;
#endif
if (_stat_float_times) {
val = PyFloat_FromDouble(bsec + 1e-9*bnsec);
} else {
val = PyLong_FromLong((long)bsec);
}
PyStructSequence_SET_ITEM(v, ST_BIRTHTIME_IDX,
val);
}
#endif
#ifdef HAVE_STRUCT_STAT_ST_FLAGS
PyStructSequence_SET_ITEM(v, ST_FLAGS_IDX,
PyLong_FromLong((long)st->st_flags));
#endif
#ifdef HAVE_STRUCT_STAT_ST_FILE_ATTRIBUTES
PyStructSequence_SET_ITEM(v, ST_FILE_ATTRIBUTES_IDX,
PyLong_FromUnsignedLong(st->st_file_attributes));
#endif
if (PyErr_Occurred()) {
Py_DECREF(v);
return NULL;
}
return v;
}
static PyObject *
posix_do_stat(const char *function_name, path_t *path,
int dir_fd, int follow_symlinks)
{
STRUCT_STAT st;
int result;
#if !defined(MS_WINDOWS) && !defined(HAVE_FSTATAT) && !defined(HAVE_LSTAT)
if (follow_symlinks_specified(function_name, follow_symlinks))
return NULL;
#endif
if (path_and_dir_fd_invalid("stat", path, dir_fd) ||
dir_fd_and_fd_invalid("stat", dir_fd, path->fd) ||
fd_and_follow_symlinks_invalid("stat", path->fd, follow_symlinks))
return NULL;
Py_BEGIN_ALLOW_THREADS
if (path->fd != -1)
result = FSTAT(path->fd, &st);
#ifdef MS_WINDOWS
else if (follow_symlinks)
result = win32_stat(path->wide, &st);
else
result = win32_lstat(path->wide, &st);
#else
else
#if defined(HAVE_LSTAT)
if ((!follow_symlinks) && (dir_fd == DEFAULT_DIR_FD))
result = LSTAT(path->narrow, &st);
else
#endif /* HAVE_LSTAT */
#ifdef HAVE_FSTATAT
if ((dir_fd != DEFAULT_DIR_FD) || !follow_symlinks)
result = fstatat(dir_fd, path->narrow, &st,
follow_symlinks ? 0 : AT_SYMLINK_NOFOLLOW);
else
#endif /* HAVE_FSTATAT */
result = STAT(path->narrow, &st);
#endif /* MS_WINDOWS */
Py_END_ALLOW_THREADS
if (result != 0) {
return path_error(path);
}
return _pystat_fromstructstat(&st);
}
/*[python input]
for s in """
FACCESSAT
FCHMODAT
FCHOWNAT
FSTATAT
LINKAT
MKDIRAT
MKFIFOAT
MKNODAT
OPENAT
READLINKAT
SYMLINKAT
UNLINKAT
""".strip().split():
s = s.strip()
print("""
#ifdef HAVE_{s}
#define {s}_DIR_FD_CONVERTER dir_fd_converter
#else
#define {s}_DIR_FD_CONVERTER dir_fd_unavailable
#endif
""".rstrip().format(s=s))
for s in """
FCHDIR
FCHMOD
FCHOWN
FDOPENDIR
FEXECVE
FPATHCONF
FSTATVFS
FTRUNCATE
""".strip().split():
s = s.strip()
print("""
#ifdef HAVE_{s}
#define PATH_HAVE_{s} 1
#else
#define PATH_HAVE_{s} 0
#endif
""".rstrip().format(s=s))
[python start generated code]*/
#ifdef HAVE_FACCESSAT
#define FACCESSAT_DIR_FD_CONVERTER dir_fd_converter
#else
#define FACCESSAT_DIR_FD_CONVERTER dir_fd_unavailable
#endif
#ifdef HAVE_FCHMODAT
#define FCHMODAT_DIR_FD_CONVERTER dir_fd_converter
#else
#define FCHMODAT_DIR_FD_CONVERTER dir_fd_unavailable
#endif
#ifdef HAVE_FCHOWNAT
#define FCHOWNAT_DIR_FD_CONVERTER dir_fd_converter
#else
#define FCHOWNAT_DIR_FD_CONVERTER dir_fd_unavailable
#endif
#ifdef HAVE_FSTATAT
#define FSTATAT_DIR_FD_CONVERTER dir_fd_converter
#else
#define FSTATAT_DIR_FD_CONVERTER dir_fd_unavailable
#endif
#ifdef HAVE_LINKAT
#define LINKAT_DIR_FD_CONVERTER dir_fd_converter
#else
#define LINKAT_DIR_FD_CONVERTER dir_fd_unavailable
#endif
#ifdef HAVE_MKDIRAT
#define MKDIRAT_DIR_FD_CONVERTER dir_fd_converter
#else
#define MKDIRAT_DIR_FD_CONVERTER dir_fd_unavailable
#endif
#ifdef HAVE_MKFIFOAT
#define MKFIFOAT_DIR_FD_CONVERTER dir_fd_converter
#else
#define MKFIFOAT_DIR_FD_CONVERTER dir_fd_unavailable
#endif
#ifdef HAVE_MKNODAT
#define MKNODAT_DIR_FD_CONVERTER dir_fd_converter
#else
#define MKNODAT_DIR_FD_CONVERTER dir_fd_unavailable
#endif
#ifdef HAVE_OPENAT
#define OPENAT_DIR_FD_CONVERTER dir_fd_converter
#else
#define OPENAT_DIR_FD_CONVERTER dir_fd_unavailable
#endif
#ifdef HAVE_READLINKAT
#define READLINKAT_DIR_FD_CONVERTER dir_fd_converter
#else
#define READLINKAT_DIR_FD_CONVERTER dir_fd_unavailable
#endif
#ifdef HAVE_SYMLINKAT
#define SYMLINKAT_DIR_FD_CONVERTER dir_fd_converter
#else
#define SYMLINKAT_DIR_FD_CONVERTER dir_fd_unavailable
#endif
#ifdef HAVE_UNLINKAT
#define UNLINKAT_DIR_FD_CONVERTER dir_fd_converter
#else
#define UNLINKAT_DIR_FD_CONVERTER dir_fd_unavailable
#endif
#ifdef HAVE_FCHDIR
#define PATH_HAVE_FCHDIR 1
#else
#define PATH_HAVE_FCHDIR 0
#endif
#ifdef HAVE_FCHMOD
#define PATH_HAVE_FCHMOD 1
#else
#define PATH_HAVE_FCHMOD 0
#endif
#ifdef HAVE_FCHOWN
#define PATH_HAVE_FCHOWN 1
#else
#define PATH_HAVE_FCHOWN 0
#endif
#ifdef HAVE_FDOPENDIR
#define PATH_HAVE_FDOPENDIR 1
#else
#define PATH_HAVE_FDOPENDIR 0
#endif
#ifdef HAVE_FEXECVE
#define PATH_HAVE_FEXECVE 1
#else
#define PATH_HAVE_FEXECVE 0
#endif
#ifdef HAVE_FPATHCONF
#define PATH_HAVE_FPATHCONF 1
#else
#define PATH_HAVE_FPATHCONF 0
#endif
#ifdef HAVE_FSTATVFS
#define PATH_HAVE_FSTATVFS 1
#else
#define PATH_HAVE_FSTATVFS 0
#endif
#ifdef HAVE_FTRUNCATE
#define PATH_HAVE_FTRUNCATE 1
#else
#define PATH_HAVE_FTRUNCATE 0
#endif
/*[python end generated code: output=4bd4f6f7d41267f1 input=80b4c890b6774ea5]*/
#ifdef MS_WINDOWS
#undef PATH_HAVE_FTRUNCATE
#define PATH_HAVE_FTRUNCATE 1
#endif
/*[python input]
class path_t_converter(CConverter):
type = "path_t"
impl_by_reference = True
parse_by_reference = True
converter = 'path_converter'
def converter_init(self, *, allow_fd=False, nullable=False):
# right now path_t doesn't support default values.
# to support a default value, you'll need to override initialize().
if self.default not in (unspecified, None):
fail("Can't specify a default to the path_t converter!")
if self.c_default not in (None, 'Py_None'):
raise RuntimeError("Can't specify a c_default to the path_t converter!")
self.nullable = nullable
self.allow_fd = allow_fd
def pre_render(self):
def strify(value):
if isinstance(value, str):
return value
return str(int(bool(value)))
# add self.py_name here when merging with posixmodule conversion
self.c_default = 'PATH_T_INITIALIZE("{}", "{}", {}, {})'.format(
self.function.name,
self.name,
strify(self.nullable),
strify(self.allow_fd),
)
def cleanup(self):
return "path_cleanup(&" + self.name + ");\n"
class dir_fd_converter(CConverter):
type = 'int'
def converter_init(self, requires=None):
if self.default in (unspecified, None):
self.c_default = 'DEFAULT_DIR_FD'
if isinstance(requires, str):
self.converter = requires.upper() + '_DIR_FD_CONVERTER'
else:
self.converter = 'dir_fd_converter'
class fildes_converter(CConverter):
type = 'int'
converter = 'fildes_converter'
class uid_t_converter(CConverter):
type = "uid_t"
converter = '_Py_Uid_Converter'
class gid_t_converter(CConverter):
type = "gid_t"
converter = '_Py_Gid_Converter'
class dev_t_converter(CConverter):
type = 'dev_t'
converter = '_Py_Dev_Converter'
class dev_t_return_converter(unsigned_long_return_converter):
type = 'dev_t'
conversion_fn = '_PyLong_FromDev'
unsigned_cast = '(dev_t)'
class FSConverter_converter(CConverter):
type = 'PyObject *'
converter = 'PyUnicode_FSConverter'
def converter_init(self):
if self.default is not unspecified:
fail("FSConverter_converter does not support default values")
self.c_default = 'NULL'
def cleanup(self):
return "Py_XDECREF(" + self.name + ");\n"
class pid_t_converter(CConverter):
type = 'pid_t'
format_unit = '" _Py_PARSE_PID "'
class idtype_t_converter(int_converter):
type = 'idtype_t'
class id_t_converter(CConverter):
type = 'id_t'
format_unit = '" _Py_PARSE_PID "'
class intptr_t_converter(CConverter):
type = 'intptr_t'
format_unit = '" _Py_PARSE_INTPTR "'
class Py_off_t_converter(CConverter):
type = 'Py_off_t'
converter = 'Py_off_t_converter'
class Py_off_t_return_converter(long_return_converter):
type = 'Py_off_t'
conversion_fn = 'PyLong_FromPy_off_t'
class path_confname_converter(CConverter):
type="int"
converter="conv_path_confname"
class confstr_confname_converter(path_confname_converter):
converter='conv_confstr_confname'
class sysconf_confname_converter(path_confname_converter):
converter="conv_sysconf_confname"
class sched_param_converter(CConverter):
type = 'struct sched_param'
converter = 'convert_sched_param'
impl_by_reference = True;
[python start generated code]*/
/*[python end generated code: output=da39a3ee5e6b4b0d input=418fce0e01144461]*/
/*[clinic input]
os.stat
path : path_t(allow_fd=True)
Path to be examined; can be string, bytes, a path-like object or
open-file-descriptor int.
*
dir_fd : dir_fd(requires='fstatat') = None
If not None, it should be a file descriptor open to a directory,
and path should be a relative string; path will then be relative to
that directory.
follow_symlinks: bool = True
If False, and the last element of the path is a symbolic link,
stat will examine the symbolic link itself instead of the file
the link points to.
Perform a stat system call on the given path.
dir_fd and follow_symlinks may not be implemented
on your platform. If they are unavailable, using them will raise a
NotImplementedError.
It's an error to use dir_fd or follow_symlinks when specifying path as
an open file descriptor.
[clinic start generated code]*/
static PyObject *
os_stat_impl(PyObject *module, path_t *path, int dir_fd, int follow_symlinks)
/*[clinic end generated code: output=7d4976e6f18a59c5 input=01d362ebcc06996b]*/
{
return posix_do_stat("stat", path, dir_fd, follow_symlinks);
}
/*[clinic input]
os.lstat
path : path_t
*
dir_fd : dir_fd(requires='fstatat') = None
Perform a stat system call on the given path, without following symbolic links.
Like stat(), but do not follow symbolic links.
Equivalent to stat(path, follow_symlinks=False).
[clinic start generated code]*/
static PyObject *
os_lstat_impl(PyObject *module, path_t *path, int dir_fd)
/*[clinic end generated code: output=ef82a5d35ce8ab37 input=0b7474765927b925]*/
{
int follow_symlinks = 0;
return posix_do_stat("lstat", path, dir_fd, follow_symlinks);
}
/*[clinic input]
os.access -> bool
path: path_t
Path to be tested; can be string, bytes, or a path-like object.
mode: int
Operating-system mode bitfield. Can be F_OK to test existence,
or the inclusive-OR of R_OK, W_OK, and X_OK.
*
dir_fd : dir_fd(requires='faccessat') = None
If not None, it should be a file descriptor open to a directory,
and path should be relative; path will then be relative to that
directory.
effective_ids: bool = False
If True, access will use the effective uid/gid instead of
the real uid/gid.
follow_symlinks: bool = True
If False, and the last element of the path is a symbolic link,
access will examine the symbolic link itself instead of the file
the link points to.
Use the real uid/gid to test for access to a path.
{parameters}
dir_fd, effective_ids, and follow_symlinks may not be implemented
on your platform. If they are unavailable, using them will raise a
NotImplementedError.
Note that most operations will use the effective uid/gid, therefore this
routine can be used in a suid/sgid environment to test if the invoking user
has the specified access to the path.
[clinic start generated code]*/
static int
os_access_impl(PyObject *module, path_t *path, int mode, int dir_fd,
int effective_ids, int follow_symlinks)
/*[clinic end generated code: output=cf84158bc90b1a77 input=3ffe4e650ee3bf20]*/
{
int return_value;
#ifdef MS_WINDOWS
DWORD attr;
#else
int result;
#endif
#ifndef HAVE_FACCESSAT
if (follow_symlinks_specified("access", follow_symlinks))
return -1;
if (effective_ids) {
argument_unavailable_error("access", "effective_ids");
return -1;
}
#endif
#ifdef MS_WINDOWS
Py_BEGIN_ALLOW_THREADS
attr = GetFileAttributesW(path->wide);
Py_END_ALLOW_THREADS
/*
* Access is possible if
* * we didn't get a -1, and
* * write access wasn't requested,
* * or the file isn't read-only,
* * or it's a directory.
* (Directories cannot be read-only on Windows.)
*/
return_value = (attr != INVALID_FILE_ATTRIBUTES) &&
(!(mode & 2) ||
!(attr & FILE_ATTRIBUTE_READONLY) ||
(attr & FILE_ATTRIBUTE_DIRECTORY));
#else
Py_BEGIN_ALLOW_THREADS
#ifdef HAVE_FACCESSAT
if ((dir_fd != DEFAULT_DIR_FD) ||
effective_ids ||
!follow_symlinks) {
int flags = 0;
if (!follow_symlinks)
flags |= AT_SYMLINK_NOFOLLOW;
if (effective_ids)
flags |= AT_EACCESS;
result = faccessat(dir_fd, path->narrow, mode, flags);
}
else
#endif
result = access(path->narrow, mode);
Py_END_ALLOW_THREADS
return_value = !result;
#endif
return return_value;
}
#ifndef F_OK
#define F_OK 0
#endif
#ifndef R_OK
#define R_OK 4
#endif
#ifndef W_OK
#define W_OK 2
#endif
#ifndef X_OK
#define X_OK 1
#endif
#ifdef HAVE_TTYNAME
/*[clinic input]
os.ttyname -> DecodeFSDefault
fd: int
Integer file descriptor handle.
/
Return the name of the terminal device connected to 'fd'.
[clinic start generated code]*/
static char *
os_ttyname_impl(PyObject *module, int fd)
/*[clinic end generated code: output=ed16ad216d813591 input=5f72ca83e76b3b45]*/
{
char *ret;
ret = ttyname(fd);
if (ret == NULL)
posix_error();
return ret;
}
#endif
#ifdef HAVE_CTERMID
/*[clinic input]
os.ctermid
Return the name of the controlling terminal for this process.
[clinic start generated code]*/
static PyObject *
os_ctermid_impl(PyObject *module)
/*[clinic end generated code: output=02f017e6c9e620db input=3b87fdd52556382d]*/
{
char *ret;
char buffer[L_ctermid];
#ifdef USE_CTERMID_R
ret = ctermid_r(buffer);
#else
ret = ctermid(buffer);
#endif
if (ret == NULL)
return posix_error();
return PyUnicode_DecodeFSDefault(buffer);
}
#endif /* HAVE_CTERMID */
/*[clinic input]
os.chdir
path: path_t(allow_fd='PATH_HAVE_FCHDIR')
Change the current working directory to the specified path.
path may always be specified as a string.
On some platforms, path may also be specified as an open file descriptor.
If this functionality is unavailable, using it raises an exception.
[clinic start generated code]*/
static PyObject *
os_chdir_impl(PyObject *module, path_t *path)
/*[clinic end generated code: output=3be6400eee26eaae input=1a4a15b4d12cb15d]*/
{
int result;
Py_BEGIN_ALLOW_THREADS
#ifdef MS_WINDOWS
/* on unix, success = 0, on windows, success = !0 */
result = !win32_wchdir(path->wide);
#else
#ifdef HAVE_FCHDIR
if (path->fd != -1)
result = fchdir(path->fd);
else
#endif
result = chdir(path->narrow);
#endif
Py_END_ALLOW_THREADS
if (result) {
return path_error(path);
}
Py_RETURN_NONE;
}
#ifdef HAVE_FCHDIR
/*[clinic input]
os.fchdir
fd: fildes
Change to the directory of the given file descriptor.
fd must be opened on a directory, not a file.
Equivalent to os.chdir(fd).
[clinic start generated code]*/
static PyObject *
os_fchdir_impl(PyObject *module, int fd)
/*[clinic end generated code: output=42e064ec4dc00ab0 input=18e816479a2fa985]*/
{
return posix_fildes_fd(fd, fchdir);
}
#endif /* HAVE_FCHDIR */
/*[clinic input]
os.chmod
path: path_t(allow_fd='PATH_HAVE_FCHMOD')
Path to be modified. May always be specified as a str, bytes, or a path-like object.
On some platforms, path may also be specified as an open file descriptor.
If this functionality is unavailable, using it raises an exception.
mode: int
Operating-system mode bitfield.
*
dir_fd : dir_fd(requires='fchmodat') = None
If not None, it should be a file descriptor open to a directory,
and path should be relative; path will then be relative to that
directory.
follow_symlinks: bool = True
If False, and the last element of the path is a symbolic link,
chmod will modify the symbolic link itself instead of the file
the link points to.
Change the access permissions of a file.
It is an error to use dir_fd or follow_symlinks when specifying path as
an open file descriptor.
dir_fd and follow_symlinks may not be implemented on your platform.
If they are unavailable, using them will raise a NotImplementedError.
[clinic start generated code]*/
static PyObject *
os_chmod_impl(PyObject *module, path_t *path, int mode, int dir_fd,
int follow_symlinks)
/*[clinic end generated code: output=5cf6a94915cc7bff input=989081551c00293b]*/
{
int result;
#ifdef MS_WINDOWS
DWORD attr;
#endif
#ifdef HAVE_FCHMODAT
int fchmodat_nofollow_unsupported = 0;
#endif
#if !(defined(HAVE_FCHMODAT) || defined(HAVE_LCHMOD))
if (follow_symlinks_specified("chmod", follow_symlinks))
return NULL;
#endif
#ifdef MS_WINDOWS
Py_BEGIN_ALLOW_THREADS
attr = GetFileAttributesW(path->wide);
if (attr == INVALID_FILE_ATTRIBUTES)
result = 0;
else {
if (mode & _S_IWRITE)
attr &= ~FILE_ATTRIBUTE_READONLY;
else
attr |= FILE_ATTRIBUTE_READONLY;
result = SetFileAttributesW(path->wide, attr);
}
Py_END_ALLOW_THREADS
if (!result) {
return path_error(path);
}
#else /* MS_WINDOWS */
Py_BEGIN_ALLOW_THREADS
#ifdef HAVE_FCHMOD
if (path->fd != -1)
result = fchmod(path->fd, mode);
else
#endif
#ifdef HAVE_LCHMOD
if ((!follow_symlinks) && (dir_fd == DEFAULT_DIR_FD))
result = lchmod(path->narrow, mode);
else
#endif
#ifdef HAVE_FCHMODAT
if ((dir_fd != DEFAULT_DIR_FD) || !follow_symlinks) {
/*
* fchmodat() doesn't currently support AT_SYMLINK_NOFOLLOW!
* The documentation specifically shows how to use it,
* and then says it isn't implemented yet.
* (true on linux with glibc 2.15, and openindiana 3.x)
*
* Once it is supported, os.chmod will automatically
* support dir_fd and follow_symlinks=False. (Hopefully.)
* Until then, we need to be careful what exception we raise.
*/
result = fchmodat(dir_fd, path->narrow, mode,
follow_symlinks ? 0 : AT_SYMLINK_NOFOLLOW);
/*
* But wait! We can't throw the exception without allowing threads,
* and we can't do that in this nested scope. (Macro trickery, sigh.)
*/
fchmodat_nofollow_unsupported =
result &&
((errno == ENOTSUP) || (errno == EOPNOTSUPP)) &&
!follow_symlinks;
}
else
#endif
result = chmod(path->narrow, mode);
Py_END_ALLOW_THREADS
if (result) {
#ifdef HAVE_FCHMODAT
if (fchmodat_nofollow_unsupported) {
if (dir_fd != DEFAULT_DIR_FD)
dir_fd_and_follow_symlinks_invalid("chmod",
dir_fd, follow_symlinks);
else
follow_symlinks_specified("chmod", follow_symlinks);
return NULL;
}
else
#endif
return path_error(path);
}
#endif
Py_RETURN_NONE;
}
#ifdef HAVE_FCHMOD
/*[clinic input]
os.fchmod
fd: int
mode: int
Change the access permissions of the file given by file descriptor fd.
Equivalent to os.chmod(fd, mode).
[clinic start generated code]*/
static PyObject *
os_fchmod_impl(PyObject *module, int fd, int mode)
/*[clinic end generated code: output=afd9bc05b4e426b3 input=8ab11975ca01ee5b]*/
{
int res;
int async_err = 0;
do {
Py_BEGIN_ALLOW_THREADS
res = fchmod(fd, mode);
Py_END_ALLOW_THREADS
} while (res != 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
if (res != 0)
return (!async_err) ? posix_error() : NULL;
Py_RETURN_NONE;
}
#endif /* HAVE_FCHMOD */
#ifdef HAVE_LCHMOD
/*[clinic input]
os.lchmod
path: path_t
mode: int
Change the access permissions of a file, without following symbolic links.
If path is a symlink, this affects the link itself rather than the target.
Equivalent to chmod(path, mode, follow_symlinks=False)."
[clinic start generated code]*/
static PyObject *
os_lchmod_impl(PyObject *module, path_t *path, int mode)
/*[clinic end generated code: output=082344022b51a1d5 input=90c5663c7465d24f]*/
{
int res;
Py_BEGIN_ALLOW_THREADS
res = lchmod(path->narrow, mode);
Py_END_ALLOW_THREADS
if (res < 0) {
path_error(path);
return NULL;
}
Py_RETURN_NONE;
}
#endif /* HAVE_LCHMOD */
#ifdef HAVE_CHFLAGS
/*[clinic input]
os.chflags
path: path_t
flags: unsigned_long(bitwise=True)
follow_symlinks: bool=True
Set file flags.
If follow_symlinks is False, and the last element of the path is a symbolic
link, chflags will change flags on the symbolic link itself instead of the
file the link points to.
follow_symlinks may not be implemented on your platform. If it is
unavailable, using it will raise a NotImplementedError.
[clinic start generated code]*/
static PyObject *
os_chflags_impl(PyObject *module, path_t *path, unsigned long flags,
int follow_symlinks)
/*[clinic end generated code: output=85571c6737661ce9 input=0327e29feb876236]*/
{
int result;
#ifndef HAVE_LCHFLAGS
if (follow_symlinks_specified("chflags", follow_symlinks))
return NULL;
#endif
Py_BEGIN_ALLOW_THREADS
#ifdef HAVE_LCHFLAGS
if (!follow_symlinks)
result = lchflags(path->narrow, flags);
else
#endif
result = chflags(path->narrow, flags);
Py_END_ALLOW_THREADS
if (result)
return path_error(path);
Py_RETURN_NONE;
}
#endif /* HAVE_CHFLAGS */
#ifdef HAVE_LCHFLAGS
/*[clinic input]
os.lchflags
path: path_t
flags: unsigned_long(bitwise=True)
Set file flags.
This function will not follow symbolic links.
Equivalent to chflags(path, flags, follow_symlinks=False).
[clinic start generated code]*/
static PyObject *
os_lchflags_impl(PyObject *module, path_t *path, unsigned long flags)
/*[clinic end generated code: output=30ae958695c07316 input=f9f82ea8b585ca9d]*/
{
int res;
Py_BEGIN_ALLOW_THREADS
res = lchflags(path->narrow, flags);
Py_END_ALLOW_THREADS
if (res < 0) {
return path_error(path);
}
Py_RETURN_NONE;
}
#endif /* HAVE_LCHFLAGS */
#ifdef HAVE_CHROOT
/*[clinic input]
os.chroot
path: path_t
Change root directory to path.
[clinic start generated code]*/
static PyObject *
os_chroot_impl(PyObject *module, path_t *path)
/*[clinic end generated code: output=de80befc763a4475 input=14822965652c3dc3]*/
{
int res;
Py_BEGIN_ALLOW_THREADS
res = chroot(path->narrow);
Py_END_ALLOW_THREADS
if (res < 0)
return path_error(path);
Py_RETURN_NONE;
}
#endif /* HAVE_CHROOT */
#ifdef HAVE_FSYNC
/*[clinic input]
os.fsync
fd: fildes
Force write of fd to disk.
[clinic start generated code]*/
static PyObject *
os_fsync_impl(PyObject *module, int fd)
/*[clinic end generated code: output=4a10d773f52b3584 input=21c3645c056967f2]*/
{
return posix_fildes_fd(fd, fsync);
}
#endif /* HAVE_FSYNC */
#ifdef HAVE_SYNC
/*[clinic input]
os.sync
Force write of everything to disk.
[clinic start generated code]*/
static PyObject *
os_sync_impl(PyObject *module)
/*[clinic end generated code: output=2796b1f0818cd71c input=84749fe5e9b404ff]*/
{
Py_BEGIN_ALLOW_THREADS
sync();
Py_END_ALLOW_THREADS
Py_RETURN_NONE;
}
#endif /* HAVE_SYNC */
#ifdef HAVE_FDATASYNC
#ifdef __hpux
extern int fdatasync(int); /* On HP-UX, in libc but not in unistd.h */
#endif
/*[clinic input]
os.fdatasync
fd: fildes
Force write of fd to disk without forcing update of metadata.
[clinic start generated code]*/
static PyObject *
os_fdatasync_impl(PyObject *module, int fd)
/*[clinic end generated code: output=b4b9698b5d7e26dd input=bc74791ee54dd291]*/
{
return posix_fildes_fd(fd, fdatasync);
}
#endif /* HAVE_FDATASYNC */
#ifdef HAVE_CHOWN
/*[clinic input]
os.chown
path : path_t(allow_fd='PATH_HAVE_FCHOWN')
Path to be examined; can be string, bytes, a path-like object, or open-file-descriptor int.
uid: uid_t
gid: gid_t
*
dir_fd : dir_fd(requires='fchownat') = None
If not None, it should be a file descriptor open to a directory,
and path should be relative; path will then be relative to that
directory.
follow_symlinks: bool = True
If False, and the last element of the path is a symbolic link,
stat will examine the symbolic link itself instead of the file
the link points to.
Change the owner and group id of path to the numeric uid and gid.\
path may always be specified as a string.
On some platforms, path may also be specified as an open file descriptor.
If this functionality is unavailable, using it raises an exception.
If dir_fd is not None, it should be a file descriptor open to a directory,
and path should be relative; path will then be relative to that directory.
If follow_symlinks is False, and the last element of the path is a symbolic
link, chown will modify the symbolic link itself instead of the file the
link points to.
It is an error to use dir_fd or follow_symlinks when specifying path as
an open file descriptor.
dir_fd and follow_symlinks may not be implemented on your platform.
If they are unavailable, using them will raise a NotImplementedError.
[clinic start generated code]*/
static PyObject *
os_chown_impl(PyObject *module, path_t *path, uid_t uid, gid_t gid,
int dir_fd, int follow_symlinks)
/*[clinic end generated code: output=4beadab0db5f70cd input=b08c5ec67996a97d]*/
{
int result;
#if !(defined(HAVE_LCHOWN) || defined(HAVE_FCHOWNAT))
if (follow_symlinks_specified("chown", follow_symlinks))
return NULL;
#endif
if (dir_fd_and_fd_invalid("chown", dir_fd, path->fd) ||
fd_and_follow_symlinks_invalid("chown", path->fd, follow_symlinks))
return NULL;
#ifdef __APPLE__
/*
* This is for Mac OS X 10.3, which doesn't have lchown.
* (But we still have an lchown symbol because of weak-linking.)
* It doesn't have fchownat either. So there's no possibility
* of a graceful failover.
*/
if ((!follow_symlinks) && (lchown == NULL)) {
follow_symlinks_specified("chown", follow_symlinks);
return NULL;
}
#endif
Py_BEGIN_ALLOW_THREADS
#ifdef HAVE_FCHOWN
if (path->fd != -1)
result = fchown(path->fd, uid, gid);
else
#endif
#ifdef HAVE_LCHOWN
if ((!follow_symlinks) && (dir_fd == DEFAULT_DIR_FD))
result = lchown(path->narrow, uid, gid);
else
#endif
#ifdef HAVE_FCHOWNAT
if ((dir_fd != DEFAULT_DIR_FD) || (!follow_symlinks))
result = fchownat(dir_fd, path->narrow, uid, gid,
follow_symlinks ? 0 : AT_SYMLINK_NOFOLLOW);
else
#endif
result = chown(path->narrow, uid, gid);
Py_END_ALLOW_THREADS
if (result)
return path_error(path);
Py_RETURN_NONE;
}
#endif /* HAVE_CHOWN */
#ifdef HAVE_FCHOWN
/*[clinic input]
os.fchown
fd: int
uid: uid_t
gid: gid_t
Change the owner and group id of the file specified by file descriptor.
Equivalent to os.chown(fd, uid, gid).
[clinic start generated code]*/
static PyObject *
os_fchown_impl(PyObject *module, int fd, uid_t uid, gid_t gid)
/*[clinic end generated code: output=97d21cbd5a4350a6 input=3af544ba1b13a0d7]*/
{
int res;
int async_err = 0;
do {
Py_BEGIN_ALLOW_THREADS
res = fchown(fd, uid, gid);
Py_END_ALLOW_THREADS
} while (res != 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
if (res != 0)
return (!async_err) ? posix_error() : NULL;
Py_RETURN_NONE;
}
#endif /* HAVE_FCHOWN */
#ifdef HAVE_LCHOWN
/*[clinic input]
os.lchown
path : path_t
uid: uid_t
gid: gid_t
Change the owner and group id of path to the numeric uid and gid.
This function will not follow symbolic links.
Equivalent to os.chown(path, uid, gid, follow_symlinks=False).
[clinic start generated code]*/
static PyObject *
os_lchown_impl(PyObject *module, path_t *path, uid_t uid, gid_t gid)
/*[clinic end generated code: output=25eaf6af412fdf2f input=b1c6014d563a7161]*/
{
int res;
Py_BEGIN_ALLOW_THREADS
res = lchown(path->narrow, uid, gid);
Py_END_ALLOW_THREADS
if (res < 0) {
return path_error(path);
}
Py_RETURN_NONE;
}
#endif /* HAVE_LCHOWN */
static PyObject *
posix_getcwd(int use_bytes)
{
char *buf, *tmpbuf;
char *cwd;
const size_t chunk = 1024;
size_t buflen = 0;
PyObject *obj;
#ifdef MS_WINDOWS
if (!use_bytes) {
wchar_t wbuf[MAXPATHLEN];
wchar_t *wbuf2 = wbuf;
PyObject *resobj;
DWORD len;
Py_BEGIN_ALLOW_THREADS
len = GetCurrentDirectoryW(Py_ARRAY_LENGTH(wbuf), wbuf);
/* If the buffer is large enough, len does not include the
terminating \0. If the buffer is too small, len includes
the space needed for the terminator. */
if (len >= Py_ARRAY_LENGTH(wbuf)) {
wbuf2 = PyMem_RawMalloc(len * sizeof(wchar_t));
if (wbuf2)
len = GetCurrentDirectoryW(len, wbuf2);
}
Py_END_ALLOW_THREADS
if (!wbuf2) {
PyErr_NoMemory();
return NULL;
}
if (!len) {
if (wbuf2 != wbuf)
PyMem_RawFree(wbuf2);
return PyErr_SetFromWindowsErr(0);
}
resobj = PyUnicode_FromWideChar(wbuf2, len);
if (wbuf2 != wbuf)
PyMem_RawFree(wbuf2);
return resobj;
}
if (win32_warn_bytes_api())
return NULL;
#endif
buf = cwd = NULL;
Py_BEGIN_ALLOW_THREADS
do {
buflen += chunk;
#ifdef MS_WINDOWS
if (buflen > INT_MAX) {
PyErr_NoMemory();
break;
}
#endif
tmpbuf = PyMem_RawRealloc(buf, buflen);
if (tmpbuf == NULL)
break;
buf = tmpbuf;
#ifdef MS_WINDOWS
cwd = getcwd(buf, (int)buflen);
#else
cwd = getcwd(buf, buflen);
#endif
} while (cwd == NULL && errno == ERANGE);
Py_END_ALLOW_THREADS
if (cwd == NULL) {
PyMem_RawFree(buf);
return posix_error();
}
if (use_bytes)
obj = PyBytes_FromStringAndSize(buf, strlen(buf));
else
obj = PyUnicode_DecodeFSDefault(buf);
PyMem_RawFree(buf);
return obj;
}
/*[clinic input]
os.getcwd
Return a unicode string representing the current working directory.
[clinic start generated code]*/
static PyObject *
os_getcwd_impl(PyObject *module)
/*[clinic end generated code: output=21badfae2ea99ddc input=f069211bb70e3d39]*/
{
return posix_getcwd(0);
}
/*[clinic input]
os.getcwdb
Return a bytes string representing the current working directory.
[clinic start generated code]*/
static PyObject *
os_getcwdb_impl(PyObject *module)
/*[clinic end generated code: output=3dd47909480e4824 input=f6f6a378dad3d9cb]*/
{
return posix_getcwd(1);
}
#if ((!defined(HAVE_LINK)) && defined(MS_WINDOWS))
#define HAVE_LINK 1
#endif
#ifdef HAVE_LINK
/*[clinic input]
os.link
src : path_t
dst : path_t
*
src_dir_fd : dir_fd = None
dst_dir_fd : dir_fd = None
follow_symlinks: bool = True
Create a hard link to a file.
If either src_dir_fd or dst_dir_fd is not None, it should be a file
descriptor open to a directory, and the respective path string (src or dst)
should be relative; the path will then be relative to that directory.
If follow_symlinks is False, and the last element of src is a symbolic
link, link will create a link to the symbolic link itself instead of the
file the link points to.
src_dir_fd, dst_dir_fd, and follow_symlinks may not be implemented on your
platform. If they are unavailable, using them will raise a
NotImplementedError.
[clinic start generated code]*/
static PyObject *
os_link_impl(PyObject *module, path_t *src, path_t *dst, int src_dir_fd,
int dst_dir_fd, int follow_symlinks)
/*[clinic end generated code: output=7f00f6007fd5269a input=b0095ebbcbaa7e04]*/
{
#ifdef MS_WINDOWS
BOOL result = FALSE;
#else
int result;
#endif
#ifndef HAVE_LINKAT
if ((src_dir_fd != DEFAULT_DIR_FD) || (dst_dir_fd != DEFAULT_DIR_FD)) {
argument_unavailable_error("link", "src_dir_fd and dst_dir_fd");
return NULL;
}
#endif
#ifndef MS_WINDOWS
if ((src->narrow && dst->wide) || (src->wide && dst->narrow)) {
PyErr_SetString(PyExc_NotImplementedError,
"link: src and dst must be the same type");
return NULL;
}
#endif
#ifdef MS_WINDOWS
Py_BEGIN_ALLOW_THREADS
result = CreateHardLinkW(dst->wide, src->wide, NULL);
Py_END_ALLOW_THREADS
if (!result)
return path_error2(src, dst);
#else
Py_BEGIN_ALLOW_THREADS
#ifdef HAVE_LINKAT
if ((src_dir_fd != DEFAULT_DIR_FD) ||
(dst_dir_fd != DEFAULT_DIR_FD) ||
(!follow_symlinks))
result = linkat(src_dir_fd, src->narrow,
dst_dir_fd, dst->narrow,
follow_symlinks ? AT_SYMLINK_FOLLOW : 0);
else
#endif /* HAVE_LINKAT */
result = link(src->narrow, dst->narrow);
Py_END_ALLOW_THREADS
if (result)
return path_error2(src, dst);
#endif /* MS_WINDOWS */
Py_RETURN_NONE;
}
#endif
#if defined(MS_WINDOWS) && !defined(HAVE_OPENDIR)
static PyObject *
_listdir_windows_no_opendir(path_t *path, PyObject *list)
{
PyObject *v;
HANDLE hFindFile = INVALID_HANDLE_VALUE;
BOOL result;
wchar_t namebuf[MAX_PATH+4]; /* Overallocate for "\*.*" */
/* only claim to have space for MAX_PATH */
Py_ssize_t len = Py_ARRAY_LENGTH(namebuf)-4;
wchar_t *wnamebuf = NULL;
WIN32_FIND_DATAW wFileData;
const wchar_t *po_wchars;
if (!path->wide) { /* Default arg: "." */
po_wchars = L".";
len = 1;
} else {
po_wchars = path->wide;
len = wcslen(path->wide);
}
/* The +5 is so we can append "\\*.*\0" */
wnamebuf = PyMem_New(wchar_t, len + 5);
if (!wnamebuf) {
PyErr_NoMemory();
goto exit;
}
wcscpy(wnamebuf, po_wchars);
if (len > 0) {
wchar_t wch = wnamebuf[len-1];
if (wch != SEP && wch != ALTSEP && wch != L':')
wnamebuf[len++] = SEP;
wcscpy(wnamebuf + len, L"*.*");
}
if ((list = PyList_New(0)) == NULL) {
goto exit;
}
Py_BEGIN_ALLOW_THREADS
hFindFile = FindFirstFileW(wnamebuf, &wFileData);
Py_END_ALLOW_THREADS
if (hFindFile == INVALID_HANDLE_VALUE) {
int error = GetLastError();
if (error == ERROR_FILE_NOT_FOUND)
goto exit;
Py_DECREF(list);
list = path_error(path);
goto exit;
}
do {
/* Skip over . and .. */
if (wcscmp(wFileData.cFileName, L".") != 0 &&
wcscmp(wFileData.cFileName, L"..") != 0) {
v = PyUnicode_FromWideChar(wFileData.cFileName,
wcslen(wFileData.cFileName));
if (path->narrow && v) {
Py_SETREF(v, PyUnicode_EncodeFSDefault(v));
}
if (v == NULL) {
Py_DECREF(list);
list = NULL;
break;
}
if (PyList_Append(list, v) != 0) {
Py_DECREF(v);
Py_DECREF(list);
list = NULL;
break;
}
Py_DECREF(v);
}
Py_BEGIN_ALLOW_THREADS
result = FindNextFileW(hFindFile, &wFileData);
Py_END_ALLOW_THREADS
/* FindNextFile sets error to ERROR_NO_MORE_FILES if
it got to the end of the directory. */
if (!result && GetLastError() != ERROR_NO_MORE_FILES) {
Py_DECREF(list);
list = path_error(path);
goto exit;
}
} while (result == TRUE);
exit:
if (hFindFile != INVALID_HANDLE_VALUE) {
if (FindClose(hFindFile) == FALSE) {
if (list != NULL) {
Py_DECREF(list);
list = path_error(path);
}
}
}
PyMem_Free(wnamebuf);
return list;
} /* end of _listdir_windows_no_opendir */
#else /* thus POSIX, ie: not (MS_WINDOWS and not HAVE_OPENDIR) */
static PyObject *
_posix_listdir(path_t *path, PyObject *list)
{
PyObject *v;
DIR *dirp = NULL;
struct dirent *ep;
int return_str; /* if false, return bytes */
#ifdef HAVE_FDOPENDIR
int fd = -1;
#endif
errno = 0;
#ifdef HAVE_FDOPENDIR
if (path->fd != -1) {
/* closedir() closes the FD, so we duplicate it */
fd = _Py_dup(path->fd);
if (fd == -1)
return NULL;
return_str = 1;
Py_BEGIN_ALLOW_THREADS
dirp = fdopendir(fd);
Py_END_ALLOW_THREADS
}
else
#endif
{
const char *name;
if (path->narrow) {
name = path->narrow;
/* only return bytes if they specified a bytes-like object */
return_str = !PyObject_CheckBuffer(path->object);
}
else {
name = ".";
return_str = 1;
}
Py_BEGIN_ALLOW_THREADS
dirp = opendir(name);
Py_END_ALLOW_THREADS
}
if (dirp == NULL) {
list = path_error(path);
#ifdef HAVE_FDOPENDIR
if (fd != -1) {
Py_BEGIN_ALLOW_THREADS
close(fd);
Py_END_ALLOW_THREADS
}
#endif
goto exit;
}
if ((list = PyList_New(0)) == NULL) {
goto exit;
}
for (;;) {
errno = 0;
Py_BEGIN_ALLOW_THREADS
ep = readdir(dirp);
Py_END_ALLOW_THREADS
if (ep == NULL) {
if (errno == 0) {
break;
} else {
Py_DECREF(list);
list = path_error(path);
goto exit;
}
}
if (ep->d_name[0] == '.' &&
(NAMLEN(ep) == 1 ||
(ep->d_name[1] == '.' && NAMLEN(ep) == 2)))
continue;
if (return_str)
v = PyUnicode_DecodeFSDefaultAndSize(ep->d_name, NAMLEN(ep));
else
v = PyBytes_FromStringAndSize(ep->d_name, NAMLEN(ep));
if (v == NULL) {
Py_CLEAR(list);
break;
}
if (PyList_Append(list, v) != 0) {
Py_DECREF(v);
Py_CLEAR(list);
break;
}
Py_DECREF(v);
}
exit:
if (dirp != NULL) {
Py_BEGIN_ALLOW_THREADS
#if HAVE_FDOPENDIR
if (fd > -1)
rewinddir(dirp);
#endif
closedir(dirp);
Py_END_ALLOW_THREADS
}
return list;
} /* end of _posix_listdir */
#endif /* which OS */
/*[clinic input]
os.listdir
path : path_t(nullable=True, allow_fd='PATH_HAVE_FDOPENDIR') = None
Return a list containing the names of the files in the directory.
path can be specified as either str, bytes, or a path-like object. If path is bytes,
the filenames returned will also be bytes; in all other circumstances
the filenames returned will be str.
If path is None, uses the path='.'.
On some platforms, path may also be specified as an open file descriptor;\
the file descriptor must refer to a directory.
If this functionality is unavailable, using it raises NotImplementedError.
The list is in arbitrary order. It does not include the special
entries '.' and '..' even if they are present in the directory.
[clinic start generated code]*/
static PyObject *
os_listdir_impl(PyObject *module, path_t *path)
/*[clinic end generated code: output=293045673fcd1a75 input=e3f58030f538295d]*/
{
#if defined(MS_WINDOWS) && !defined(HAVE_OPENDIR)
return _listdir_windows_no_opendir(path, NULL);
#else
return _posix_listdir(path, NULL);
#endif
}
/*[clinic input]
os._getfinalpathname
path: unicode
/
A helper function for samepath on windows.
[clinic start generated code]*/
static PyObject *
os__getfinalpathname_impl(PyObject *module, PyObject *path)
/*[clinic end generated code: output=9bd78d0e52782e75 input=71d5e89334891bf4]*/
{
char *final8;
int64_t hFile;
size_t final8z;
PyObject *path_utf8;
char16_t *path_utf16;
char16_t buf[PATH_MAX], *target_path = buf;
int buf_size = Py_ARRAY_LENGTH(buf);
int result_length;
PyObject *result;
if (!(path_utf8 = PyUnicode_AsUTF8String(path))) return 0;
path_utf16 = gc(utf8to16(PyBytes_AS_STRING(path_utf8), PyBytes_GET_SIZE(path_utf8), 0));
Py_DECREF(path_utf8);
if (!path_utf16) return PyErr_NoMemory();
Py_BEGIN_ALLOW_THREADS
hFile = CreateFile(
path_utf16,
0, /* desired access */
0, /* share mode */
NULL, /* security attributes */
kNtOpenExisting,
/* FILE_FLAG_BACKUP_SEMANTICS is required to open a directory */
kNtFileFlagBackupSemantics,
0);
Py_END_ALLOW_THREADS
if(hFile == kNtInvalidHandleValue)
return win32_error_object("CreateFile", path);
/* We have a good handle to the target, use it to determine the
target path name. */
while (1) {
Py_BEGIN_ALLOW_THREADS
result_length = GetFinalPathNameByHandle(hFile, target_path,
buf_size, kNtVolumeNameDos);
Py_END_ALLOW_THREADS
if (!result_length) {
result = win32_error_object("GetFinalPathNameByHandle", path);
goto cleanup;
}
if (result_length < buf_size) {
break;
}
char16_t *tmp;
tmp = PyMem_Realloc(target_path != buf ? target_path : NULL,
result_length * sizeof(*tmp));
if (!tmp) {
result = PyErr_NoMemory();
goto cleanup;
}
buf_size = result_length;
target_path = tmp;
}
final8 = gc(utf16to8(target_path, result_length, &final8z));
result = PyUnicode_FromStringAndSize(final8, final8z);
cleanup:
if (target_path != buf) {
PyMem_Free(target_path);
}
CloseHandle(hFile);
return result;
}
#ifdef MS_WINDOWS
/* A helper function for abspath on win32 */
/*[clinic input]
os._getfullpathname
path: path_t
/
[clinic start generated code]*/
static PyObject *
os__getfullpathname_impl(PyObject *module, path_t *path)
/*[clinic end generated code: output=bb8679d56845bc9b input=332ed537c29d0a3e]*/
{
wchar_t woutbuf[MAX_PATH], *woutbufp = woutbuf;
wchar_t *wtemp;
DWORD result;
PyObject *v;
result = GetFullPathNameW(path->wide,
Py_ARRAY_LENGTH(woutbuf),
woutbuf, &wtemp);
if (result > Py_ARRAY_LENGTH(woutbuf)) {
woutbufp = PyMem_New(wchar_t, result);
if (!woutbufp)
return PyErr_NoMemory();
result = GetFullPathNameW(path->wide, result, woutbufp, &wtemp);
}
if (result) {
v = PyUnicode_FromWideChar(woutbufp, wcslen(woutbufp));
if (path->narrow)
Py_SETREF(v, PyUnicode_EncodeFSDefault(v));
} else
v = win32_error_object("GetFullPathNameW", path->object);
if (woutbufp != woutbuf)
PyMem_Free(woutbufp);
return v;
}
/*[clinic input]
os._isdir
path: path_t
/
Return true if the pathname refers to an existing directory.
[clinic start generated code]*/
static PyObject *
os__isdir_impl(PyObject *module, path_t *path)
/*[clinic end generated code: output=75f56f32720836cb input=5e0800149c0ad95f]*/
{
DWORD attributes;
Py_BEGIN_ALLOW_THREADS
attributes = GetFileAttributesW(path->wide);
Py_END_ALLOW_THREADS
if (attributes == INVALID_FILE_ATTRIBUTES)
Py_RETURN_FALSE;
if (attributes & FILE_ATTRIBUTE_DIRECTORY)
Py_RETURN_TRUE;
else
Py_RETURN_FALSE;
}
#endif /* MS_WINDOWS */
/*[clinic input]
os._getvolumepathname
path: unicode
A helper function for ismount on Win32.
[clinic start generated code]*/
static PyObject *
os__getvolumepathname_impl(PyObject *module, PyObject *path)
/*[clinic end generated code: output=cbdcbd1059ceef4c input=7eacadc40acbda6b]*/
{
PyObject *result;
PyObject *path_utf8;
char16_t *path_utf16;
char16_t *mountpath;
char *mountpath8;
size_t buflen;
bool32 ret;
if (!(path_utf8 = PyUnicode_AsUTF8String(path))) return 0;
path_utf16 = gc(utf8to16(PyBytes_AS_STRING(path_utf8), PyBytes_GET_SIZE(path_utf8), &buflen));
Py_DECREF(path_utf8);
if (!path_utf16) return PyErr_NoMemory();
buflen += 1;
/* Volume path should be shorter than entire path */
buflen = Py_MAX(buflen, PATH_MAX);
if (buflen > DWORD_MAX) {
PyErr_SetString(PyExc_OverflowError, "path too long");
return NULL;
}
if (!(mountpath = PyMem_New(char16_t, buflen)))
return PyErr_NoMemory();
Py_BEGIN_ALLOW_THREADS
ret = GetVolumePathName(path_utf16, mountpath,
Py_SAFE_DOWNCAST(buflen, size_t, uint32_t));
Py_END_ALLOW_THREADS
if (ret) {
mountpath8 = gc(utf16to8(mountpath, -1, &buflen));
result = PyUnicode_FromStringAndSize(mountpath8, buflen);
} else {
result = win32_error_object("_getvolumepathname", path);
}
PyMem_Free(mountpath);
return result;
}
/* static PyObject * */
/* os__getvolumepathname_impl(PyObject *module, PyObject *path) */
/* /\*[clinic end generated code: output=cbdcbd1059ceef4c input=7eacadc40acbda6b]*\/ */
/* { */
/* PyObject *result; */
/* const utf8_t *path_utf8; */
/* const wchar_t *path_wchar; */
/* char16_t *mountpath=NULL; */
/* size_t buflen; */
/* bool32 ret; */
/* path_wchar = PyUnicode_AsUTF8String(path, &buflen); */
/* if (path_wchar == NULL) */
/* return NULL; */
/* buflen += 1; */
/* /\* Volume path should be shorter than entire path *\/ */
/* buflen = Py_MAX(buflen, MAX_PATH); */
/* if (buflen > DWORD_MAX) { */
/* PyErr_SetString(PyExc_OverflowError, "path too long"); */
/* return NULL; */
/* } */
/* mountpath = PyMem_New(char16_t, buflen); */
/* if (mountpath == NULL) */
/* return PyErr_NoMemory(); */
/* Py_BEGIN_ALLOW_THREADS */
/* ret = GetVolumePathNameW(path_wchar, mountpath, */
/* Py_SAFE_DOWNCAST(buflen, size_t, uint32_t)); */
/* Py_END_ALLOW_THREADS */
/* if (!ret) { */
/* result = win32_error_object("_getvolumepathname", path); */
/* goto exit; */
/* } */
/* result = PyUnicode_FromWideChar(mountpath, wcslen(mountpath)); */
/* exit: */
/* PyMem_Free(mountpath); */
/* return result; */
/* } */
/*[clinic input]
os.mkdir
path : path_t
mode: int = 0o777
*
dir_fd : dir_fd(requires='mkdirat') = None
# "mkdir(path, mode=0o777, *, dir_fd=None)\n\n\
Create a directory.
If dir_fd is not None, it should be a file descriptor open to a directory,
and path should be relative; path will then be relative to that directory.
dir_fd may not be implemented on your platform.
If it is unavailable, using it will raise a NotImplementedError.
The mode argument is ignored on Windows.
[clinic start generated code]*/
static PyObject *
os_mkdir_impl(PyObject *module, path_t *path, int mode, int dir_fd)
/*[clinic end generated code: output=a70446903abe821f input=e965f68377e9b1ce]*/
{
int result;
#ifdef MS_WINDOWS
Py_BEGIN_ALLOW_THREADS
result = CreateDirectoryW(path->wide, NULL);
Py_END_ALLOW_THREADS
if (!result)
return path_error(path);
#else
Py_BEGIN_ALLOW_THREADS
#if HAVE_MKDIRAT
if (dir_fd != DEFAULT_DIR_FD)
result = mkdirat(dir_fd, path->narrow, mode);
else
#endif
#if ( defined(__WATCOMC__) || defined(PYCC_VACPP) ) && !defined(__QNX__)
result = mkdir(path->narrow);
#else
result = mkdir(path->narrow, mode);
#endif
Py_END_ALLOW_THREADS
if (result < 0)
return path_error(path);
#endif /* MS_WINDOWS */
Py_RETURN_NONE;
}
#ifdef HAVE_NICE
/*[clinic input]
os.nice
increment: int
/
Add increment to the priority of process and return the new priority.
[clinic start generated code]*/
static PyObject *
os_nice_impl(PyObject *module, int increment)
/*[clinic end generated code: output=9dad8a9da8109943 input=864be2d402a21da2]*/
{
int value;
/* There are two flavours of 'nice': one that returns the new
priority (as required by almost all standards out there) and the
Linux/FreeBSD/BSDI one, which returns '0' on success and advices
the use of getpriority() to get the new priority.
If we are of the nice family that returns the new priority, we
need to clear errno before the call, and check if errno is filled
before calling posix_error() on a returnvalue of -1, because the
-1 may be the actual new priority! */
errno = 0;
value = nice(increment);
#if defined(HAVE_BROKEN_NICE) && defined(HAVE_GETPRIORITY)
if (value == 0)
value = getpriority(PRIO_PROCESS, 0);
#endif
if (value == -1 && errno != 0)
/* either nice() or getpriority() returned an error */
return posix_error();
return PyLong_FromLong((long) value);
}
#endif /* HAVE_NICE */
#ifdef HAVE_GETPRIORITY
/*[clinic input]
os.getpriority
which: int
who: int
Return program scheduling priority.
[clinic start generated code]*/
static PyObject *
os_getpriority_impl(PyObject *module, int which, int who)
/*[clinic end generated code: output=c41b7b63c7420228 input=9be615d40e2544ef]*/
{
int retval;
errno = 0;
retval = getpriority(which, who);
if (errno != 0)
return posix_error();
return PyLong_FromLong((long)retval);
}
#endif /* HAVE_GETPRIORITY */
#ifdef HAVE_SETPRIORITY
/*[clinic input]
os.setpriority
which: int
who: int
priority: int
Set program scheduling priority.
[clinic start generated code]*/
static PyObject *
os_setpriority_impl(PyObject *module, int which, int who, int priority)
/*[clinic end generated code: output=3d910d95a7771eb2 input=710ccbf65b9dc513]*/
{
int retval;
retval = setpriority(which, who, priority);
if (retval == -1)
return posix_error();
Py_RETURN_NONE;
}
#endif /* HAVE_SETPRIORITY */
static PyObject *
internal_rename(path_t *src, path_t *dst, int src_dir_fd, int dst_dir_fd, int is_replace)
{
const char *function_name = is_replace ? "replace" : "rename";
int dir_fd_specified;
#ifdef MS_WINDOWS
BOOL result;
int flags = is_replace ? MOVEFILE_REPLACE_EXISTING : 0;
#else
int result;
#endif
dir_fd_specified = (src_dir_fd != DEFAULT_DIR_FD) ||
(dst_dir_fd != DEFAULT_DIR_FD);
#ifndef HAVE_RENAMEAT
if (dir_fd_specified) {
argument_unavailable_error(function_name, "src_dir_fd and dst_dir_fd");
return NULL;
}
#endif
#ifdef MS_WINDOWS
Py_BEGIN_ALLOW_THREADS
result = MoveFileExW(src->wide, dst->wide, flags);
Py_END_ALLOW_THREADS
if (!result)
return path_error2(src, dst);
#else
if ((src->narrow && dst->wide) || (src->wide && dst->narrow)) {
PyErr_Format(PyExc_ValueError,
"%s: src and dst must be the same type", function_name);
return NULL;
}
Py_BEGIN_ALLOW_THREADS
#ifdef HAVE_RENAMEAT
if (dir_fd_specified)
result = renameat(src_dir_fd, src->narrow, dst_dir_fd, dst->narrow);
else
#endif
result = rename(src->narrow, dst->narrow);
Py_END_ALLOW_THREADS
if (result)
return path_error2(src, dst);
#endif
Py_RETURN_NONE;
}
/*[clinic input]
os.rename
src : path_t
dst : path_t
*
src_dir_fd : dir_fd = None
dst_dir_fd : dir_fd = None
Rename a file or directory.
If either src_dir_fd or dst_dir_fd is not None, it should be a file
descriptor open to a directory, and the respective path string (src or dst)
should be relative; the path will then be relative to that directory.
src_dir_fd and dst_dir_fd, may not be implemented on your platform.
If they are unavailable, using them will raise a NotImplementedError.
[clinic start generated code]*/
static PyObject *
os_rename_impl(PyObject *module, path_t *src, path_t *dst, int src_dir_fd,
int dst_dir_fd)
/*[clinic end generated code: output=59e803072cf41230 input=faa61c847912c850]*/
{
return internal_rename(src, dst, src_dir_fd, dst_dir_fd, 0);
}
/*[clinic input]
os.replace = os.rename
Rename a file or directory, overwriting the destination.
If either src_dir_fd or dst_dir_fd is not None, it should be a file
descriptor open to a directory, and the respective path string (src or dst)
should be relative; the path will then be relative to that directory.
src_dir_fd and dst_dir_fd, may not be implemented on your platform.
If they are unavailable, using them will raise a NotImplementedError."
[clinic start generated code]*/
static PyObject *
os_replace_impl(PyObject *module, path_t *src, path_t *dst, int src_dir_fd,
int dst_dir_fd)
/*[clinic end generated code: output=1968c02e7857422b input=25515dfb107c8421]*/
{
return internal_rename(src, dst, src_dir_fd, dst_dir_fd, 1);
}
/*[clinic input]
os.rmdir
path: path_t
*
dir_fd: dir_fd(requires='unlinkat') = None
Remove a directory.
If dir_fd is not None, it should be a file descriptor open to a directory,
and path should be relative; path will then be relative to that directory.
dir_fd may not be implemented on your platform.
If it is unavailable, using it will raise a NotImplementedError.
[clinic start generated code]*/
static PyObject *
os_rmdir_impl(PyObject *module, path_t *path, int dir_fd)
/*[clinic end generated code: output=080eb54f506e8301 input=38c8b375ca34a7e2]*/
{
int result;
Py_BEGIN_ALLOW_THREADS
#ifdef MS_WINDOWS
/* Windows, success=1, UNIX, success=0 */
result = !RemoveDirectoryW(path->wide);
#else
#ifdef HAVE_UNLINKAT
if (dir_fd != DEFAULT_DIR_FD)
result = unlinkat(dir_fd, path->narrow, AT_REMOVEDIR);
else
#endif
result = rmdir(path->narrow);
#endif
Py_END_ALLOW_THREADS
if (result)
return path_error(path);
Py_RETURN_NONE;
}
#ifdef HAVE_SYSTEM
#ifdef MS_WINDOWS
/*[clinic input]
os.system -> long
command: Py_UNICODE
Execute the command in a subshell.
[clinic start generated code]*/
static long
os_system_impl(PyObject *module, Py_UNICODE *command)
/*[clinic end generated code: output=96c4dffee36dfb48 input=303f5ce97df606b0]*/
{
long result;
Py_BEGIN_ALLOW_THREADS
_Py_BEGIN_SUPPRESS_IPH
result = _wsystem(command);
_Py_END_SUPPRESS_IPH
Py_END_ALLOW_THREADS
return result;
}
#else /* MS_WINDOWS */
/*[clinic input]
os.system -> long
command: FSConverter
Execute the command in a subshell.
[clinic start generated code]*/
static long
os_system_impl(PyObject *module, PyObject *command)
/*[clinic end generated code: output=290fc437dd4f33a0 input=86a58554ba6094af]*/
{
long result;
const char *bytes = PyBytes_AsString(command);
Py_BEGIN_ALLOW_THREADS
result = system(bytes);
Py_END_ALLOW_THREADS
return result;
}
#endif
#endif /* HAVE_SYSTEM */
/*[clinic input]
os.umask
mask: int
/
Set the current numeric umask and return the previous umask.
[clinic start generated code]*/
static PyObject *
os_umask_impl(PyObject *module, int mask)
/*[clinic end generated code: output=a2e33ce3bc1a6e33 input=ab6bfd9b24d8a7e8]*/
{
int i = (int)umask(mask);
if (i < 0)
return posix_error();
return PyLong_FromLong((long)i);
}
/*[clinic input]
os.unlink
path: path_t
*
dir_fd: dir_fd(requires='unlinkat')=None
Remove a file (same as remove()).
If dir_fd is not None, it should be a file descriptor open to a directory,
and path should be relative; path will then be relative to that directory.
dir_fd may not be implemented on your platform.
If it is unavailable, using it will raise a NotImplementedError.
[clinic start generated code]*/
static PyObject *
os_unlink_impl(PyObject *module, path_t *path, int dir_fd)
/*[clinic end generated code: output=621797807b9963b1 input=d7bcde2b1b2a2552]*/
{
int result;
Py_BEGIN_ALLOW_THREADS
_Py_BEGIN_SUPPRESS_IPH
#ifdef MS_WINDOWS
/* Windows, success=1, UNIX, success=0 */
result = !Py_DeleteFileW(path->wide);
#else
#ifdef HAVE_UNLINKAT
if (dir_fd != DEFAULT_DIR_FD)
result = unlinkat(dir_fd, path->narrow, 0);
else
#endif /* HAVE_UNLINKAT */
result = unlink(path->narrow);
#endif
_Py_END_SUPPRESS_IPH
Py_END_ALLOW_THREADS
if (result)
return path_error(path);
Py_RETURN_NONE;
}
/*[clinic input]
os.remove = os.unlink
Remove a file (same as unlink()).
If dir_fd is not None, it should be a file descriptor open to a directory,
and path should be relative; path will then be relative to that directory.
dir_fd may not be implemented on your platform.
If it is unavailable, using it will raise a NotImplementedError.
[clinic start generated code]*/
static PyObject *
os_remove_impl(PyObject *module, path_t *path, int dir_fd)
/*[clinic end generated code: output=a8535b28f0068883 input=e05c5ab55cd30983]*/
{
return os_unlink_impl(module, path, dir_fd);
}
static PyStructSequence_Field uname_result_fields[] = {
{"sysname", PyDoc_STR("operating system name")},
{"nodename", PyDoc_STR("name of machine on network (implementation-defined)")},
{"release", PyDoc_STR("operating system release")},
{"version", PyDoc_STR("operating system version")},
{"machine", PyDoc_STR("hardware identifier")},
{NULL}
};
PyDoc_STRVAR(uname_result__doc__,
"uname_result: Result from os.uname().\n\n\
This object may be accessed either as a tuple of\n\
(sysname, nodename, release, version, machine),\n\
or via the attributes sysname, nodename, release, version, and machine.\n\
\n\
See os.uname for more information.");
static PyStructSequence_Desc uname_result_desc = {
"uname_result", /* name */
uname_result__doc__, /* doc */
uname_result_fields,
5
};
static PyTypeObject UnameResultType;
#ifdef HAVE_UNAME
/*[clinic input]
os.uname
Return an object identifying the current operating system.
The object behaves like a named tuple with the following fields:
(sysname, nodename, release, version, machine)
[clinic start generated code]*/
static PyObject *
os_uname_impl(PyObject *module)
/*[clinic end generated code: output=e6a49cf1a1508a19 input=e68bd246db3043ed]*/
{
struct utsname u;
int res;
PyObject *value;
Py_BEGIN_ALLOW_THREADS
if(!IsWindows()) res = uname(&u);
else {
strcpy(u.sysname, "Linux");
strcpy(u.machine, "x86_64");
strcpy(u.nodename, "");
strcpy(u.release, "");
strcpy(u.version, "");
res = 0;
}
Py_END_ALLOW_THREADS
if (res < 0)
return posix_error();
value = PyStructSequence_New(&UnameResultType);
if (value == NULL)
return NULL;
#define SET(i, field) \
{ \
PyObject *o = PyUnicode_DecodeFSDefault(field); \
if (!o) { \
Py_DECREF(value); \
return NULL; \
} \
PyStructSequence_SET_ITEM(value, i, o); \
} \
SET(0, u.sysname);
SET(1, u.nodename);
SET(2, u.release);
SET(3, u.version);
SET(4, u.machine);
#undef SET
return value;
}
#endif /* HAVE_UNAME */
typedef struct {
int now;
time_t atime_s;
long atime_ns;
time_t mtime_s;
long mtime_ns;
} utime_t;
/*
* these macros assume that "ut" is a pointer to a utime_t
* they also intentionally leak the declaration of a pointer named "time"
*/
#define UTIME_TO_TIMESPEC \
struct timespec ts[2]; \
struct timespec *time; \
if (ut->now) \
time = NULL; \
else { \
ts[0].tv_sec = ut->atime_s; \
ts[0].tv_nsec = ut->atime_ns; \
ts[1].tv_sec = ut->mtime_s; \
ts[1].tv_nsec = ut->mtime_ns; \
time = ts; \
} \
#define UTIME_TO_TIMEVAL \
struct timeval tv[2]; \
struct timeval *time; \
if (ut->now) \
time = NULL; \
else { \
tv[0].tv_sec = ut->atime_s; \
tv[0].tv_usec = ut->atime_ns / 1000; \
tv[1].tv_sec = ut->mtime_s; \
tv[1].tv_usec = ut->mtime_ns / 1000; \
time = tv; \
} \
#define UTIME_TO_UTIMBUF \
struct utimbuf u; \
struct utimbuf *time; \
if (ut->now) \
time = NULL; \
else { \
u.actime = ut->atime_s; \
u.modtime = ut->mtime_s; \
time = &u; \
}
#define UTIME_TO_TIME_T \
time_t timet[2]; \
time_t *time; \
if (ut->now) \
time = NULL; \
else { \
timet[0] = ut->atime_s; \
timet[1] = ut->mtime_s; \
time = timet; \
} \
#if defined(HAVE_FUTIMESAT) || defined(HAVE_UTIMENSAT)
static int
utime_dir_fd(utime_t *ut, int dir_fd, const char *path, int follow_symlinks)
{
#ifdef HAVE_UTIMENSAT
int flags = follow_symlinks ? 0 : AT_SYMLINK_NOFOLLOW;
UTIME_TO_TIMESPEC;
return utimensat(dir_fd, path, time, flags);
#elif defined(HAVE_FUTIMESAT)
UTIME_TO_TIMEVAL;
/*
* follow_symlinks will never be false here;
* we only allow !follow_symlinks and dir_fd together
* if we have utimensat()
*/
assert(follow_symlinks);
return futimesat(dir_fd, path, time);
#endif
}
#define FUTIMENSAT_DIR_FD_CONVERTER dir_fd_converter
#else
#define FUTIMENSAT_DIR_FD_CONVERTER dir_fd_unavailable
#endif
#if defined(HAVE_FUTIMES) || defined(HAVE_FUTIMENS)
static int
utime_fd(utime_t *ut, int fd)
{
#ifdef HAVE_FUTIMENS
UTIME_TO_TIMESPEC;
return futimens(fd, time);
#else
UTIME_TO_TIMEVAL;
return futimes(fd, time);
#endif
}
#define PATH_UTIME_HAVE_FD 1
#else
#define PATH_UTIME_HAVE_FD 0
#endif
#if defined(HAVE_UTIMENSAT) || defined(HAVE_LUTIMES)
# define UTIME_HAVE_NOFOLLOW_SYMLINKS
#endif
#ifdef UTIME_HAVE_NOFOLLOW_SYMLINKS
static int
utime_nofollow_symlinks(utime_t *ut, const char *path)
{
#ifdef HAVE_UTIMENSAT
UTIME_TO_TIMESPEC;
return utimensat(DEFAULT_DIR_FD, path, time, AT_SYMLINK_NOFOLLOW);
#else
UTIME_TO_TIMEVAL;
return lutimes(path, time);
#endif
}
#endif
#ifndef MS_WINDOWS
static int
utime_default(utime_t *ut, const char *path)
{
UTIME_TO_TIMESPEC;
return utimensat(DEFAULT_DIR_FD, path, time, 0);
}
#endif
static int
split_py_long_to_s_and_ns(PyObject *py_long, time_t *s, long *ns)
{
int result = 0;
PyObject *divmod;
divmod = PyNumber_Divmod(py_long, billion);
if (!divmod)
goto exit;
*s = _PyLong_AsTime_t(PyTuple_GET_ITEM(divmod, 0));
if ((*s == -1) && PyErr_Occurred())
goto exit;
*ns = PyLong_AsLong(PyTuple_GET_ITEM(divmod, 1));
if ((*ns == -1) && PyErr_Occurred())
goto exit;
result = 1;
exit:
Py_XDECREF(divmod);
return result;
}
/*[clinic input]
os.utime
path: path_t(allow_fd='PATH_UTIME_HAVE_FD')
times: object = NULL
*
ns: object = NULL
dir_fd: dir_fd(requires='futimensat') = None
follow_symlinks: bool=True
# "utime(path, times=None, *[, ns], dir_fd=None, follow_symlinks=True)\n\
Set the access and modified time of path.
path may always be specified as a string.
On some platforms, path may also be specified as an open file descriptor.
If this functionality is unavailable, using it raises an exception.
If times is not None, it must be a tuple (atime, mtime);
atime and mtime should be expressed as float seconds since the epoch.
If ns is specified, it must be a tuple (atime_ns, mtime_ns);
atime_ns and mtime_ns should be expressed as integer nanoseconds
since the epoch.
If times is None and ns is unspecified, utime uses the current time.
Specifying tuples for both times and ns is an error.
If dir_fd is not None, it should be a file descriptor open to a directory,
and path should be relative; path will then be relative to that directory.
If follow_symlinks is False, and the last element of the path is a symbolic
link, utime will modify the symbolic link itself instead of the file the
link points to.
It is an error to use dir_fd or follow_symlinks when specifying path
as an open file descriptor.
dir_fd and follow_symlinks may not be available on your platform.
If they are unavailable, using them will raise a NotImplementedError.
[clinic start generated code]*/
static PyObject *
os_utime_impl(PyObject *module, path_t *path, PyObject *times, PyObject *ns,
int dir_fd, int follow_symlinks)
/*[clinic end generated code: output=cfcac69d027b82cf input=081cdc54ca685385]*/
{
#ifdef MS_WINDOWS
HANDLE hFile;
FILETIME atime, mtime;
#else
int result;
#endif
utime_t utime;
bzero(&utime, sizeof(utime_t));
if (times && (times != Py_None) && ns) {
PyErr_SetString(PyExc_ValueError,
"utime: you may specify either 'times'"
" or 'ns' but not both");
return NULL;
}
if (times && (times != Py_None)) {
time_t a_sec, m_sec;
long a_nsec, m_nsec;
if (!PyTuple_CheckExact(times) || (PyTuple_Size(times) != 2)) {
PyErr_SetString(PyExc_TypeError,
"utime: 'times' must be either"
" a tuple of two ints or None");
return NULL;
}
utime.now = 0;
if (_PyTime_ObjectToTimespec(PyTuple_GET_ITEM(times, 0),
&a_sec, &a_nsec, _PyTime_ROUND_FLOOR) == -1 ||
_PyTime_ObjectToTimespec(PyTuple_GET_ITEM(times, 1),
&m_sec, &m_nsec, _PyTime_ROUND_FLOOR) == -1) {
return NULL;
}
utime.atime_s = a_sec;
utime.atime_ns = a_nsec;
utime.mtime_s = m_sec;
utime.mtime_ns = m_nsec;
}
else if (ns) {
if (!PyTuple_CheckExact(ns) || (PyTuple_Size(ns) != 2)) {
PyErr_SetString(PyExc_TypeError,
"utime: 'ns' must be a tuple of two ints");
return NULL;
}
utime.now = 0;
if (!split_py_long_to_s_and_ns(PyTuple_GET_ITEM(ns, 0),
&utime.atime_s, &utime.atime_ns) ||
!split_py_long_to_s_and_ns(PyTuple_GET_ITEM(ns, 1),
&utime.mtime_s, &utime.mtime_ns)) {
return NULL;
}
}
else {
/* times and ns are both None/unspecified. use "now". */
utime.now = 1;
}
#if !defined(UTIME_HAVE_NOFOLLOW_SYMLINKS)
if (follow_symlinks_specified("utime", follow_symlinks))
return NULL;
#endif
if (path_and_dir_fd_invalid("utime", path, dir_fd) ||
dir_fd_and_fd_invalid("utime", dir_fd, path->fd) ||
fd_and_follow_symlinks_invalid("utime", path->fd, follow_symlinks))
return NULL;
#if !defined(HAVE_UTIMENSAT)
if ((dir_fd != DEFAULT_DIR_FD) && (!follow_symlinks)) {
PyErr_SetString(PyExc_ValueError,
"utime: cannot use dir_fd and follow_symlinks "
"together on this platform");
return NULL;
}
#endif
#ifdef MS_WINDOWS
Py_BEGIN_ALLOW_THREADS
hFile = CreateFileW(path->wide, FILE_WRITE_ATTRIBUTES, 0,
NULL, OPEN_EXISTING,
FILE_FLAG_BACKUP_SEMANTICS, NULL);
Py_END_ALLOW_THREADS
if (hFile == INVALID_HANDLE_VALUE) {
path_error(path);
return NULL;
}
if (utime.now) {
GetSystemTimeAsFileTime(&mtime);
atime = mtime;
}
else {
_Py_time_t_to_FILE_TIME(utime.atime_s, utime.atime_ns, &atime);
_Py_time_t_to_FILE_TIME(utime.mtime_s, utime.mtime_ns, &mtime);
}
if (!SetFileTime(hFile, NULL, &atime, &mtime)) {
/* Avoid putting the file name into the error here,
as that may confuse the user into believing that
something is wrong with the file, when it also
could be the time stamp that gives a problem. */
PyErr_SetFromWindowsErr(0);
CloseHandle(hFile);
return NULL;
}
CloseHandle(hFile);
#else /* MS_WINDOWS */
Py_BEGIN_ALLOW_THREADS
#ifdef UTIME_HAVE_NOFOLLOW_SYMLINKS
if ((!follow_symlinks) && (dir_fd == DEFAULT_DIR_FD))
result = utime_nofollow_symlinks(&utime, path->narrow);
else
#endif
#if defined(HAVE_FUTIMESAT) || defined(HAVE_UTIMENSAT)
if ((dir_fd != DEFAULT_DIR_FD) || (!follow_symlinks))
result = utime_dir_fd(&utime, dir_fd, path->narrow, follow_symlinks);
else
#endif
#if defined(HAVE_FUTIMES) || defined(HAVE_FUTIMENS)
if (path->fd != -1)
result = utime_fd(&utime, path->fd);
else
#endif
result = utime_default(&utime, path->narrow);
Py_END_ALLOW_THREADS
if (result < 0) {
/* see previous comment about not putting filename in error here */
posix_error();
return NULL;
}
#endif /* MS_WINDOWS */
Py_RETURN_NONE;
}
/* Process operations */
/*[clinic input]
os._exit
status: int
Exit to the system with specified status, without normal exit processing.
[clinic start generated code]*/
static PyObject *
os__exit_impl(PyObject *module, int status)
/*[clinic end generated code: output=116e52d9c2260d54 input=5e6d57556b0c4a62]*/
{
_exit(status);
return NULL; /* Make gcc -Wall happy */
}
#if defined(HAVE_WEXECV) || defined(HAVE_WSPAWNV)
#define EXECV_CHAR wchar_t
#else
#define EXECV_CHAR char
#endif
#if defined(HAVE_EXECV) || defined(HAVE_SPAWNV)
static void
free_string_array(EXECV_CHAR **array, Py_ssize_t count)
{
Py_ssize_t i;
for (i = 0; i < count; i++)
PyMem_Free(array[i]);
PyMem_DEL(array);
}
static int
fsconvert_strdup(PyObject *o, EXECV_CHAR **out)
{
Py_ssize_t size;
PyObject *ub;
int result = 0;
#if defined(HAVE_WEXECV) || defined(HAVE_WSPAWNV)
if (!PyUnicode_FSDecoder(o, &ub))
return 0;
*out = PyUnicode_AsWideCharString(ub, &size);
if (*out)
result = 1;
#else
if (!PyUnicode_FSConverter(o, &ub))
return 0;
size = PyBytes_GET_SIZE(ub);
*out = PyMem_Malloc(size + 1);
if (*out) {
memcpy(*out, PyBytes_AS_STRING(ub), size + 1);
result = 1;
} else
PyErr_NoMemory();
#endif
Py_DECREF(ub);
return result;
}
#endif
#if defined(HAVE_EXECV) || defined (HAVE_FEXECVE)
static EXECV_CHAR**
parse_envlist(PyObject* env, Py_ssize_t *envc_ptr)
{
Py_ssize_t i, pos, envc;
PyObject *keys=NULL, *vals=NULL;
PyObject *key, *val, *key2, *val2, *keyval;
EXECV_CHAR **envlist;
i = PyMapping_Size(env);
if (i < 0)
return NULL;
envlist = PyMem_NEW(EXECV_CHAR *, i + 1);
if (envlist == NULL) {
PyErr_NoMemory();
return NULL;
}
envc = 0;
keys = PyMapping_Keys(env);
if (!keys)
goto error;
vals = PyMapping_Values(env);
if (!vals)
goto error;
if (!PyList_Check(keys) || !PyList_Check(vals)) {
PyErr_Format(PyExc_TypeError,
"env.keys() or env.values() is not a list");
goto error;
}
for (pos = 0; pos < i; pos++) {
key = PyList_GetItem(keys, pos);
val = PyList_GetItem(vals, pos);
if (!key || !val)
goto error;
#if defined(HAVE_WEXECV) || defined(HAVE_WSPAWNV)
if (!PyUnicode_FSDecoder(key, &key2))
goto error;
if (!PyUnicode_FSDecoder(val, &val2)) {
Py_DECREF(key2);
goto error;
}
/* Search from index 1 because on Windows starting '=' is allowed for
defining hidden environment variables. */
if (PyUnicode_GET_LENGTH(key2) == 0 ||
PyUnicode_FindChar(key2, '=', 1, PyUnicode_GET_LENGTH(key2), 1) != -1)
{
PyErr_SetString(PyExc_ValueError, "illegal environment variable name");
Py_DECREF(key2);
Py_DECREF(val2);
goto error;
}
keyval = PyUnicode_FromFormat("%U=%U", key2, val2);
#else
if (!PyUnicode_FSConverter(key, &key2))
goto error;
if (!PyUnicode_FSConverter(val, &val2)) {
Py_DECREF(key2);
goto error;
}
if (PyBytes_GET_SIZE(key2) == 0 ||
strchr(PyBytes_AS_STRING(key2) + 1, '=') != NULL)
{
PyErr_SetString(PyExc_ValueError, "illegal environment variable name");
Py_DECREF(key2);
Py_DECREF(val2);
goto error;
}
keyval = PyBytes_FromFormat("%s=%s", PyBytes_AS_STRING(key2),
PyBytes_AS_STRING(val2));
#endif
Py_DECREF(key2);
Py_DECREF(val2);
if (!keyval)
goto error;
if (!fsconvert_strdup(keyval, &envlist[envc++])) {
Py_DECREF(keyval);
goto error;
}
Py_DECREF(keyval);
}
Py_DECREF(vals);
Py_DECREF(keys);
envlist[envc] = 0;
*envc_ptr = envc;
return envlist;
error:
Py_XDECREF(keys);
Py_XDECREF(vals);
free_string_array(envlist, envc);
return NULL;
}
static EXECV_CHAR**
parse_arglist(PyObject* argv, Py_ssize_t *argc)
{
int i;
EXECV_CHAR **argvlist = PyMem_NEW(EXECV_CHAR *, *argc+1);
if (argvlist == NULL) {
PyErr_NoMemory();
return NULL;
}
for (i = 0; i < *argc; i++) {
PyObject* item = PySequence_ITEM(argv, i);
if (item == NULL)
goto fail;
if (!fsconvert_strdup(item, &argvlist[i])) {
Py_DECREF(item);
goto fail;
}
Py_DECREF(item);
}
argvlist[*argc] = NULL;
return argvlist;
fail:
*argc = i;
free_string_array(argvlist, *argc);
return NULL;
}
#endif
#ifdef HAVE_EXECV
/*[clinic input]
os.execv
path: path_t
Path of executable file.
argv: object
Tuple or list of strings.
/
Execute an executable path with arguments, replacing current process.
[clinic start generated code]*/
static PyObject *
os_execv_impl(PyObject *module, path_t *path, PyObject *argv)
/*[clinic end generated code: output=3b52fec34cd0dafd input=9bac31efae07dac7]*/
{
EXECV_CHAR **argvlist;
Py_ssize_t argc;
/* execv has two arguments: (path, argv), where
argv is a list or tuple of strings. */
if (!PyList_Check(argv) && !PyTuple_Check(argv)) {
PyErr_SetString(PyExc_TypeError,
"execv() arg 2 must be a tuple or list");
return NULL;
}
argc = PySequence_Size(argv);
if (argc < 1) {
PyErr_SetString(PyExc_ValueError, "execv() arg 2 must not be empty");
return NULL;
}
argvlist = parse_arglist(argv, &argc);
if (argvlist == NULL) {
return NULL;
}
if (!argvlist[0][0]) {
PyErr_SetString(PyExc_ValueError,
"execv() arg 2 first element cannot be empty");
free_string_array(argvlist, argc);
return NULL;
}
_Py_BEGIN_SUPPRESS_IPH
#ifdef HAVE_WEXECV
_wexecv(path->wide, argvlist);
#else
execv(path->narrow, argvlist);
#endif
_Py_END_SUPPRESS_IPH
/* If we get here it's definitely an error */
free_string_array(argvlist, argc);
return posix_error();
}
/*[clinic input]
os.execve
path: path_t(allow_fd='PATH_HAVE_FEXECVE')
Path of executable file.
argv: object
Tuple or list of strings.
env: object
Dictionary of strings mapping to strings.
Execute an executable path with arguments, replacing current process.
[clinic start generated code]*/
static PyObject *
os_execve_impl(PyObject *module, path_t *path, PyObject *argv, PyObject *env)
/*[clinic end generated code: output=ff9fa8e4da8bde58 input=626804fa092606d9]*/
{
EXECV_CHAR **argvlist = NULL;
EXECV_CHAR **envlist;
Py_ssize_t argc, envc;
/* execve has three arguments: (path, argv, env), where
argv is a list or tuple of strings and env is a dictionary
like posix.environ. */
if (!PyList_Check(argv) && !PyTuple_Check(argv)) {
PyErr_SetString(PyExc_TypeError,
"execve: argv must be a tuple or list");
goto fail;
}
argc = PySequence_Size(argv);
if (argc < 1) {
PyErr_SetString(PyExc_ValueError, "execve: argv must not be empty");
return NULL;
}
if (!PyMapping_Check(env)) {
PyErr_SetString(PyExc_TypeError,
"execve: environment must be a mapping object");
goto fail;
}
argvlist = parse_arglist(argv, &argc);
if (argvlist == NULL) {
goto fail;
}
if (!argvlist[0][0]) {
PyErr_SetString(PyExc_ValueError,
"execve: argv first element cannot be empty");
goto fail;
}
envlist = parse_envlist(env, &envc);
if (envlist == NULL)
goto fail;
_Py_BEGIN_SUPPRESS_IPH
#ifdef HAVE_FEXECVE
if (path->fd > -1)
fexecve(path->fd, argvlist, envlist);
else
#endif
#ifdef HAVE_WEXECV
_wexecve(path->wide, argvlist, envlist);
#else
execve(path->narrow, argvlist, envlist);
#endif
_Py_END_SUPPRESS_IPH
/* If we get here it's definitely an error */
posix_path_error(path);
free_string_array(envlist, envc);
fail:
if (argvlist)
free_string_array(argvlist, argc);
return NULL;
}
#endif /* HAVE_EXECV */
#if defined(HAVE_SPAWNV) || defined(HAVE_WSPAWNV)
/*[clinic input]
os.spawnv
mode: int
Mode of process creation.
path: path_t
Path of executable file.
argv: object
Tuple or list of strings.
/
Execute the program specified by path in a new process.
[clinic start generated code]*/
static PyObject *
os_spawnv_impl(PyObject *module, int mode, path_t *path, PyObject *argv)
/*[clinic end generated code: output=71cd037a9d96b816 input=43224242303291be]*/
{
EXECV_CHAR **argvlist;
int i;
Py_ssize_t argc;
intptr_t spawnval;
PyObject *(*getitem)(PyObject *, Py_ssize_t);
/* spawnv has three arguments: (mode, path, argv), where
argv is a list or tuple of strings. */
if (PyList_Check(argv)) {
argc = PyList_Size(argv);
getitem = PyList_GetItem;
}
else if (PyTuple_Check(argv)) {
argc = PyTuple_Size(argv);
getitem = PyTuple_GetItem;
}
else {
PyErr_SetString(PyExc_TypeError,
"spawnv() arg 2 must be a tuple or list");
return NULL;
}
if (argc == 0) {
PyErr_SetString(PyExc_ValueError,
"spawnv() arg 2 cannot be empty");
return NULL;
}
argvlist = PyMem_NEW(EXECV_CHAR *, argc+1);
if (argvlist == NULL) {
return PyErr_NoMemory();
}
for (i = 0; i < argc; i++) {
if (!fsconvert_strdup((*getitem)(argv, i),
&argvlist[i])) {
free_string_array(argvlist, i);
PyErr_SetString(
PyExc_TypeError,
"spawnv() arg 2 must contain only strings");
return NULL;
}
if (i == 0 && !argvlist[0][0]) {
free_string_array(argvlist, i + 1);
PyErr_SetString(
PyExc_ValueError,
"spawnv() arg 2 first element cannot be empty");
return NULL;
}
}
argvlist[argc] = NULL;
if (mode == _OLD_P_OVERLAY)
mode = _P_OVERLAY;
Py_BEGIN_ALLOW_THREADS
_Py_BEGIN_SUPPRESS_IPH
#ifdef HAVE_WSPAWNV
spawnval = _wspawnv(mode, path->wide, argvlist);
#else
spawnval = _spawnv(mode, path->narrow, argvlist);
#endif
_Py_END_SUPPRESS_IPH
Py_END_ALLOW_THREADS
free_string_array(argvlist, argc);
if (spawnval == -1)
return posix_error();
else
return Py_BuildValue(_Py_PARSE_INTPTR, spawnval);
}
/*[clinic input]
os.spawnve
mode: int
Mode of process creation.
path: path_t
Path of executable file.
argv: object
Tuple or list of strings.
env: object
Dictionary of strings mapping to strings.
/
Execute the program specified by path in a new process.
[clinic start generated code]*/
static PyObject *
os_spawnve_impl(PyObject *module, int mode, path_t *path, PyObject *argv,
PyObject *env)
/*[clinic end generated code: output=30fe85be56fe37ad input=3e40803ee7c4c586]*/
{
EXECV_CHAR **argvlist;
EXECV_CHAR **envlist;
PyObject *res = NULL;
Py_ssize_t argc, i, envc;
intptr_t spawnval;
PyObject *(*getitem)(PyObject *, Py_ssize_t);
Py_ssize_t lastarg = 0;
/* spawnve has four arguments: (mode, path, argv, env), where
argv is a list or tuple of strings and env is a dictionary
like posix.environ. */
if (PyList_Check(argv)) {
argc = PyList_Size(argv);
getitem = PyList_GetItem;
}
else if (PyTuple_Check(argv)) {
argc = PyTuple_Size(argv);
getitem = PyTuple_GetItem;
}
else {
PyErr_SetString(PyExc_TypeError,
"spawnve() arg 2 must be a tuple or list");
goto fail_0;
}
if (argc == 0) {
PyErr_SetString(PyExc_ValueError,
"spawnve() arg 2 cannot be empty");
goto fail_0;
}
if (!PyMapping_Check(env)) {
PyErr_SetString(PyExc_TypeError,
"spawnve() arg 3 must be a mapping object");
goto fail_0;
}
argvlist = PyMem_NEW(EXECV_CHAR *, argc+1);
if (argvlist == NULL) {
PyErr_NoMemory();
goto fail_0;
}
for (i = 0; i < argc; i++) {
if (!fsconvert_strdup((*getitem)(argv, i),
&argvlist[i]))
{
lastarg = i;
goto fail_1;
}
if (i == 0 && !argvlist[0][0]) {
lastarg = i + 1;
PyErr_SetString(
PyExc_ValueError,
"spawnv() arg 2 first element cannot be empty");
goto fail_1;
}
}
lastarg = argc;
argvlist[argc] = NULL;
envlist = parse_envlist(env, &envc);
if (envlist == NULL)
goto fail_1;
if (mode == _OLD_P_OVERLAY)
mode = _P_OVERLAY;
Py_BEGIN_ALLOW_THREADS
_Py_BEGIN_SUPPRESS_IPH
#ifdef HAVE_WSPAWNV
spawnval = _wspawnve(mode, path->wide, argvlist, envlist);
#else
spawnval = _spawnve(mode, path->narrow, argvlist, envlist);
#endif
_Py_END_SUPPRESS_IPH
Py_END_ALLOW_THREADS
if (spawnval == -1)
(void) posix_error();
else
res = Py_BuildValue(_Py_PARSE_INTPTR, spawnval);
while (--envc >= 0)
PyMem_DEL(envlist[envc]);
PyMem_DEL(envlist);
fail_1:
free_string_array(argvlist, lastarg);
fail_0:
return res;
}
#endif /* HAVE_SPAWNV */
#ifdef HAVE_FORK1
/*[clinic input]
os.fork1
Fork a child process with a single multiplexed (i.e., not bound) thread.
Return 0 to child process and PID of child to parent process.
[clinic start generated code]*/
static PyObject *
os_fork1_impl(PyObject *module)
/*[clinic end generated code: output=0de8e67ce2a310bc input=12db02167893926e]*/
{
pid_t pid;
int result = 0;
_PyImport_AcquireLock();
pid = fork1();
if (pid == 0) {
/* child: this clobbers and resets the import lock. */
PyOS_AfterFork();
} else {
/* parent: release the import lock. */
result = _PyImport_ReleaseLock();
}
if (pid == -1)
return posix_error();
if (result < 0) {
/* Don't clobber the OSError if the fork failed. */
PyErr_SetString(PyExc_RuntimeError,
"not holding the import lock");
return NULL;
}
return PyLong_FromPid(pid);
}
#endif /* HAVE_FORK1 */
#ifdef HAVE_FORK
/*[clinic input]
os.fork
Fork a child process.
Return 0 to child process and PID of child to parent process.
[clinic start generated code]*/
static PyObject *
os_fork_impl(PyObject *module)
/*[clinic end generated code: output=3626c81f98985d49 input=13c956413110eeaa]*/
{
pid_t pid;
int result = 0;
_PyImport_AcquireLock();
pid = fork();
if (pid == 0) {
/* child: this clobbers and resets the import lock. */
PyOS_AfterFork();
} else {
/* parent: release the import lock. */
result = _PyImport_ReleaseLock();
}
if (pid == -1)
return posix_error();
if (result < 0) {
/* Don't clobber the OSError if the fork failed. */
PyErr_SetString(PyExc_RuntimeError,
"not holding the import lock");
return NULL;
}
return PyLong_FromPid(pid);
}
#endif /* HAVE_FORK */
#ifdef HAVE_SCHED_GET_PRIORITY_MAX
/*[clinic input]
os.sched_get_priority_max
policy: int
Get the maximum scheduling priority for policy.
[clinic start generated code]*/
static PyObject *
os_sched_get_priority_max_impl(PyObject *module, int policy)
/*[clinic end generated code: output=9e465c6e43130521 input=2097b7998eca6874]*/
{
int max;
max = sched_get_priority_max(policy);
if (max < 0)
return posix_error();
return PyLong_FromLong(max);
}
/*[clinic input]
os.sched_get_priority_min
policy: int
Get the minimum scheduling priority for policy.
[clinic start generated code]*/
static PyObject *
os_sched_get_priority_min_impl(PyObject *module, int policy)
/*[clinic end generated code: output=7595c1138cc47a6d input=21bc8fa0d70983bf]*/
{
int min = sched_get_priority_min(policy);
if (min < 0)
return posix_error();
return PyLong_FromLong(min);
}
#endif /* HAVE_SCHED_GET_PRIORITY_MAX */
#ifdef HAVE_SCHED_SETSCHEDULER
/*[clinic input]
os.sched_getscheduler
pid: pid_t
/
Get the scheduling policy for the process identifiedy by pid.
Passing 0 for pid returns the scheduling policy for the calling process.
[clinic start generated code]*/
static PyObject *
os_sched_getscheduler_impl(PyObject *module, pid_t pid)
/*[clinic end generated code: output=dce4c0bd3f1b34c8 input=5f14cfd1f189e1a0]*/
{
int policy;
policy = sched_getscheduler(pid);
if (policy < 0)
return posix_error();
return PyLong_FromLong(policy);
}
#endif /* HAVE_SCHED_SETSCHEDULER */
#if defined(HAVE_SCHED_SETSCHEDULER) || defined(HAVE_SCHED_SETPARAM)
/*[clinic input]
class os.sched_param "PyObject *" "&SchedParamType"
@classmethod
os.sched_param.__new__
sched_priority: object
A scheduling parameter.
Current has only one field: sched_priority");
[clinic start generated code]*/
static PyObject *
os_sched_param_impl(PyTypeObject *type, PyObject *sched_priority)
/*[clinic end generated code: output=48f4067d60f48c13 input=73a4c22f7071fc62]*/
{
PyObject *res;
res = PyStructSequence_New(type);
if (!res)
return NULL;
Py_INCREF(sched_priority);
PyStructSequence_SET_ITEM(res, 0, sched_priority);
return res;
}
PyDoc_VAR(os_sched_param__doc__);
static PyStructSequence_Field sched_param_fields[] = {
{"sched_priority", PyDoc_STR("the scheduling priority")},
{0}
};
static PyStructSequence_Desc sched_param_desc = {
"sched_param", /* name */
os_sched_param__doc__, /* doc */
sched_param_fields,
1
};
static int
convert_sched_param(PyObject *param, struct sched_param *res)
{
long priority;
if (Py_TYPE(param) != &SchedParamType) {
PyErr_SetString(PyExc_TypeError, "must have a sched_param object");
return 0;
}
priority = PyLong_AsLong(PyStructSequence_GET_ITEM(param, 0));
if (priority == -1 && PyErr_Occurred())
return 0;
if (priority > INT_MAX || priority < INT_MIN) {
PyErr_SetString(PyExc_OverflowError, "sched_priority out of range");
return 0;
}
res->sched_priority = Py_SAFE_DOWNCAST(priority, long, int);
return 1;
}
#endif /* defined(HAVE_SCHED_SETSCHEDULER) || defined(HAVE_SCHED_SETPARAM) */
#ifdef HAVE_SCHED_SETSCHEDULER
/*[clinic input]
os.sched_setscheduler
pid: pid_t
policy: int
param: sched_param
/
Set the scheduling policy for the process identified by pid.
If pid is 0, the calling process is changed.
param is an instance of sched_param.
[clinic start generated code]*/
static PyObject *
os_sched_setscheduler_impl(PyObject *module, pid_t pid, int policy,
struct sched_param *param)
/*[clinic end generated code: output=b0ac0a70d3b1d705 input=c581f9469a5327dd]*/
{
/*
** sched_setscheduler() returns 0 in Linux, but the previous
** scheduling policy under Solaris/Illumos, and others.
** On error, -1 is returned in all Operating Systems.
*/
if (sched_setscheduler(pid, policy, param) == -1)
return posix_error();
Py_RETURN_NONE;
}
#endif /* HAVE_SCHED_SETSCHEDULER*/
#ifdef HAVE_SCHED_SETPARAM
/*[clinic input]
os.sched_getparam
pid: pid_t
/
Returns scheduling parameters for the process identified by pid.
If pid is 0, returns parameters for the calling process.
Return value is an instance of sched_param.
[clinic start generated code]*/
static PyObject *
os_sched_getparam_impl(PyObject *module, pid_t pid)
/*[clinic end generated code: output=b194e8708dcf2db8 input=18a1ef9c2efae296]*/
{
struct sched_param param;
PyObject *result;
PyObject *priority;
if (sched_getparam(pid, ¶m))
return posix_error();
result = PyStructSequence_New(&SchedParamType);
if (!result)
return NULL;
priority = PyLong_FromLong(param.sched_priority);
if (!priority) {
Py_DECREF(result);
return NULL;
}
PyStructSequence_SET_ITEM(result, 0, priority);
return result;
}
/*[clinic input]
os.sched_setparam
pid: pid_t
param: sched_param
/
Set scheduling parameters for the process identified by pid.
If pid is 0, sets parameters for the calling process.
param should be an instance of sched_param.
[clinic start generated code]*/
static PyObject *
os_sched_setparam_impl(PyObject *module, pid_t pid,
struct sched_param *param)
/*[clinic end generated code: output=8af013f78a32b591 input=6b8d6dfcecdc21bd]*/
{
if (sched_setparam(pid, param))
return posix_error();
Py_RETURN_NONE;
}
#endif /* HAVE_SCHED_SETPARAM */
#ifdef HAVE_SCHED_RR_GET_INTERVAL
/*[clinic input]
os.sched_rr_get_interval -> double
pid: pid_t
/
Return the round-robin quantum for the process identified by pid, in seconds.
Value returned is a float.
[clinic start generated code]*/
static double
os_sched_rr_get_interval_impl(PyObject *module, pid_t pid)
/*[clinic end generated code: output=7e2d935833ab47dc input=2a973da15cca6fae]*/
{
struct timespec interval;
if (sched_rr_get_interval(pid, &interval)) {
posix_error();
return -1.0;
}
return (double)interval.tv_sec + 1e-9*interval.tv_nsec;
}
#endif /* HAVE_SCHED_RR_GET_INTERVAL */
/*[clinic input]
os.sched_yield
Voluntarily relinquish the CPU.
[clinic start generated code]*/
static PyObject *
os_sched_yield_impl(PyObject *module)
/*[clinic end generated code: output=902323500f222cac input=e54d6f98189391d4]*/
{
if (sched_yield())
return posix_error();
Py_RETURN_NONE;
}
#ifdef HAVE_SCHED_SETAFFINITY
/* The minimum number of CPUs allocated in a cpu_set_t */
static const int NCPUS_START = sizeof(unsigned long) * CHAR_BIT;
/*[clinic input]
os.sched_setaffinity
pid: pid_t
mask : object
/
Set the CPU affinity of the process identified by pid to mask.
mask should be an iterable of integers identifying CPUs.
[clinic start generated code]*/
static PyObject *
os_sched_setaffinity_impl(PyObject *module, pid_t pid, PyObject *mask)
/*[clinic end generated code: output=882d7dd9a229335b input=a0791a597c7085ba]*/
{
int ncpus;
size_t setsize;
cpu_set_t *cpu_set = NULL;
PyObject *iterator = NULL, *item;
iterator = PyObject_GetIter(mask);
if (iterator == NULL)
return NULL;
ncpus = NCPUS_START;
setsize = CPU_ALLOC_SIZE(ncpus);
cpu_set = CPU_ALLOC(ncpus);
if (cpu_set == NULL) {
PyErr_NoMemory();
goto error;
}
CPU_ZERO_S(setsize, cpu_set);
while ((item = PyIter_Next(iterator))) {
long cpu;
if (!PyLong_Check(item)) {
PyErr_Format(PyExc_TypeError,
"expected an iterator of ints, "
"but iterator yielded %R",
Py_TYPE(item));
Py_DECREF(item);
goto error;
}
cpu = PyLong_AsLong(item);
Py_DECREF(item);
if (cpu < 0) {
if (!PyErr_Occurred())
PyErr_SetString(PyExc_ValueError, "negative CPU number");
goto error;
}
if (cpu > INT_MAX - 1) {
PyErr_SetString(PyExc_OverflowError, "CPU number too large");
goto error;
}
if (cpu >= ncpus) {
/* Grow CPU mask to fit the CPU number */
int newncpus = ncpus;
cpu_set_t *newmask;
size_t newsetsize;
while (newncpus <= cpu) {
if (newncpus > INT_MAX / 2)
newncpus = cpu + 1;
else
newncpus = newncpus * 2;
}
newmask = CPU_ALLOC(newncpus);
if (newmask == NULL) {
PyErr_NoMemory();
goto error;
}
newsetsize = CPU_ALLOC_SIZE(newncpus);
CPU_ZERO_S(newsetsize, newmask);
memcpy(newmask, cpu_set, setsize);
CPU_FREE(cpu_set);
setsize = newsetsize;
cpu_set = newmask;
ncpus = newncpus;
}
CPU_SET_S(cpu, setsize, cpu_set);
}
Py_CLEAR(iterator);
if (sched_setaffinity(pid, setsize, cpu_set)) {
posix_error();
goto error;
}
CPU_FREE(cpu_set);
Py_RETURN_NONE;
error:
if (cpu_set)
CPU_FREE(cpu_set);
Py_XDECREF(iterator);
return NULL;
}
/*[clinic input]
os.sched_getaffinity
pid: pid_t
/
Return the affinity of the process identified by pid (or the current process if zero).
The affinity is returned as a set of CPU identifiers.
[clinic start generated code]*/
static PyObject *
os_sched_getaffinity_impl(PyObject *module, pid_t pid)
/*[clinic end generated code: output=f726f2c193c17a4f input=983ce7cb4a565980]*/
{
int cpu, ncpus, count;
size_t setsize;
cpu_set_t *mask = NULL;
PyObject *res = NULL;
ncpus = NCPUS_START;
while (1) {
setsize = CPU_ALLOC_SIZE(ncpus);
mask = CPU_ALLOC(ncpus);
if (mask == NULL)
return PyErr_NoMemory();
if (sched_getaffinity(pid, setsize, mask) == 0)
break;
CPU_FREE(mask);
if (errno != EINVAL)
return posix_error();
if (ncpus > INT_MAX / 2) {
PyErr_SetString(PyExc_OverflowError, "could not allocate "
"a large enough CPU set");
return NULL;
}
ncpus = ncpus * 2;
}
res = PySet_New(NULL);
if (res == NULL)
goto error;
for (cpu = 0, count = CPU_COUNT_S(setsize, mask); count; cpu++) {
if (CPU_ISSET_S(cpu, setsize, mask)) {
PyObject *cpu_num = PyLong_FromLong(cpu);
--count;
if (cpu_num == NULL)
goto error;
if (PySet_Add(res, cpu_num)) {
Py_DECREF(cpu_num);
goto error;
}
Py_DECREF(cpu_num);
}
}
CPU_FREE(mask);
return res;
error:
if (mask)
CPU_FREE(mask);
Py_XDECREF(res);
return NULL;
}
#endif /* HAVE_SCHED_SETAFFINITY */
/* AIX uses /dev/ptc but is otherwise the same as /dev/ptmx */
/* IRIX has both /dev/ptc and /dev/ptmx, use ptmx */
#if defined(HAVE_DEV_PTC) && !defined(HAVE_DEV_PTMX)
#define DEV_PTY_FILE "/dev/ptc"
#define HAVE_DEV_PTMX
#else
#define DEV_PTY_FILE "/dev/ptmx"
#endif
#if defined(HAVE_OPENPTY) || defined(HAVE__GETPTY) || defined(HAVE_DEV_PTMX)
/*[clinic input]
os.openpty
Open a pseudo-terminal.
Return a tuple of (master_fd, slave_fd) containing open file descriptors
for both the master and slave ends.
[clinic start generated code]*/
static PyObject *
os_openpty_impl(PyObject *module)
/*[clinic end generated code: output=98841ce5ec9cef3c input=f3d99fd99e762907]*/
{
int master_fd = -1, slave_fd = -1;
#ifndef HAVE_OPENPTY
char * slave_name;
#endif
#if defined(HAVE_DEV_PTMX) && !defined(HAVE_OPENPTY) && !defined(HAVE__GETPTY)
PyOS_sighandler_t sig_saved;
#ifdef sun
extern char *ptsname(int fildes);
#endif
#endif
#ifdef HAVE_OPENPTY
if (openpty(&master_fd, &slave_fd, NULL, NULL, NULL) != 0)
goto posix_error;
if (_Py_set_inheritable(master_fd, 0, NULL) < 0)
goto error;
if (_Py_set_inheritable(slave_fd, 0, NULL) < 0)
goto error;
#elif defined(HAVE__GETPTY)
slave_name = _getpty(&master_fd, O_RDWR, 0666, 0);
if (slave_name == NULL)
goto posix_error;
if (_Py_set_inheritable(master_fd, 0, NULL) < 0)
goto error;
slave_fd = _Py_open(slave_name, O_RDWR);
if (slave_fd < 0)
goto error;
#else
master_fd = open(DEV_PTY_FILE, O_RDWR | O_NOCTTY); /* open master */
if (master_fd < 0)
goto posix_error;
sig_saved = PyOS_setsig(SIGCHLD, SIG_DFL);
/* change permission of slave */
if (grantpt(master_fd) < 0) {
PyOS_setsig(SIGCHLD, sig_saved);
goto posix_error;
}
/* unlock slave */
if (unlockpt(master_fd) < 0) {
PyOS_setsig(SIGCHLD, sig_saved);
goto posix_error;
}
PyOS_setsig(SIGCHLD, sig_saved);
slave_name = ptsname(master_fd); /* get name of slave */
if (slave_name == NULL)
goto posix_error;
slave_fd = _Py_open(slave_name, O_RDWR | O_NOCTTY); /* open slave */
if (slave_fd == -1)
goto error;
if (_Py_set_inheritable(master_fd, 0, NULL) < 0)
goto posix_error;
#if !defined(__CYGWIN__) && !defined(__ANDROID__) && !defined(HAVE_DEV_PTC)
ioctl(slave_fd, I_PUSH, "ptem"); /* push ptem */
ioctl(slave_fd, I_PUSH, "ldterm"); /* push ldterm */
#ifndef __hpux
ioctl(slave_fd, I_PUSH, "ttcompat"); /* push ttcompat */
#endif /* __hpux */
#endif /* HAVE_CYGWIN */
#endif /* HAVE_OPENPTY */
return Py_BuildValue("(ii)", master_fd, slave_fd);
posix_error:
posix_error();
error:
if (master_fd != -1)
close(master_fd);
if (slave_fd != -1)
close(slave_fd);
return NULL;
}
#endif /* defined(HAVE_OPENPTY) || defined(HAVE__GETPTY) || defined(HAVE_DEV_PTMX) */
#if HAVE_FORKPTY
/*[clinic input]
os.forkpty
Fork a new process with a new pseudo-terminal as controlling tty.
Returns a tuple of (pid, master_fd).
Like fork(), return pid of 0 to the child process,
and pid of child to the parent process.
To both, return fd of newly opened pseudo-terminal.
[clinic start generated code]*/
static PyObject *
os_forkpty_impl(PyObject *module)
/*[clinic end generated code: output=60d0a5c7512e4087 input=f1f7f4bae3966010]*/
{
int master_fd = -1, result = 0;
pid_t pid;
_PyImport_AcquireLock();
pid = forkpty(&master_fd, NULL, NULL, NULL);
if (pid == 0) {
/* child: this clobbers and resets the import lock. */
PyOS_AfterFork();
} else {
/* parent: release the import lock. */
result = _PyImport_ReleaseLock();
}
if (pid == -1)
return posix_error();
if (result < 0) {
/* Don't clobber the OSError if the fork failed. */
PyErr_SetString(PyExc_RuntimeError,
"not holding the import lock");
return NULL;
}
return Py_BuildValue("(Ni)", PyLong_FromPid(pid), master_fd);
}
#endif /* HAVE_FORKPTY */
#ifdef HAVE_GETEGID
/*[clinic input]
os.getegid
Return the current process's effective group id.
[clinic start generated code]*/
static PyObject *
os_getegid_impl(PyObject *module)
/*[clinic end generated code: output=67d9be7ac68898a2 input=1596f79ad1107d5d]*/
{
return _PyLong_FromGid(getegid());
}
#endif /* HAVE_GETEGID */
#ifdef HAVE_GETEUID
/*[clinic input]
os.geteuid
Return the current process's effective user id.
[clinic start generated code]*/
static PyObject *
os_geteuid_impl(PyObject *module)
/*[clinic end generated code: output=ea1b60f0d6abb66e input=4644c662d3bd9f19]*/
{
return _PyLong_FromUid(geteuid());
}
#endif /* HAVE_GETEUID */
#ifdef HAVE_GETGID
/*[clinic input]
os.getgid
Return the current process's group id.
[clinic start generated code]*/
static PyObject *
os_getgid_impl(PyObject *module)
/*[clinic end generated code: output=4f28ebc9d3e5dfcf input=58796344cd87c0f6]*/
{
return _PyLong_FromGid(getgid());
}
#endif /* HAVE_GETGID */
#ifdef HAVE_GETPID
/*[clinic input]
os.getpid
Return the current process id.
[clinic start generated code]*/
static PyObject *
os_getpid_impl(PyObject *module)
/*[clinic end generated code: output=9ea6fdac01ed2b3c input=5a9a00f0ab68aa00]*/
{
return PyLong_FromPid(getpid());
}
#endif /* HAVE_GETPID */
#ifdef HAVE_GETGROUPLIST
/* AC 3.5: funny apple logic below */
PyDoc_STRVAR(posix_getgrouplist__doc__,
"getgrouplist(user, group) -> list of groups to which a user belongs\n\n\
Returns a list of groups to which a user belongs.\n\n\
user: username to lookup\n\
group: base group id of the user");
static PyObject *
posix_getgrouplist(PyObject *self, PyObject *args)
{
#ifdef NGROUPS_MAX
#define MAX_GROUPS NGROUPS_MAX
#else
/* defined to be 16 on Solaris7, so this should be a small number */
#define MAX_GROUPS 64
#endif
const char *user;
int i, ngroups;
PyObject *list;
#ifdef __APPLE__
int *groups, basegid;
#else
gid_t *groups, basegid;
#endif
ngroups = MAX_GROUPS;
#ifdef __APPLE__
if (!PyArg_ParseTuple(args, "si:getgrouplist", &user, &basegid))
return NULL;
#else
if (!PyArg_ParseTuple(args, "sO&:getgrouplist", &user,
_Py_Gid_Converter, &basegid))
return NULL;
#endif
#ifdef __APPLE__
groups = PyMem_New(int, ngroups);
#else
groups = PyMem_New(gid_t, ngroups);
#endif
if (groups == NULL)
return PyErr_NoMemory();
if (getgrouplist(user, basegid, groups, &ngroups) == -1) {
PyMem_Del(groups);
return posix_error();
}
list = PyList_New(ngroups);
if (list == NULL) {
PyMem_Del(groups);
return NULL;
}
for (i = 0; i < ngroups; i++) {
#ifdef __APPLE__
PyObject *o = PyLong_FromUnsignedLong((unsigned long)groups[i]);
#else
PyObject *o = _PyLong_FromGid(groups[i]);
#endif
if (o == NULL) {
Py_DECREF(list);
PyMem_Del(groups);
return NULL;
}
PyList_SET_ITEM(list, i, o);
}
PyMem_Del(groups);
return list;
}
#endif /* HAVE_GETGROUPLIST */
#ifdef HAVE_GETGROUPS
/*[clinic input]
os.getgroups
Return list of supplemental group IDs for the process.
[clinic start generated code]*/
static PyObject *
os_getgroups_impl(PyObject *module)
/*[clinic end generated code: output=42b0c17758561b56 input=d3f109412e6a155c]*/
{
PyObject *result = NULL;
#ifdef NGROUPS_MAX
#define MAX_GROUPS NGROUPS_MAX
#else
/* defined to be 16 on Solaris7, so this should be a small number */
#define MAX_GROUPS 64
#endif
gid_t grouplist[MAX_GROUPS];
/* On MacOSX getgroups(2) can return more than MAX_GROUPS results
* This is a helper variable to store the intermediate result when
* that happens.
*
* To keep the code readable the OSX behaviour is unconditional,
* according to the POSIX spec this should be safe on all unix-y
* systems.
*/
gid_t* alt_grouplist = grouplist;
int n;
#ifdef __APPLE__
/* Issue #17557: As of OS X 10.8, getgroups(2) no longer raises EINVAL if
* there are more groups than can fit in grouplist. Therefore, on OS X
* always first call getgroups with length 0 to get the actual number
* of groups.
*/
n = getgroups(0, NULL);
if (n < 0) {
return posix_error();
} else if (n <= MAX_GROUPS) {
/* groups will fit in existing array */
alt_grouplist = grouplist;
} else {
alt_grouplist = PyMem_New(gid_t, n);
if (alt_grouplist == NULL) {
return PyErr_NoMemory();
}
}
n = getgroups(n, alt_grouplist);
if (n == -1) {
if (alt_grouplist != grouplist) {
PyMem_Free(alt_grouplist);
}
return posix_error();
}
#else
n = getgroups(MAX_GROUPS, grouplist);
if (n < 0) {
if (errno == EINVAL) {
n = getgroups(0, NULL);
if (n == -1) {
return posix_error();
}
if (n == 0) {
/* Avoid malloc(0) */
alt_grouplist = grouplist;
} else {
alt_grouplist = PyMem_New(gid_t, n);
if (alt_grouplist == NULL) {
return PyErr_NoMemory();
}
n = getgroups(n, alt_grouplist);
if (n == -1) {
PyMem_Free(alt_grouplist);
return posix_error();
}
}
} else {
return posix_error();
}
}
#endif
result = PyList_New(n);
if (result != NULL) {
int i;
for (i = 0; i < n; ++i) {
PyObject *o = _PyLong_FromGid(alt_grouplist[i]);
if (o == NULL) {
Py_DECREF(result);
result = NULL;
break;
}
PyList_SET_ITEM(result, i, o);
}
}
if (alt_grouplist != grouplist) {
PyMem_Free(alt_grouplist);
}
return result;
}
#endif /* HAVE_GETGROUPS */
#ifdef HAVE_INITGROUPS
PyDoc_STRVAR(posix_initgroups__doc__,
"initgroups(username, gid) -> None\n\n\
Call the system initgroups() to initialize the group access list with all of\n\
the groups of which the specified username is a member, plus the specified\n\
group id.");
/* AC 3.5: funny apple logic */
static PyObject *
posix_initgroups(PyObject *self, PyObject *args)
{
PyObject *oname;
const char *username;
int res;
#ifdef __APPLE__
int gid;
#else
gid_t gid;
#endif
#ifdef __APPLE__
if (!PyArg_ParseTuple(args, "O&i:initgroups",
PyUnicode_FSConverter, &oname,
&gid))
#else
if (!PyArg_ParseTuple(args, "O&O&:initgroups",
PyUnicode_FSConverter, &oname,
_Py_Gid_Converter, &gid))
#endif
return NULL;
username = PyBytes_AS_STRING(oname);
res = initgroups(username, gid);
Py_DECREF(oname);
if (res == -1)
return PyErr_SetFromErrno(PyExc_OSError);
Py_INCREF(Py_None);
return Py_None;
}
#endif /* HAVE_INITGROUPS */
#ifdef HAVE_GETPGID
/*[clinic input]
os.getpgid
pid: pid_t
Call the system call getpgid(), and return the result.
[clinic start generated code]*/
static PyObject *
os_getpgid_impl(PyObject *module, pid_t pid)
/*[clinic end generated code: output=1db95a97be205d18 input=39d710ae3baaf1c7]*/
{
pid_t pgid = getpgid(pid);
if (pgid < 0)
return posix_error();
return PyLong_FromPid(pgid);
}
#endif /* HAVE_GETPGID */
#ifdef HAVE_GETPGRP
/*[clinic input]
os.getpgrp
Return the current process group id.
[clinic start generated code]*/
static PyObject *
os_getpgrp_impl(PyObject *module)
/*[clinic end generated code: output=c4fc381e51103cf3 input=6846fb2bb9a3705e]*/
{
#ifdef GETPGRP_HAVE_ARG
return PyLong_FromPid(getpgrp(0));
#else /* GETPGRP_HAVE_ARG */
return PyLong_FromPid(getpgrp());
#endif /* GETPGRP_HAVE_ARG */
}
#endif /* HAVE_GETPGRP */
#ifdef HAVE_SETPGRP
/*[clinic input]
os.setpgrp
Make the current process the leader of its process group.
[clinic start generated code]*/
static PyObject *
os_setpgrp_impl(PyObject *module)
/*[clinic end generated code: output=2554735b0a60f0a0 input=1f0619fcb5731e7e]*/
{
#ifdef SETPGRP_HAVE_ARG
if (setpgrp(0, 0) < 0)
#else /* SETPGRP_HAVE_ARG */
if (setpgrp() < 0)
#endif /* SETPGRP_HAVE_ARG */
return posix_error();
Py_INCREF(Py_None);
return Py_None;
}
#endif /* HAVE_SETPGRP */
#ifdef HAVE_GETPPID
#ifdef MS_WINDOWS
static PyObject*
win32_getppid()
{
HANDLE snapshot;
pid_t mypid;
PyObject* result = NULL;
BOOL have_record;
PROCESSENTRY32 pe;
mypid = getpid(); /* This function never fails */
snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if (snapshot == INVALID_HANDLE_VALUE)
return PyErr_SetFromWindowsErr(GetLastError());
pe.dwSize = sizeof(pe);
have_record = Process32First(snapshot, &pe);
while (have_record) {
if (mypid == (pid_t)pe.th32ProcessID) {
/* We could cache the ulong value in a static variable. */
result = PyLong_FromPid((pid_t)pe.th32ParentProcessID);
break;
}
have_record = Process32Next(snapshot, &pe);
}
/* If our loop exits and our pid was not found (result will be NULL)
* then GetLastError will return ERROR_NO_MORE_FILES. This is an
* error anyway, so let's raise it. */
if (!result)
result = PyErr_SetFromWindowsErr(GetLastError());
CloseHandle(snapshot);
return result;
}
#endif /*MS_WINDOWS*/
/*[clinic input]
os.getppid
Return the parent's process id.
If the parent process has already exited, Windows machines will still
return its id; others systems will return the id of the 'init' process (1).
[clinic start generated code]*/
static PyObject *
os_getppid_impl(PyObject *module)
/*[clinic end generated code: output=43b2a946a8c603b4 input=e637cb87539c030e]*/
{
#ifdef MS_WINDOWS
return win32_getppid();
#else
return PyLong_FromPid(getppid());
#endif
}
#endif /* HAVE_GETPPID */
#ifdef HAVE_GETLOGIN
/*[clinic input]
os.getlogin
Return the actual login name.
[clinic start generated code]*/
static PyObject *
os_getlogin_impl(PyObject *module)
/*[clinic end generated code: output=a32e66a7e5715dac input=2a21ab1e917163df]*/
{
PyObject *result = NULL;
#ifdef MS_WINDOWS
wchar_t user_name[UNLEN + 1];
DWORD num_chars = Py_ARRAY_LENGTH(user_name);
if (GetUserNameW(user_name, &num_chars)) {
/* num_chars is the number of unicode chars plus null terminator */
result = PyUnicode_FromWideChar(user_name, num_chars - 1);
}
else
result = PyErr_SetFromWindowsErr(GetLastError());
#else
char *name;
int old_errno = errno;
errno = 0;
name = getlogin();
if (name == NULL) {
if (errno)
posix_error();
else
PyErr_SetString(PyExc_OSError, "unable to determine login name");
}
else
result = PyUnicode_DecodeFSDefault(name);
errno = old_errno;
#endif
return result;
}
#endif /* HAVE_GETLOGIN */
#ifdef HAVE_GETUID
/*[clinic input]
os.getuid
Return the current process's user id.
[clinic start generated code]*/
static PyObject *
os_getuid_impl(PyObject *module)
/*[clinic end generated code: output=415c0b401ebed11a input=b53c8b35f110a516]*/
{
return _PyLong_FromUid(getuid());
}
#endif /* HAVE_GETUID */
#ifdef MS_WINDOWS
#define HAVE_KILL
#endif /* MS_WINDOWS */
#ifdef HAVE_KILL
/*[clinic input]
os.kill
pid: pid_t
signal: Py_ssize_t
/
Kill a process with a signal.
[clinic start generated code]*/
static PyObject *
os_kill_impl(PyObject *module, pid_t pid, Py_ssize_t signal)
/*[clinic end generated code: output=8e346a6701c88568 input=61a36b86ca275ab9]*/
#ifndef MS_WINDOWS
{
if (kill(pid, (int)signal) == -1)
return posix_error();
Py_RETURN_NONE;
}
#else /* !MS_WINDOWS */
{
PyObject *result;
DWORD sig = (DWORD)signal;
DWORD err;
HANDLE handle;
/* Console processes which share a common console can be sent CTRL+C or
CTRL+BREAK events, provided they handle said events. */
if (sig == CTRL_C_EVENT || sig == CTRL_BREAK_EVENT) {
if (GenerateConsoleCtrlEvent(sig, (DWORD)pid) == 0) {
err = GetLastError();
PyErr_SetFromWindowsErr(err);
}
else
Py_RETURN_NONE;
}
/* If the signal is outside of what GenerateConsoleCtrlEvent can use,
attempt to open and terminate the process. */
handle = OpenProcess(PROCESS_ALL_ACCESS, FALSE, (DWORD)pid);
if (handle == NULL) {
err = GetLastError();
return PyErr_SetFromWindowsErr(err);
}
if (TerminateProcess(handle, sig) == 0) {
err = GetLastError();
result = PyErr_SetFromWindowsErr(err);
} else {
Py_INCREF(Py_None);
result = Py_None;
}
CloseHandle(handle);
return result;
}
#endif /* !MS_WINDOWS */
#endif /* HAVE_KILL */
#ifdef HAVE_KILLPG
/*[clinic input]
os.killpg
pgid: pid_t
signal: int
/
Kill a process group with a signal.
[clinic start generated code]*/
static PyObject *
os_killpg_impl(PyObject *module, pid_t pgid, int signal)
/*[clinic end generated code: output=6dbcd2f1fdf5fdba input=38b5449eb8faec19]*/
{
/* XXX some man pages make the `pgid` parameter an int, others
a pid_t. Since getpgrp() returns a pid_t, we assume killpg should
take the same type. Moreover, pid_t is always at least as wide as
int (else compilation of this module fails), which is safe. */
if (killpg(pgid, signal) == -1)
return posix_error();
Py_RETURN_NONE;
}
#endif /* HAVE_KILLPG */
#ifdef HAVE_PLOCK
/*[clinic input]
os.plock
op: int
/
Lock program segments into memory.");
[clinic start generated code]*/
static PyObject *
os_plock_impl(PyObject *module, int op)
/*[clinic end generated code: output=81424167033b168e input=e6e5e348e1525f60]*/
{
if (plock(op) == -1)
return posix_error();
Py_RETURN_NONE;
}
#endif /* HAVE_PLOCK */
#ifdef HAVE_SETUID
/*[clinic input]
os.setuid
uid: uid_t
/
Set the current process's user id.
[clinic start generated code]*/
static PyObject *
os_setuid_impl(PyObject *module, uid_t uid)
/*[clinic end generated code: output=a0a41fd0d1ec555f input=c921a3285aa22256]*/
{
if (setuid(uid) < 0)
return posix_error();
Py_RETURN_NONE;
}
#endif /* HAVE_SETUID */
#ifdef HAVE_SETEUID
/*[clinic input]
os.seteuid
euid: uid_t
/
Set the current process's effective user id.
[clinic start generated code]*/
static PyObject *
os_seteuid_impl(PyObject *module, uid_t euid)
/*[clinic end generated code: output=102e3ad98361519a input=ba93d927e4781aa9]*/
{
if (seteuid(euid) < 0)
return posix_error();
Py_RETURN_NONE;
}
#endif /* HAVE_SETEUID */
#ifdef HAVE_SETEGID
/*[clinic input]
os.setegid
egid: gid_t
/
Set the current process's effective group id.
[clinic start generated code]*/
static PyObject *
os_setegid_impl(PyObject *module, gid_t egid)
/*[clinic end generated code: output=4e4b825a6a10258d input=4080526d0ccd6ce3]*/
{
if (setegid(egid) < 0)
return posix_error();
Py_RETURN_NONE;
}
#endif /* HAVE_SETEGID */
#ifdef HAVE_SETREUID
/*[clinic input]
os.setreuid
ruid: uid_t
euid: uid_t
/
Set the current process's real and effective user ids.
[clinic start generated code]*/
static PyObject *
os_setreuid_impl(PyObject *module, uid_t ruid, uid_t euid)
/*[clinic end generated code: output=62d991210006530a input=0ca8978de663880c]*/
{
if (setreuid(ruid, euid) < 0) {
return posix_error();
} else {
Py_INCREF(Py_None);
return Py_None;
}
}
#endif /* HAVE_SETREUID */
#ifdef HAVE_SETREGID
/*[clinic input]
os.setregid
rgid: gid_t
egid: gid_t
/
Set the current process's real and effective group ids.
[clinic start generated code]*/
static PyObject *
os_setregid_impl(PyObject *module, gid_t rgid, gid_t egid)
/*[clinic end generated code: output=aa803835cf5342f3 input=c59499f72846db78]*/
{
if (setregid(rgid, egid) < 0)
return posix_error();
Py_RETURN_NONE;
}
#endif /* HAVE_SETREGID */
#ifdef HAVE_SETGID
/*[clinic input]
os.setgid
gid: gid_t
/
Set the current process's group id.
[clinic start generated code]*/
static PyObject *
os_setgid_impl(PyObject *module, gid_t gid)
/*[clinic end generated code: output=bdccd7403f6ad8c3 input=27d30c4059045dc6]*/
{
if (setgid(gid) < 0)
return posix_error();
Py_RETURN_NONE;
}
#endif /* HAVE_SETGID */
#if HAVE_SETGROUPS
/*[clinic input]
os.setgroups
groups: object
/
Set the groups of the current process to list.
[clinic start generated code]*/
static PyObject *
os_setgroups(PyObject *module, PyObject *groups)
/*[clinic end generated code: output=3fcb32aad58c5ecd input=fa742ca3daf85a7e]*/
{
Py_ssize_t i, len;
gid_t grouplist[MAX_GROUPS];
if (!PySequence_Check(groups)) {
PyErr_SetString(PyExc_TypeError, "setgroups argument must be a sequence");
return NULL;
}
len = PySequence_Size(groups);
if (len < 0) {
return NULL;
}
if (len > MAX_GROUPS) {
PyErr_SetString(PyExc_ValueError, "too many groups");
return NULL;
}
for(i = 0; i < len; i++) {
PyObject *elem;
elem = PySequence_GetItem(groups, i);
if (!elem)
return NULL;
if (!PyLong_Check(elem)) {
PyErr_SetString(PyExc_TypeError,
"groups must be integers");
Py_DECREF(elem);
return NULL;
} else {
if (!_Py_Gid_Converter(elem, &grouplist[i])) {
Py_DECREF(elem);
return NULL;
}
}
Py_DECREF(elem);
}
if (setgroups(len, grouplist) < 0)
return posix_error();
Py_INCREF(Py_None);
return Py_None;
}
#endif /* HAVE_SETGROUPS */
#if defined(HAVE_WAIT3) || defined(HAVE_WAIT4)
static PyObject *
wait_helper(pid_t pid, int status, struct rusage *ru)
{
PyObject *result;
static PyObject *struct_rusage;
_Py_IDENTIFIER(struct_rusage);
if (pid == -1)
return posix_error();
if (struct_rusage == NULL) {
PyObject *m = PyImport_ImportModuleNoBlock("resource");
if (m == NULL)
return NULL;
struct_rusage = _PyObject_GetAttrId(m, &PyId_struct_rusage);
Py_DECREF(m);
if (struct_rusage == NULL)
return NULL;
}
/* XXX(nnorwitz): Copied (w/mods) from resource.c, there should be only one. */
result = PyStructSequence_New((PyTypeObject*) struct_rusage);
if (!result)
return NULL;
#ifndef doubletime
#define doubletime(TV) ((double)(TV).tv_sec + (TV).tv_usec * 0.000001)
#endif
PyStructSequence_SET_ITEM(result, 0,
PyFloat_FromDouble(doubletime(ru->ru_utime)));
PyStructSequence_SET_ITEM(result, 1,
PyFloat_FromDouble(doubletime(ru->ru_stime)));
#define SET_INT(result, index, value)\
PyStructSequence_SET_ITEM(result, index, PyLong_FromLong(value))
SET_INT(result, 2, ru->ru_maxrss);
SET_INT(result, 3, ru->ru_ixrss);
SET_INT(result, 4, ru->ru_idrss);
SET_INT(result, 5, ru->ru_isrss);
SET_INT(result, 6, ru->ru_minflt);
SET_INT(result, 7, ru->ru_majflt);
SET_INT(result, 8, ru->ru_nswap);
SET_INT(result, 9, ru->ru_inblock);
SET_INT(result, 10, ru->ru_oublock);
SET_INT(result, 11, ru->ru_msgsnd);
SET_INT(result, 12, ru->ru_msgrcv);
SET_INT(result, 13, ru->ru_nsignals);
SET_INT(result, 14, ru->ru_nvcsw);
SET_INT(result, 15, ru->ru_nivcsw);
#undef SET_INT
if (PyErr_Occurred()) {
Py_DECREF(result);
return NULL;
}
return Py_BuildValue("NiN", PyLong_FromPid(pid), status, result);
}
#endif /* HAVE_WAIT3 || HAVE_WAIT4 */
#ifdef HAVE_WAIT3
/*[clinic input]
os.wait3
options: int
Wait for completion of a child process.
Returns a tuple of information about the child process:
(pid, status, rusage)
[clinic start generated code]*/
static PyObject *
os_wait3_impl(PyObject *module, int options)
/*[clinic end generated code: output=92c3224e6f28217a input=8ac4c56956b61710]*/
{
pid_t pid;
struct rusage ru;
int async_err = 0;
WAIT_TYPE status;
WAIT_STATUS_INT(status) = 0;
do {
Py_BEGIN_ALLOW_THREADS
pid = wait3(&status, options, &ru);
Py_END_ALLOW_THREADS
} while (pid < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
if (pid < 0)
return (!async_err) ? posix_error() : NULL;
return wait_helper(pid, WAIT_STATUS_INT(status), &ru);
}
#endif /* HAVE_WAIT3 */
#ifdef HAVE_WAIT4
/*[clinic input]
os.wait4
pid: pid_t
options: int
Wait for completion of a specific child process.
Returns a tuple of information about the child process:
(pid, status, rusage)
[clinic start generated code]*/
static PyObject *
os_wait4_impl(PyObject *module, pid_t pid, int options)
/*[clinic end generated code: output=66195aa507b35f70 input=d11deed0750600ba]*/
{
pid_t res;
struct rusage ru;
int async_err = 0;
WAIT_TYPE status;
WAIT_STATUS_INT(status) = 0;
do {
Py_BEGIN_ALLOW_THREADS
res = wait4(pid, &status, options, &ru);
Py_END_ALLOW_THREADS
} while (res < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
if (res < 0)
return (!async_err) ? posix_error() : NULL;
return wait_helper(res, WAIT_STATUS_INT(status), &ru);
}
#endif /* HAVE_WAIT4 */
#if defined(HAVE_WAITID) && !defined(__APPLE__)
/*[clinic input]
os.waitid
idtype: idtype_t
Must be one of be P_PID, P_PGID or P_ALL.
id: id_t
The id to wait on.
options: int
Constructed from the ORing of one or more of WEXITED, WSTOPPED
or WCONTINUED and additionally may be ORed with WNOHANG or WNOWAIT.
/
Returns the result of waiting for a process or processes.
Returns either waitid_result or None if WNOHANG is specified and there are
no children in a waitable state.
[clinic start generated code]*/
static PyObject *
os_waitid_impl(PyObject *module, idtype_t idtype, id_t id, int options)
/*[clinic end generated code: output=5d2e1c0bde61f4d8 input=d8e7f76e052b7920]*/
{
PyObject *result;
int res;
int async_err = 0;
siginfo_t si;
si.si_pid = 0;
do {
Py_BEGIN_ALLOW_THREADS
res = waitid(idtype, id, &si, options);
Py_END_ALLOW_THREADS
} while (res < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
if (res < 0)
return (!async_err) ? posix_error() : NULL;
if (si.si_pid == 0)
Py_RETURN_NONE;
result = PyStructSequence_New(&WaitidResultType);
if (!result)
return NULL;
PyStructSequence_SET_ITEM(result, 0, PyLong_FromPid(si.si_pid));
PyStructSequence_SET_ITEM(result, 1, _PyLong_FromUid(si.si_uid));
PyStructSequence_SET_ITEM(result, 2, PyLong_FromLong((long)(si.si_signo)));
PyStructSequence_SET_ITEM(result, 3, PyLong_FromLong((long)(si.si_status)));
PyStructSequence_SET_ITEM(result, 4, PyLong_FromLong((long)(si.si_code)));
if (PyErr_Occurred()) {
Py_DECREF(result);
return NULL;
}
return result;
}
#endif /* defined(HAVE_WAITID) && !defined(__APPLE__) */
#if defined(HAVE_WAITPID)
/*[clinic input]
os.waitpid
pid: pid_t
options: int
/
Wait for completion of a given child process.
Returns a tuple of information regarding the child process:
(pid, status)
The options argument is ignored on Windows.
[clinic start generated code]*/
static PyObject *
os_waitpid_impl(PyObject *module, pid_t pid, int options)
/*[clinic end generated code: output=5c37c06887a20270 input=0bf1666b8758fda3]*/
{
pid_t res;
int async_err = 0;
WAIT_TYPE status;
WAIT_STATUS_INT(status) = 0;
do {
Py_BEGIN_ALLOW_THREADS
res = waitpid(pid, &status, options);
Py_END_ALLOW_THREADS
} while (res < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
if (res < 0)
return (!async_err) ? posix_error() : NULL;
return Py_BuildValue("Ni", PyLong_FromPid(res), WAIT_STATUS_INT(status));
}
#elif defined(HAVE_CWAIT)
/* MS C has a variant of waitpid() that's usable for most purposes. */
/*[clinic input]
os.waitpid
pid: intptr_t
options: int
/
Wait for completion of a given process.
Returns a tuple of information regarding the process:
(pid, status << 8)
The options argument is ignored on Windows.
[clinic start generated code]*/
static PyObject *
os_waitpid_impl(PyObject *module, intptr_t pid, int options)
/*[clinic end generated code: output=be836b221271d538 input=40f2440c515410f8]*/
{
int status;
intptr_t res;
int async_err = 0;
do {
Py_BEGIN_ALLOW_THREADS
_Py_BEGIN_SUPPRESS_IPH
res = _cwait(&status, pid, options);
_Py_END_SUPPRESS_IPH
Py_END_ALLOW_THREADS
} while (res < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
if (res < 0)
return (!async_err) ? posix_error() : NULL;
/* shift the status left a byte so this is more like the POSIX waitpid */
return Py_BuildValue(_Py_PARSE_INTPTR "i", res, status << 8);
}
#endif
#ifdef HAVE_WAIT
/*[clinic input]
os.wait
Wait for completion of a child process.
Returns a tuple of information about the child process:
(pid, status)
[clinic start generated code]*/
static PyObject *
os_wait_impl(PyObject *module)
/*[clinic end generated code: output=6bc419ac32fb364b input=03b0182d4a4700ce]*/
{
pid_t pid;
int async_err = 0;
WAIT_TYPE status;
WAIT_STATUS_INT(status) = 0;
do {
Py_BEGIN_ALLOW_THREADS
pid = wait(&status);
Py_END_ALLOW_THREADS
} while (pid < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
if (pid < 0)
return (!async_err) ? posix_error() : NULL;
return Py_BuildValue("Ni", PyLong_FromPid(pid), WAIT_STATUS_INT(status));
}
#endif /* HAVE_WAIT */
#if defined(HAVE_READLINK) || defined(MS_WINDOWS)
PyDoc_STRVAR(readlink__doc__,
"readlink(path, *, dir_fd=None) -> path\n\n\
Return a string representing the path to which the symbolic link points.\n\
\n\
If dir_fd is not None, it should be a file descriptor open to a directory,\n\
and path should be relative; path will then be relative to that directory.\n\
dir_fd may not be implemented on your platform.\n\
If it is unavailable, using it will raise a NotImplementedError.");
#endif
/* AC 3.5: merge win32 and not together */
static PyObject *
posix_readlink(PyObject *self, PyObject *args, PyObject *kwargs)
{
path_t path;
int dir_fd = DEFAULT_DIR_FD;
char buffer[MAXPATHLEN+1];
ssize_t length;
PyObject *return_value = NULL;
static char *keywords[] = {"path", "dir_fd", NULL};
bzero(&path, sizeof(path));
path.function_name = "readlink";
if (!PyArg_ParseTupleAndKeywords(args, kwargs, "O&|$O&:readlink", keywords,
path_converter, &path,
READLINKAT_DIR_FD_CONVERTER, &dir_fd))
return NULL;
Py_BEGIN_ALLOW_THREADS
#ifdef HAVE_READLINKAT
if (dir_fd != DEFAULT_DIR_FD)
length = readlinkat(dir_fd, path.narrow, buffer, MAXPATHLEN);
else
#endif
length = readlink(path.narrow, buffer, MAXPATHLEN);
Py_END_ALLOW_THREADS
if (length < 0) {
return_value = path_error(&path);
goto exit;
}
buffer[length] = '\0';
if (PyUnicode_Check(path.object))
return_value = PyUnicode_DecodeFSDefaultAndSize(buffer, length);
else
return_value = PyBytes_FromStringAndSize(buffer, length);
exit:
path_cleanup(&path);
return return_value;
}
#ifdef HAVE_SYMLINK
#if defined(MS_WINDOWS)
/* Grab CreateSymbolicLinkW dynamically from kernel32 */
static BOOLEAN (CALLBACK *Py_CreateSymbolicLinkW)(const char16_t *, const char16_t *, DWORD) = NULL;
static int
check_CreateSymbolicLink(void)
{
HINSTANCE hKernel32;
/* only recheck */
if (Py_CreateSymbolicLinkW)
return 1;
hKernel32 = GetModuleHandleW(L"KERNEL32");
*(FARPROC*)&Py_CreateSymbolicLinkW = GetProcAddress(hKernel32,
"CreateSymbolicLinkW");
return Py_CreateSymbolicLinkW != NULL;
}
/* Remove the last portion of the path - return 0 on success */
static int
_dirnameW(WCHAR *path)
{
WCHAR *ptr;
size_t length = wcsnlen_s(path, MAX_PATH);
if (length == MAX_PATH) {
return -1;
}
/* walk the path from the end until a backslash is encountered */
for(ptr = path + length; ptr != path; ptr--) {
if (*ptr == L'\\' || *ptr == L'/') {
break;
}
}
*ptr = 0;
return 0;
}
/* Is this path absolute? */
static int
_is_absW(const WCHAR *path)
{
return path[0] == L'\\' || path[0] == L'/' ||
(path[0] && path[1] == L':');
}
/* join root and rest with a backslash - return 0 on success */
static int
_joinW(WCHAR *dest_path, const WCHAR *root, const WCHAR *rest)
{
if (_is_absW(rest)) {
return wcscpy_s(dest_path, MAX_PATH, rest);
}
if (wcscpy_s(dest_path, MAX_PATH, root)) {
return -1;
}
if (dest_path[0] && wcscat_s(dest_path, MAX_PATH, L"\\")) {
return -1;
}
return wcscat_s(dest_path, MAX_PATH, rest);
}
/* Return True if the path at src relative to dest is a directory */
static int
_check_dirW(const char16_t * src, const char16_t * dest)
{
WIN32_FILE_ATTRIBUTE_DATA src_info;
WCHAR dest_parent[MAX_PATH];
WCHAR src_resolved[MAX_PATH] = L"";
/* dest_parent = os.path.dirname(dest) */
if (wcscpy_s(dest_parent, MAX_PATH, dest) ||
_dirnameW(dest_parent)) {
return 0;
}
/* src_resolved = os.path.join(dest_parent, src) */
if (_joinW(src_resolved, dest_parent, src)) {
return 0;
}
return (
GetFileAttributesExW(src_resolved, GetFileExInfoStandard, &src_info)
&& src_info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY
);
}
#endif
/*[clinic input]
os.symlink
src: path_t
dst: path_t
target_is_directory: bool = False
*
dir_fd: dir_fd(requires='symlinkat')=None
# "symlink(src, dst, target_is_directory=False, *, dir_fd=None)\n\n\
Create a symbolic link pointing to src named dst.
target_is_directory is required on Windows if the target is to be
interpreted as a directory. (On Windows, symlink requires
Windows 6.0 or greater, and raises a NotImplementedError otherwise.)
target_is_directory is ignored on non-Windows platforms.
If dir_fd is not None, it should be a file descriptor open to a directory,
and path should be relative; path will then be relative to that directory.
dir_fd may not be implemented on your platform.
If it is unavailable, using it will raise a NotImplementedError.
[clinic start generated code]*/
static PyObject *
os_symlink_impl(PyObject *module, path_t *src, path_t *dst,
int target_is_directory, int dir_fd)
/*[clinic end generated code: output=08ca9f3f3cf960f6 input=e820ec4472547bc3]*/
{
int result;
if ((src->narrow && dst->wide) || (src->wide && dst->narrow)) {
PyErr_SetString(PyExc_ValueError,
"symlink: src and dst must be the same type");
return NULL;
}
Py_BEGIN_ALLOW_THREADS
if (dir_fd != DEFAULT_DIR_FD)
result = symlinkat(src->narrow, dir_fd, dst->narrow);
else
result = symlink(src->narrow, dst->narrow);
Py_END_ALLOW_THREADS
if (result)
return path_error2(src, dst);
Py_RETURN_NONE;
}
#endif /* HAVE_SYMLINK */
static PyStructSequence_Field times_result_fields[] = {
{"user", PyDoc_STR("user time")},
{"system", PyDoc_STR("system time")},
{"children_user", PyDoc_STR("user time of children")},
{"children_system", PyDoc_STR("system time of children")},
{"elapsed", PyDoc_STR("elapsed time since an arbitrary point in the past")},
{NULL}
};
PyDoc_STRVAR(times_result__doc__,
"times_result: Result from os.times().\n\n\
This object may be accessed either as a tuple of\n\
(user, system, children_user, children_system, elapsed),\n\
or via the attributes user, system, children_user, children_system,\n\
and elapsed.\n\
\n\
See os.times for more information.");
static PyStructSequence_Desc times_result_desc = {
"times_result", /* name */
times_result__doc__, /* doc */
times_result_fields,
5
};
static PyTypeObject TimesResultType;
#ifdef MS_WINDOWS
#define HAVE_TIMES /* mandatory, for the method table */
#endif
#ifdef HAVE_TIMES
static PyObject *
build_times_result(double user, double system,
double children_user, double children_system,
double elapsed)
{
PyObject *value = PyStructSequence_New(&TimesResultType);
if (value == NULL)
return NULL;
#define SET(i, field) \
{ \
PyObject *o = PyFloat_FromDouble(field); \
if (!o) { \
Py_DECREF(value); \
return NULL; \
} \
PyStructSequence_SET_ITEM(value, i, o); \
} \
SET(0, user);
SET(1, system);
SET(2, children_user);
SET(3, children_system);
SET(4, elapsed);
#undef SET
return value;
}
#ifndef MS_WINDOWS
#define NEED_TICKS_PER_SECOND
static long ticks_per_second = -1;
#endif /* MS_WINDOWS */
/*[clinic input]
os.times
Return a collection containing process timing information.
The object returned behaves like a named tuple with these fields:
(utime, stime, cutime, cstime, elapsed_time)
All fields are floating point numbers.
[clinic start generated code]*/
static PyObject *
os_times_impl(PyObject *module)
/*[clinic end generated code: output=35f640503557d32a input=2bf9df3d6ab2e48b]*/
#ifdef MS_WINDOWS
{
FILETIME create, exit, kernel, user;
HANDLE hProc;
hProc = GetCurrentProcess();
GetProcessTimes(hProc, &create, &exit, &kernel, &user);
/* The fields of a FILETIME structure are the hi and lo part
of a 64-bit value expressed in 100 nanosecond units.
1e7 is one second in such units; 1e-7 the inverse.
429.4967296 is 2**32 / 1e7 or 2**32 * 1e-7.
*/
return build_times_result(
(double)(user.dwHighDateTime*429.4967296 +
user.dwLowDateTime*1e-7),
(double)(kernel.dwHighDateTime*429.4967296 +
kernel.dwLowDateTime*1e-7),
(double)0,
(double)0,
(double)0);
}
#else /* MS_WINDOWS */
{
struct tms t;
clock_t c;
errno = 0;
c = times(&t);
if (c == (clock_t) -1)
return posix_error();
return build_times_result(
(double)t.tms_utime / ticks_per_second,
(double)t.tms_stime / ticks_per_second,
(double)t.tms_cutime / ticks_per_second,
(double)t.tms_cstime / ticks_per_second,
(double)c / ticks_per_second);
}
#endif /* MS_WINDOWS */
#endif /* HAVE_TIMES */
#ifdef HAVE_GETSID
/*[clinic input]
os.getsid
pid: pid_t
/
Call the system call getsid(pid) and return the result.
[clinic start generated code]*/
static PyObject *
os_getsid_impl(PyObject *module, pid_t pid)
/*[clinic end generated code: output=112deae56b306460 input=eeb2b923a30ce04e]*/
{
int sid;
sid = getsid(pid);
if (sid < 0)
return posix_error();
return PyLong_FromLong((long)sid);
}
#endif /* HAVE_GETSID */
#ifdef HAVE_SETSID
/*[clinic input]
os.setsid
Call the system call setsid().
[clinic start generated code]*/
static PyObject *
os_setsid_impl(PyObject *module)
/*[clinic end generated code: output=e2ddedd517086d77 input=5fff45858e2f0776]*/
{
if (setsid() < 0)
return posix_error();
Py_RETURN_NONE;
}
#endif /* HAVE_SETSID */
#ifdef HAVE_SETPGID
/*[clinic input]
os.setpgid
pid: pid_t
pgrp: pid_t
/
Call the system call setpgid(pid, pgrp).
[clinic start generated code]*/
static PyObject *
os_setpgid_impl(PyObject *module, pid_t pid, pid_t pgrp)
/*[clinic end generated code: output=6461160319a43d6a input=fceb395eca572e1a]*/
{
if (setpgid(pid, pgrp) < 0)
return posix_error();
Py_RETURN_NONE;
}
#endif /* HAVE_SETPGID */
#ifdef HAVE_TCGETPGRP
/*[clinic input]
os.tcgetpgrp
fd: int
/
Return the process group associated with the terminal specified by fd.
[clinic start generated code]*/
static PyObject *
os_tcgetpgrp_impl(PyObject *module, int fd)
/*[clinic end generated code: output=f865e88be86c272b input=7f6c18eac10ada86]*/
{
pid_t pgid = tcgetpgrp(fd);
if (pgid < 0)
return posix_error();
return PyLong_FromPid(pgid);
}
#endif /* HAVE_TCGETPGRP */
#ifdef HAVE_TCSETPGRP
/*[clinic input]
os.tcsetpgrp
fd: int
pgid: pid_t
/
Set the process group associated with the terminal specified by fd.
[clinic start generated code]*/
static PyObject *
os_tcsetpgrp_impl(PyObject *module, int fd, pid_t pgid)
/*[clinic end generated code: output=f1821a381b9daa39 input=5bdc997c6a619020]*/
{
if (tcsetpgrp(fd, pgid) < 0)
return posix_error();
Py_RETURN_NONE;
}
#endif /* HAVE_TCSETPGRP */
/* Functions acting on file descriptors */
#ifdef O_CLOEXEC
extern int _Py_open_cloexec_works;
#endif
/*[clinic input]
os.open -> int
path: path_t
flags: int
mode: int = 0o777
*
dir_fd: dir_fd(requires='openat') = None
# "open(path, flags, mode=0o777, *, dir_fd=None)\n\n\
Open a file for low level IO. Returns a file descriptor (integer).
If dir_fd is not None, it should be a file descriptor open to a directory,
and path should be relative; path will then be relative to that directory.
dir_fd may not be implemented on your platform.
If it is unavailable, using it will raise a NotImplementedError.
[clinic start generated code]*/
static int
os_open_impl(PyObject *module, path_t *path, int flags, int mode, int dir_fd)
/*[clinic end generated code: output=abc7227888c8bc73 input=ad8623b29acd2934]*/
{
int fd;
int async_err = 0;
#ifdef O_CLOEXEC
int *atomic_flag_works = &_Py_open_cloexec_works;
#elif !defined(MS_WINDOWS)
int *atomic_flag_works = NULL;
#endif
#ifdef MS_WINDOWS
flags |= O_NOINHERIT;
#elif defined(O_CLOEXEC)
flags |= O_CLOEXEC;
#endif
_Py_BEGIN_SUPPRESS_IPH
do {
Py_BEGIN_ALLOW_THREADS
#ifdef MS_WINDOWS
fd = _wopen(path->wide, flags, mode);
#else
#ifdef HAVE_OPENAT
if (dir_fd != DEFAULT_DIR_FD)
fd = openat(dir_fd, path->narrow, flags, mode);
else
#endif /* HAVE_OPENAT */
fd = open(path->narrow, flags, mode);
#endif /* !MS_WINDOWS */
Py_END_ALLOW_THREADS
} while (fd < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
_Py_END_SUPPRESS_IPH
if (fd < 0) {
if (!async_err)
PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, path->object);
return -1;
}
#ifndef MS_WINDOWS
if (_Py_set_inheritable(fd, 0, atomic_flag_works) < 0) {
close(fd);
return -1;
}
#endif
return fd;
}
/*[clinic input]
os.close
fd: int
Close a file descriptor.
[clinic start generated code]*/
static PyObject *
os_close_impl(PyObject *module, int fd)
/*[clinic end generated code: output=2fe4e93602822c14 input=2bc42451ca5c3223]*/
{
int res;
/* We do not want to retry upon EINTR: see http://lwn.net/Articles/576478/
* and http://linux.derkeiler.com/Mailing-Lists/Kernel/2005-09/3000.html
* for more details.
*/
Py_BEGIN_ALLOW_THREADS
_Py_BEGIN_SUPPRESS_IPH
res = close(fd);
_Py_END_SUPPRESS_IPH
Py_END_ALLOW_THREADS
if (res < 0)
return posix_error();
Py_RETURN_NONE;
}
/*[clinic input]
os.closerange
fd_low: int
fd_high: int
/
Closes all file descriptors in [fd_low, fd_high), ignoring errors.
[clinic start generated code]*/
static PyObject *
os_closerange_impl(PyObject *module, int fd_low, int fd_high)
/*[clinic end generated code: output=0ce5c20fcda681c2 input=5855a3d053ebd4ec]*/
{
int i;
Py_BEGIN_ALLOW_THREADS
_Py_BEGIN_SUPPRESS_IPH
for (i = Py_MAX(fd_low, 0); i < fd_high; i++)
close(i);
_Py_END_SUPPRESS_IPH
Py_END_ALLOW_THREADS
Py_RETURN_NONE;
}
/*[clinic input]
os.dup -> int
fd: int
/
Return a duplicate of a file descriptor.
[clinic start generated code]*/
static int
os_dup_impl(PyObject *module, int fd)
/*[clinic end generated code: output=486f4860636b2a9f input=6f10f7ea97f7852a]*/
{
return _Py_dup(fd);
}
/*[clinic input]
os.dup2
fd: int
fd2: int
inheritable: bool=True
Duplicate file descriptor.
[clinic start generated code]*/
static PyObject *
os_dup2_impl(PyObject *module, int fd, int fd2, int inheritable)
/*[clinic end generated code: output=db832a2d872ccc5f input=76e96f511be0352f]*/
{
int res;
if (fd < 0 || fd2 < 0)
return posix_error();
/* dup2() can fail with EINTR if the target FD is already open, because it
* then has to be closed. See os_close_impl() for why we don't handle EINTR
* upon close(), and therefore below.
*/
#ifdef MS_WINDOWS
Py_BEGIN_ALLOW_THREADS
_Py_BEGIN_SUPPRESS_IPH
res = dup2(fd, fd2);
_Py_END_SUPPRESS_IPH
Py_END_ALLOW_THREADS
if (res < 0)
return posix_error();
/* Character files like console cannot be make non-inheritable */
if (!inheritable && _Py_set_inheritable(fd2, 0, NULL) < 0) {
close(fd2);
return NULL;
}
#elif defined(F_DUP2FD_CLOEXEC)
Py_BEGIN_ALLOW_THREADS
if (!inheritable)
res = fcntl(fd, F_DUP2FD_CLOEXEC, fd2);
else
res = dup2(fd, fd2);
Py_END_ALLOW_THREADS
if (res < 0)
return posix_error();
#else
if (!inheritable) {
Py_BEGIN_ALLOW_THREADS
res = dup3(fd, fd2, O_CLOEXEC);
Py_END_ALLOW_THREADS
if (res < 0)
return posix_error();
}
if (inheritable)
{
Py_BEGIN_ALLOW_THREADS
res = dup2(fd, fd2);
Py_END_ALLOW_THREADS
if (res < 0)
return posix_error();
if (!inheritable && _Py_set_inheritable(fd2, 0, NULL) < 0) {
close(fd2);
return NULL;
}
}
#endif
Py_RETURN_NONE;
}
#ifdef HAVE_LOCKF
/*[clinic input]
os.lockf
fd: int
An open file descriptor.
command: int
One of F_LOCK, F_TLOCK, F_ULOCK or F_TEST.
length: Py_off_t
The number of bytes to lock, starting at the current position.
/
Apply, test or remove a POSIX lock on an open file descriptor.
[clinic start generated code]*/
static PyObject *
os_lockf_impl(PyObject *module, int fd, int command, Py_off_t length)
/*[clinic end generated code: output=af7051f3e7c29651 input=65da41d2106e9b79]*/
{
int res;
Py_BEGIN_ALLOW_THREADS
res = lockf(fd, command, length);
Py_END_ALLOW_THREADS
if (res < 0)
return posix_error();
Py_RETURN_NONE;
}
#endif /* HAVE_LOCKF */
/*[clinic input]
os.lseek -> Py_off_t
fd: int
position: Py_off_t
how: int
/
Set the position of a file descriptor. Return the new position.
Return the new cursor position in number of bytes
relative to the beginning of the file.
[clinic start generated code]*/
static Py_off_t
os_lseek_impl(PyObject *module, int fd, Py_off_t position, int how)
/*[clinic end generated code: output=971e1efb6b30bd2f input=902654ad3f96a6d3]*/
{
Py_off_t result;
#ifdef SEEK_SET
/* Turn 0, 1, 2 into SEEK_{SET,CUR,END} */
switch (how) {
case 0: how = SEEK_SET; break;
case 1: how = SEEK_CUR; break;
case 2: how = SEEK_END; break;
}
#endif /* SEEK_END */
if (PyErr_Occurred())
return -1;
Py_BEGIN_ALLOW_THREADS
_Py_BEGIN_SUPPRESS_IPH
#ifdef MS_WINDOWS
result = _lseeki64(fd, position, how);
#else
result = lseek(fd, position, how);
#endif
_Py_END_SUPPRESS_IPH
Py_END_ALLOW_THREADS
if (result < 0)
posix_error();
return result;
}
/*[clinic input]
os.read
fd: int
length: Py_ssize_t
/
Read from a file descriptor. Returns a bytes object.
[clinic start generated code]*/
static PyObject *
os_read_impl(PyObject *module, int fd, Py_ssize_t length)
/*[clinic end generated code: output=dafbe9a5cddb987b input=1df2eaa27c0bf1d3]*/
{
Py_ssize_t n;
PyObject *buffer;
if (length < 0) {
errno = EINVAL;
return posix_error();
}
length = Py_MIN(length, _PY_READ_MAX);
buffer = PyBytes_FromStringAndSize((char *)NULL, length);
if (buffer == NULL)
return NULL;
n = _Py_read(fd, PyBytes_AS_STRING(buffer), length);
if (n == -1) {
Py_DECREF(buffer);
return NULL;
}
if (n != length)
_PyBytes_Resize(&buffer, n);
return buffer;
}
#if (defined(HAVE_SENDFILE) && (defined(__FreeBSD__) || defined(__DragonFly__) \
|| defined(__APPLE__))) || defined(HAVE_READV) || defined(HAVE_WRITEV)
static int
iov_setup(struct iovec **iov, Py_buffer **buf, PyObject *seq, Py_ssize_t cnt, int type)
{
Py_ssize_t i, j;
*iov = PyMem_New(struct iovec, cnt);
if (*iov == NULL) {
PyErr_NoMemory();
return -1;
}
*buf = PyMem_New(Py_buffer, cnt);
if (*buf == NULL) {
PyMem_Del(*iov);
PyErr_NoMemory();
return -1;
}
for (i = 0; i < cnt; i++) {
PyObject *item = PySequence_GetItem(seq, i);
if (item == NULL)
goto fail;
if (PyObject_GetBuffer(item, &(*buf)[i], type) == -1) {
Py_DECREF(item);
goto fail;
}
Py_DECREF(item);
(*iov)[i].iov_base = (*buf)[i].buf;
(*iov)[i].iov_len = (*buf)[i].len;
}
return 0;
fail:
PyMem_Del(*iov);
for (j = 0; j < i; j++) {
PyBuffer_Release(&(*buf)[j]);
}
PyMem_Del(*buf);
return -1;
}
static void
iov_cleanup(struct iovec *iov, Py_buffer *buf, int cnt)
{
int i;
PyMem_Del(iov);
for (i = 0; i < cnt; i++) {
PyBuffer_Release(&buf[i]);
}
PyMem_Del(buf);
}
#endif
#ifdef HAVE_READV
/*[clinic input]
os.readv -> Py_ssize_t
fd: int
buffers: object
/
Read from a file descriptor fd into an iterable of buffers.
The buffers should be mutable buffers accepting bytes.
readv will transfer data into each buffer until it is full
and then move on to the next buffer in the sequence to hold
the rest of the data.
readv returns the total number of bytes read,
which may be less than the total capacity of all the buffers.
[clinic start generated code]*/
static Py_ssize_t
os_readv_impl(PyObject *module, int fd, PyObject *buffers)
/*[clinic end generated code: output=792da062d3fcebdb input=e679eb5dbfa0357d]*/
{
Py_ssize_t cnt, n;
int async_err = 0;
struct iovec *iov;
Py_buffer *buf;
if (!PySequence_Check(buffers)) {
PyErr_SetString(PyExc_TypeError,
"readv() arg 2 must be a sequence");
return -1;
}
cnt = PySequence_Size(buffers);
if (cnt < 0)
return -1;
if (iov_setup(&iov, &buf, buffers, cnt, PyBUF_WRITABLE) < 0)
return -1;
do {
Py_BEGIN_ALLOW_THREADS
n = readv(fd, iov, cnt);
Py_END_ALLOW_THREADS
} while (n < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
iov_cleanup(iov, buf, cnt);
if (n < 0) {
if (!async_err)
posix_error();
return -1;
}
return n;
}
#endif /* HAVE_READV */
#ifdef HAVE_PREAD
/*[clinic input]
# TODO length should be size_t! but Python doesn't support parsing size_t yet.
os.pread
fd: int
length: int
offset: Py_off_t
/
Read a number of bytes from a file descriptor starting at a particular offset.
Read length bytes from file descriptor fd, starting at offset bytes from
the beginning of the file. The file offset remains unchanged.
[clinic start generated code]*/
static PyObject *
os_pread_impl(PyObject *module, int fd, int length, Py_off_t offset)
/*[clinic end generated code: output=435b29ee32b54a78 input=084948dcbaa35d4c]*/
{
Py_ssize_t n;
int async_err = 0;
PyObject *buffer;
if (length < 0) {
errno = EINVAL;
return posix_error();
}
buffer = PyBytes_FromStringAndSize((char *)NULL, length);
if (buffer == NULL)
return NULL;
do {
Py_BEGIN_ALLOW_THREADS
_Py_BEGIN_SUPPRESS_IPH
n = pread(fd, PyBytes_AS_STRING(buffer), length, offset);
_Py_END_SUPPRESS_IPH
Py_END_ALLOW_THREADS
} while (n < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
if (n < 0) {
Py_DECREF(buffer);
return (!async_err) ? posix_error() : NULL;
}
if (n != length)
_PyBytes_Resize(&buffer, n);
return buffer;
}
#endif /* HAVE_PREAD */
/*[clinic input]
os.write -> Py_ssize_t
fd: int
data: Py_buffer
/
Write a bytes object to a file descriptor.
[clinic start generated code]*/
static Py_ssize_t
os_write_impl(PyObject *module, int fd, Py_buffer *data)
/*[clinic end generated code: output=e4ef5bc904b58ef9 input=3207e28963234f3c]*/
{
return _Py_write(fd, data->buf, data->len);
}
#ifdef HAVE_SENDFILE
PyDoc_STRVAR(posix_sendfile__doc__,
"sendfile(out, in, offset, count) -> byteswritten\n\
sendfile(out, in, offset, count[, headers][, trailers], flags=0)\n\
-> byteswritten\n\
Copy count bytes from file descriptor in to file descriptor out.");
/* AC 3.5: don't bother converting, has optional group*/
static PyObject *
posix_sendfile(PyObject *self, PyObject *args, PyObject *kwdict)
{
int in, out;
Py_ssize_t ret;
int async_err = 0;
off_t offset;
if (IsFreebsd() || IsXnu()) {
Py_ssize_t len;
PyObject *headers = NULL, *trailers = NULL;
Py_buffer *hbuf, *tbuf;
off_t sbytes;
struct sf_hdtr sf;
int flags = 0;
/* Beware that "in" clashes with Python's own "in" operator keyword */
static char *keywords[] = {"out", "in",
"offset", "count",
"headers", "trailers", "flags", NULL};
sf.headers = NULL;
sf.trailers = NULL;
if (IsXnu()) {
if (!PyArg_ParseTupleAndKeywords(args, kwdict, "iiO&O&|OOi:sendfile",
keywords, &out, &in, Py_off_t_converter, &offset, Py_off_t_converter, &sbytes,
&headers, &trailers, &flags))
return NULL;
} else {
if (!PyArg_ParseTupleAndKeywords(args, kwdict, "iiO&n|OOi:sendfile",
keywords, &out, &in, Py_off_t_converter, &offset, &len,
&headers, &trailers, &flags))
return NULL;
}
if (headers != NULL) {
if (!PySequence_Check(headers)) {
PyErr_SetString(PyExc_TypeError,
"sendfile() headers must be a sequence");
return NULL;
} else {
Py_ssize_t i = PySequence_Size(headers);
if (i < 0)
return NULL;
if (i > INT_MAX) {
PyErr_SetString(PyExc_OverflowError,
"sendfile() header is too large");
return NULL;
}
if (i > 0) {
sf.hdr_cnt = (int)i;
if (iov_setup(&(sf.headers), &hbuf,
headers, sf.hdr_cnt, PyBUF_SIMPLE) < 0)
return NULL;
if (IsXnu()) {
for (i = 0; i < sf.hdr_cnt; i++) {
Py_ssize_t blen = sf.headers[i].iov_len;
if (sbytes >= 0x7fffffffffffffff - blen) {
PyErr_SetString(PyExc_OverflowError,
"sendfile() header is too large");
return NULL;
}
sbytes += blen;
}
}
}
}
}
if (trailers != NULL) {
if (!PySequence_Check(trailers)) {
PyErr_SetString(PyExc_TypeError,
"sendfile() trailers must be a sequence");
return NULL;
} else {
Py_ssize_t i = PySequence_Size(trailers);
if (i < 0)
return NULL;
if (i > INT_MAX) {
PyErr_SetString(PyExc_OverflowError,
"sendfile() trailer is too large");
return NULL;
}
if (i > 0) {
sf.trl_cnt = (int)i;
if (iov_setup(&(sf.trailers), &tbuf,
trailers, sf.trl_cnt, PyBUF_SIMPLE) < 0)
return NULL;
}
}
}
_Py_BEGIN_SUPPRESS_IPH
do {
Py_BEGIN_ALLOW_THREADS
if (IsXnu()) {
ret = sys_sendfile_xnu(in, out, offset, &sbytes, &sf, flags);
} else {
ret = sys_sendfile_freebsd(in, out, offset, len, &sf, &sbytes, flags);
}
Py_END_ALLOW_THREADS
} while (ret < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
_Py_END_SUPPRESS_IPH
if (sf.headers != NULL)
iov_cleanup(sf.headers, hbuf, sf.hdr_cnt);
if (sf.trailers != NULL)
iov_cleanup(sf.trailers, tbuf, sf.trl_cnt);
if (ret < 0) {
if ((errno == EAGAIN) || (errno == EBUSY)) {
if (sbytes != 0) {
// some data has been sent
goto done;
}
else {
// no data has been sent; upper application is supposed
// to retry on EAGAIN or EBUSY
return posix_error();
}
}
return (!async_err) ? posix_error() : NULL;
}
goto done;
done:
#if !defined(HAVE_LARGEFILE_SUPPORT)
return Py_BuildValue("l", sbytes);
#else
return Py_BuildValue("L", sbytes);
#endif
} else {
Py_ssize_t count;
PyObject *offobj;
static char *keywords[] = {"out", "in",
"offset", "count", NULL};
if (!PyArg_ParseTupleAndKeywords(args, kwdict, "iiOn:sendfile",
keywords, &out, &in, &offobj, &count))
return NULL;
if (IsLinux()) {
if (offobj == Py_None) {
do {
Py_BEGIN_ALLOW_THREADS
ret = sys_sendfile(out, in, NULL, count);
Py_END_ALLOW_THREADS
} while (ret < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
if (ret < 0)
return (!async_err) ? posix_error() : NULL;
return Py_BuildValue("n", ret);
}
}
if (!Py_off_t_converter(offobj, &offset))
return NULL;
do {
Py_BEGIN_ALLOW_THREADS
ret = sendfile(out, in, &offset, count);
Py_END_ALLOW_THREADS
} while (ret < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
if (ret < 0)
return (!async_err) ? posix_error() : NULL;
return Py_BuildValue("n", ret);
}
}
#endif /* HAVE_SENDFILE */
/*[clinic input]
os.fstat
fd : int
Perform a stat system call on the given file descriptor.
Like stat(), but for an open file descriptor.
Equivalent to os.stat(fd).
[clinic start generated code]*/
static PyObject *
os_fstat_impl(PyObject *module, int fd)
/*[clinic end generated code: output=efc038cb5f654492 input=27e0e0ebbe5600c9]*/
{
STRUCT_STAT st;
int res;
int async_err = 0;
do {
Py_BEGIN_ALLOW_THREADS
res = FSTAT(fd, &st);
Py_END_ALLOW_THREADS
} while (res != 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
if (res != 0) {
#ifdef MS_WINDOWS
return PyErr_SetFromWindowsErr(0);
#else
return (!async_err) ? posix_error() : NULL;
#endif
}
return _pystat_fromstructstat(&st);
}
/*[clinic input]
os.isatty -> bool
fd: int
/
Return True if the fd is connected to a terminal.
Return True if the file descriptor is an open file descriptor
connected to the slave end of a terminal.
[clinic start generated code]*/
static int
os_isatty_impl(PyObject *module, int fd)
/*[clinic end generated code: output=6a48c8b4e644ca00 input=08ce94aa1eaf7b5e]*/
{
int return_value;
_Py_BEGIN_SUPPRESS_IPH
return_value = isatty(fd);
_Py_END_SUPPRESS_IPH
return return_value;
}
#ifdef HAVE_PIPE
/*[clinic input]
os.pipe
Create a pipe.
Returns a tuple of two file descriptors:
(read_fd, write_fd)
[clinic start generated code]*/
static PyObject *
os_pipe_impl(PyObject *module)
/*[clinic end generated code: output=ff9b76255793b440 input=02535e8c8fa6c4d4]*/
{
int fds[2];
int res;
Py_BEGIN_ALLOW_THREADS
res = pipe2(fds, O_CLOEXEC);
Py_END_ALLOW_THREADS
if (res != 0 && errno == ENOSYS)
{
Py_BEGIN_ALLOW_THREADS
res = pipe(fds);
Py_END_ALLOW_THREADS
if (res == 0) {
if (_Py_set_inheritable(fds[0], 0, NULL) < 0) {
close(fds[0]);
close(fds[1]);
return NULL;
}
if (_Py_set_inheritable(fds[1], 0, NULL) < 0) {
close(fds[0]);
close(fds[1]);
return NULL;
}
}
}
if (res != 0)
return PyErr_SetFromErrno(PyExc_OSError);
return Py_BuildValue("(ii)", fds[0], fds[1]);
}
#endif /* HAVE_PIPE */
#ifdef HAVE_PIPE2
/*[clinic input]
os.pipe2
flags: int
/
Create a pipe with flags set atomically.
Returns a tuple of two file descriptors:
(read_fd, write_fd)
flags can be constructed by ORing together one or more of these values:
O_NONBLOCK, O_CLOEXEC.
[clinic start generated code]*/
static PyObject *
os_pipe2_impl(PyObject *module, int flags)
/*[clinic end generated code: output=25751fb43a45540f input=f261b6e7e63c6817]*/
{
int fds[2];
int res;
res = pipe2(fds, flags);
if (res != 0)
return posix_error();
return Py_BuildValue("(ii)", fds[0], fds[1]);
}
#endif /* HAVE_PIPE2 */
#ifdef HAVE_WRITEV
/*[clinic input]
os.writev -> Py_ssize_t
fd: int
buffers: object
/
Iterate over buffers, and write the contents of each to a file descriptor.
Returns the total number of bytes written.
buffers must be a sequence of bytes-like objects.
[clinic start generated code]*/
static Py_ssize_t
os_writev_impl(PyObject *module, int fd, PyObject *buffers)
/*[clinic end generated code: output=56565cfac3aac15b input=5b8d17fe4189d2fe]*/
{
Py_ssize_t cnt;
Py_ssize_t result;
int async_err = 0;
struct iovec *iov;
Py_buffer *buf;
if (!PySequence_Check(buffers)) {
PyErr_SetString(PyExc_TypeError,
"writev() arg 2 must be a sequence");
return -1;
}
cnt = PySequence_Size(buffers);
if (cnt < 0)
return -1;
if (iov_setup(&iov, &buf, buffers, cnt, PyBUF_SIMPLE) < 0) {
return -1;
}
do {
Py_BEGIN_ALLOW_THREADS
result = writev(fd, iov, cnt);
Py_END_ALLOW_THREADS
} while (result < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
iov_cleanup(iov, buf, cnt);
if (result < 0 && !async_err)
posix_error();
return result;
}
#endif /* HAVE_WRITEV */
#ifdef HAVE_PWRITE
/*[clinic input]
os.pwrite -> Py_ssize_t
fd: int
buffer: Py_buffer
offset: Py_off_t
/
Write bytes to a file descriptor starting at a particular offset.
Write buffer to fd, starting at offset bytes from the beginning of
the file. Returns the number of bytes writte. Does not change the
current file offset.
[clinic start generated code]*/
static Py_ssize_t
os_pwrite_impl(PyObject *module, int fd, Py_buffer *buffer, Py_off_t offset)
/*[clinic end generated code: output=c74da630758ee925 input=19903f1b3dd26377]*/
{
Py_ssize_t size;
int async_err = 0;
do {
Py_BEGIN_ALLOW_THREADS
_Py_BEGIN_SUPPRESS_IPH
size = pwrite(fd, buffer->buf, (size_t)buffer->len, offset);
_Py_END_SUPPRESS_IPH
Py_END_ALLOW_THREADS
} while (size < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
if (size < 0 && !async_err)
posix_error();
return size;
}
#endif /* HAVE_PWRITE */
#ifdef HAVE_MKFIFO
/*[clinic input]
os.mkfifo
path: path_t
mode: int=0o666
*
dir_fd: dir_fd(requires='mkfifoat')=None
Create a "fifo" (a POSIX named pipe).
If dir_fd is not None, it should be a file descriptor open to a directory,
and path should be relative; path will then be relative to that directory.
dir_fd may not be implemented on your platform.
If it is unavailable, using it will raise a NotImplementedError.
[clinic start generated code]*/
static PyObject *
os_mkfifo_impl(PyObject *module, path_t *path, int mode, int dir_fd)
/*[clinic end generated code: output=ce41cfad0e68c940 input=73032e98a36e0e19]*/
{
int result;
int async_err = 0;
do {
Py_BEGIN_ALLOW_THREADS
if (dir_fd != DEFAULT_DIR_FD) {
result = mkfifoat(dir_fd, path->narrow, mode);
if (result == -1 && result == ENOSYS)
result = mkfifo(path->narrow, mode);
} else {
result = mkfifo(path->narrow, mode);
}
Py_END_ALLOW_THREADS
} while (result != 0 && errno == EINTR &&
!(async_err = PyErr_CheckSignals()));
if (result != 0)
return (!async_err) ? posix_error() : NULL;
Py_RETURN_NONE;
}
#endif /* HAVE_MKFIFO */
#if defined(HAVE_MKNOD) && defined(HAVE_MAKEDEV)
/*[clinic input]
os.mknod
path: path_t
mode: int=0o600
device: dev_t=0
*
dir_fd: dir_fd(requires='mknodat')=None
Create a node in the file system.
Create a node in the file system (file, device special file or named pipe)
at path. mode specifies both the permissions to use and the
type of node to be created, being combined (bitwise OR) with one of
S_IFREG, S_IFCHR, S_IFBLK, and S_IFIFO. If S_IFCHR or S_IFBLK is set on mode,
device defines the newly created device special file (probably using
os.makedev()). Otherwise device is ignored.
If dir_fd is not None, it should be a file descriptor open to a directory,
and path should be relative; path will then be relative to that directory.
dir_fd may not be implemented on your platform.
If it is unavailable, using it will raise a NotImplementedError.
[clinic start generated code]*/
static PyObject *
os_mknod_impl(PyObject *module, path_t *path, int mode, dev_t device,
int dir_fd)
/*[clinic end generated code: output=92e55d3ca8917461 input=ee44531551a4d83b]*/
{
int result;
int async_err = 0;
do {
Py_BEGIN_ALLOW_THREADS
if (dir_fd != DEFAULT_DIR_FD) {
result = mknodat(dir_fd, path->narrow, mode, device);
if (result == -1 && result == ENOSYS)
result = mknod(path->narrow, mode, device);
} else
result = mknod(path->narrow, mode, device);
Py_END_ALLOW_THREADS
} while (result != 0 && errno == EINTR &&
!(async_err = PyErr_CheckSignals()));
if (result != 0)
return (!async_err) ? posix_error() : NULL;
Py_RETURN_NONE;
}
#endif /* defined(HAVE_MKNOD) && defined(HAVE_MAKEDEV) */
#ifdef HAVE_DEVICE_MACROS
/*[clinic input]
os.major -> unsigned_int
device: dev_t
/
Extracts a device major number from a raw device number.
[clinic start generated code]*/
static unsigned int
os_major_impl(PyObject *module, dev_t device)
/*[clinic end generated code: output=5b3b2589bafb498e input=1e16a4d30c4d4462]*/
{
return major(device);
}
/*[clinic input]
os.minor -> unsigned_int
device: dev_t
/
Extracts a device minor number from a raw device number.
[clinic start generated code]*/
static unsigned int
os_minor_impl(PyObject *module, dev_t device)
/*[clinic end generated code: output=5e1a25e630b0157d input=0842c6d23f24c65e]*/
{
return minor(device);
}
/*[clinic input]
os.makedev -> dev_t
major: int
minor: int
/
Composes a raw device number from the major and minor device numbers.
[clinic start generated code]*/
static dev_t
os_makedev_impl(PyObject *module, int major, int minor)
/*[clinic end generated code: output=881aaa4aba6f6a52 input=4b9fd8fc73cbe48f]*/
{
return makedev(major, minor);
}
#endif /* HAVE_DEVICE_MACROS */
#if defined HAVE_FTRUNCATE || defined MS_WINDOWS
/*[clinic input]
os.ftruncate
fd: int
length: Py_off_t
/
Truncate a file, specified by file descriptor, to a specific length.
[clinic start generated code]*/
static PyObject *
os_ftruncate_impl(PyObject *module, int fd, Py_off_t length)
/*[clinic end generated code: output=fba15523721be7e4 input=63b43641e52818f2]*/
{
int result;
int async_err = 0;
do {
Py_BEGIN_ALLOW_THREADS
_Py_BEGIN_SUPPRESS_IPH
result = ftruncate(fd, length);
_Py_END_SUPPRESS_IPH
Py_END_ALLOW_THREADS
} while (result != 0 && errno == EINTR &&
!(async_err = PyErr_CheckSignals()));
if (result != 0)
return (!async_err) ? posix_error() : NULL;
Py_RETURN_NONE;
}
#endif /* HAVE_FTRUNCATE || MS_WINDOWS */
#if defined HAVE_TRUNCATE || defined MS_WINDOWS
/*[clinic input]
os.truncate
path: path_t(allow_fd='PATH_HAVE_FTRUNCATE')
length: Py_off_t
Truncate a file, specified by path, to a specific length.
On some platforms, path may also be specified as an open file descriptor.
If this functionality is unavailable, using it raises an exception.
[clinic start generated code]*/
static PyObject *
os_truncate_impl(PyObject *module, path_t *path, Py_off_t length)
/*[clinic end generated code: output=43009c8df5c0a12b input=77229cf0b50a9b77]*/
{
int result;
if (path->fd != -1)
return os_ftruncate_impl(module, path->fd, length);
Py_BEGIN_ALLOW_THREADS
_Py_BEGIN_SUPPRESS_IPH
result = truncate(path->narrow, length);
_Py_END_SUPPRESS_IPH
Py_END_ALLOW_THREADS
if (result < 0)
return posix_path_error(path);
Py_RETURN_NONE;
}
#endif /* HAVE_TRUNCATE || MS_WINDOWS */
/* Issue #22396: On 32-bit AIX platform, the prototypes of os.posix_fadvise()
and os.posix_fallocate() in system headers are wrong if _LARGE_FILES is
defined, which is the case in Python on AIX. AIX bug report:
http://www-01.ibm.com/support/docview.wss?uid=isg1IV56170 */
#if defined(_AIX) && defined(_LARGE_FILES) && !defined(__64BIT__)
# define POSIX_FADVISE_AIX_BUG
#endif
#if defined(HAVE_POSIX_FALLOCATE) && !defined(POSIX_FADVISE_AIX_BUG)
/*[clinic input]
os.posix_fallocate
fd: int
offset: Py_off_t
length: Py_off_t
/
Ensure a file has allocated at least a particular number of bytes on disk.
Ensure that the file specified by fd encompasses a range of bytes
starting at offset bytes from the beginning and continuing for length bytes.
[clinic start generated code]*/
static PyObject *
os_posix_fallocate_impl(PyObject *module, int fd, Py_off_t offset,
Py_off_t length)
/*[clinic end generated code: output=73f107139564aa9d input=d7a2ef0ab2ca52fb]*/
{
int result;
int async_err = 0;
do {
Py_BEGIN_ALLOW_THREADS
result = posix_fallocate(fd, offset, length);
Py_END_ALLOW_THREADS
} while (result == EINTR && !(async_err = PyErr_CheckSignals()));
if (result == 0)
Py_RETURN_NONE;
if (async_err)
return NULL;
errno = result;
return posix_error();
}
#endif /* HAVE_POSIX_FALLOCATE) && !POSIX_FADVISE_AIX_BUG */
#if defined(HAVE_POSIX_FADVISE) && !defined(POSIX_FADVISE_AIX_BUG)
/*[clinic input]
os.posix_fadvise
fd: int
offset: Py_off_t
length: Py_off_t
advice: int
/
Announce an intention to access data in a specific pattern.
Announce an intention to access data in a specific pattern, thus allowing
the kernel to make optimizations.
The advice applies to the region of the file specified by fd starting at
offset and continuing for length bytes.
advice is one of POSIX_FADV_NORMAL, POSIX_FADV_SEQUENTIAL,
POSIX_FADV_RANDOM, POSIX_FADV_NOREUSE, POSIX_FADV_WILLNEED, or
POSIX_FADV_DONTNEED.
[clinic start generated code]*/
static PyObject *
os_posix_fadvise_impl(PyObject *module, int fd, Py_off_t offset,
Py_off_t length, int advice)
/*[clinic end generated code: output=412ef4aa70c98642 input=0fbe554edc2f04b5]*/
{
int result;
int async_err = 0;
do {
Py_BEGIN_ALLOW_THREADS
result = posix_fadvise(fd, offset, length, advice);
Py_END_ALLOW_THREADS
} while (result == EINTR && !(async_err = PyErr_CheckSignals()));
if (result == 0)
Py_RETURN_NONE;
if (async_err)
return NULL;
errno = result;
return posix_error();
}
#endif /* HAVE_POSIX_FADVISE && !POSIX_FADVISE_AIX_BUG */
#ifdef HAVE_PUTENV
/* Save putenv() parameters as values here, so we can collect them when they
* get re-set with another call for the same key. */
static PyObject *posix_putenv_garbage;
static void
posix_putenv_garbage_setitem(PyObject *name, PyObject *value)
{
/* Install the first arg and newstr in posix_putenv_garbage;
* this will cause previous value to be collected. This has to
* happen after the real putenv() call because the old value
* was still accessible until then. */
if (PyDict_SetItem(posix_putenv_garbage, name, value))
/* really not much we can do; just leak */
PyErr_Clear();
else
Py_DECREF(value);
}
#ifdef MS_WINDOWS
/*[clinic input]
os.putenv
name: unicode
value: unicode
/
Change or add an environment variable.
[clinic start generated code]*/
static PyObject *
os_putenv_impl(PyObject *module, PyObject *name, PyObject *value)
/*[clinic end generated code: output=d29a567d6b2327d2 input=ba586581c2e6105f]*/
{
const wchar_t *env;
Py_ssize_t size;
/* Search from index 1 because on Windows starting '=' is allowed for
defining hidden environment variables. */
if (PyUnicode_GET_LENGTH(name) == 0 ||
PyUnicode_FindChar(name, '=', 1, PyUnicode_GET_LENGTH(name), 1) != -1)
{
PyErr_SetString(PyExc_ValueError, "illegal environment variable name");
return NULL;
}
PyObject *unicode = PyUnicode_FromFormat("%U=%U", name, value);
if (unicode == NULL) {
return NULL;
}
env = PyUnicode_AsUnicodeAndSize(unicode, &size);
if (env == NULL)
goto error;
if (size > _MAX_ENV) {
PyErr_Format(PyExc_ValueError,
"the environment variable is longer than %u characters",
_MAX_ENV);
goto error;
}
if (wcslen(env) != (size_t)size) {
PyErr_SetString(PyExc_ValueError, "embedded null character");
goto error;
}
if (_wputenv(env)) {
posix_error();
goto error;
}
posix_putenv_garbage_setitem(name, unicode);
Py_RETURN_NONE;
error:
Py_DECREF(unicode);
return NULL;
}
#else /* MS_WINDOWS */
/*[clinic input]
os.putenv
name: FSConverter
value: FSConverter
/
Change or add an environment variable.
[clinic start generated code]*/
static PyObject *
os_putenv_impl(PyObject *module, PyObject *name, PyObject *value)
/*[clinic end generated code: output=d29a567d6b2327d2 input=a97bc6152f688d31]*/
{
PyObject *bytes = NULL;
char *env;
const char *name_string = PyBytes_AS_STRING(name);
const char *value_string = PyBytes_AS_STRING(value);
if (strchr(name_string, '=') != NULL) {
PyErr_SetString(PyExc_ValueError, "illegal environment variable name");
return NULL;
}
bytes = PyBytes_FromFormat("%s=%s", name_string, value_string);
if (bytes == NULL) {
return NULL;
}
env = PyBytes_AS_STRING(bytes);
if (putenv(env)) {
Py_DECREF(bytes);
return posix_error();
}
posix_putenv_garbage_setitem(name, bytes);
Py_RETURN_NONE;
}
#endif /* MS_WINDOWS */
#endif /* HAVE_PUTENV */
#ifdef HAVE_UNSETENV
/*[clinic input]
os.unsetenv
name: FSConverter
/
Delete an environment variable.
[clinic start generated code]*/
static PyObject *
os_unsetenv_impl(PyObject *module, PyObject *name)
/*[clinic end generated code: output=54c4137ab1834f02 input=2bb5288a599c7107]*/
{
#ifndef HAVE_BROKEN_UNSETENV
int err;
#endif
#ifdef HAVE_BROKEN_UNSETENV
unsetenv(PyBytes_AS_STRING(name));
#else
err = unsetenv(PyBytes_AS_STRING(name));
if (err)
return posix_error();
#endif
/* Remove the key from posix_putenv_garbage;
* this will cause it to be collected. This has to
* happen after the real unsetenv() call because the
* old value was still accessible until then.
*/
if (PyDict_DelItem(posix_putenv_garbage, name)) {
/* really not much we can do; just leak */
PyErr_Clear();
}
Py_RETURN_NONE;
}
#endif /* HAVE_UNSETENV */
/*[clinic input]
os.strerror
code: int
/
Translate an error code to a message string.
[clinic start generated code]*/
static PyObject *
os_strerror_impl(PyObject *module, int code)
/*[clinic end generated code: output=baebf09fa02a78f2 input=75a8673d97915a91]*/
{
char *message = strerror(code);
if (message == NULL) {
PyErr_SetString(PyExc_ValueError,
"strerror() argument out of range");
return NULL;
}
return PyUnicode_DecodeLocale(message, "surrogateescape");
}
#ifdef WCOREDUMP
/*[clinic input]
os.WCOREDUMP -> bool
status: int
/
Return True if the process returning status was dumped to a core file.
[clinic start generated code]*/
static int
os_WCOREDUMP_impl(PyObject *module, int status)
/*[clinic end generated code: output=1a584b147b16bd18 input=8b05e7ab38528d04]*/
{
WAIT_TYPE wait_status;
WAIT_STATUS_INT(wait_status) = status;
return WCOREDUMP(wait_status);
}
#endif /* WCOREDUMP */
#ifdef WIFCONTINUED
/*[clinic input]
os.WIFCONTINUED -> bool
status: int
Return True if a particular process was continued from a job control stop.
Return True if the process returning status was continued from a
job control stop.
[clinic start generated code]*/
static int
os_WIFCONTINUED_impl(PyObject *module, int status)
/*[clinic end generated code: output=1e35295d844364bd input=e777e7d38eb25bd9]*/
{
WAIT_TYPE wait_status;
WAIT_STATUS_INT(wait_status) = status;
return WIFCONTINUED(wait_status);
}
#endif /* WIFCONTINUED */
#ifdef WIFSTOPPED
/*[clinic input]
os.WIFSTOPPED -> bool
status: int
Return True if the process returning status was stopped.
[clinic start generated code]*/
static int
os_WIFSTOPPED_impl(PyObject *module, int status)
/*[clinic end generated code: output=fdb57122a5c9b4cb input=043cb7f1289ef904]*/
{
WAIT_TYPE wait_status;
WAIT_STATUS_INT(wait_status) = status;
return WIFSTOPPED(wait_status);
}
#endif /* WIFSTOPPED */
#ifdef WIFSIGNALED
/*[clinic input]
os.WIFSIGNALED -> bool
status: int
Return True if the process returning status was terminated by a signal.
[clinic start generated code]*/
static int
os_WIFSIGNALED_impl(PyObject *module, int status)
/*[clinic end generated code: output=d1dde4dcc819a5f5 input=d55ba7cc9ce5dc43]*/
{
WAIT_TYPE wait_status;
WAIT_STATUS_INT(wait_status) = status;
return WIFSIGNALED(wait_status);
}
#endif /* WIFSIGNALED */
#ifdef WIFEXITED
/*[clinic input]
os.WIFEXITED -> bool
status: int
Return True if the process returning status exited via the exit() system call.
[clinic start generated code]*/
static int
os_WIFEXITED_impl(PyObject *module, int status)
/*[clinic end generated code: output=01c09d6ebfeea397 input=d63775a6791586c0]*/
{
WAIT_TYPE wait_status;
WAIT_STATUS_INT(wait_status) = status;
return WIFEXITED(wait_status);
}
#endif /* WIFEXITED */
#ifdef WEXITSTATUS
/*[clinic input]
os.WEXITSTATUS -> int
status: int
Return the process return code from status.
[clinic start generated code]*/
static int
os_WEXITSTATUS_impl(PyObject *module, int status)
/*[clinic end generated code: output=6e3efbba11f6488d input=e1fb4944e377585b]*/
{
WAIT_TYPE wait_status;
WAIT_STATUS_INT(wait_status) = status;
return WEXITSTATUS(wait_status);
}
#endif /* WEXITSTATUS */
#ifdef WTERMSIG
/*[clinic input]
os.WTERMSIG -> int
status: int
Return the signal that terminated the process that provided the status value.
[clinic start generated code]*/
static int
os_WTERMSIG_impl(PyObject *module, int status)
/*[clinic end generated code: output=172f7dfc8dcfc3ad input=727fd7f84ec3f243]*/
{
WAIT_TYPE wait_status;
WAIT_STATUS_INT(wait_status) = status;
return WTERMSIG(wait_status);
}
#endif /* WTERMSIG */
#ifdef WSTOPSIG
/*[clinic input]
os.WSTOPSIG -> int
status: int
Return the signal that stopped the process that provided the status value.
[clinic start generated code]*/
static int
os_WSTOPSIG_impl(PyObject *module, int status)
/*[clinic end generated code: output=0ab7586396f5d82b input=46ebf1d1b293c5c1]*/
{
WAIT_TYPE wait_status;
WAIT_STATUS_INT(wait_status) = status;
return WSTOPSIG(wait_status);
}
#endif /* WSTOPSIG */
#if defined(HAVE_FSTATVFS)
#ifdef _SCO_DS
/* SCO OpenServer 5.0 and later requires _SVID3 before it reveals the
needed definitions in sys/statvfs.h */
#define _SVID3
#endif
static PyObject *
_pystatvfs_fromstructstatvfs(struct statvfs st) {
PyObject *v = PyStructSequence_New(&StatVFSResultType);
if (v == NULL)
return NULL;
PyStructSequence_SET_ITEM(v, 0, PyLong_FromLong((long) st.f_bsize));
PyStructSequence_SET_ITEM(v, 1, PyLong_FromLong((long) st.f_frsize));
#if !defined(HAVE_LARGEFILE_SUPPORT)
PyStructSequence_SET_ITEM(v, 2, PyLong_FromLong((long) st.f_blocks));
PyStructSequence_SET_ITEM(v, 3, PyLong_FromLong((long) st.f_bfree));
PyStructSequence_SET_ITEM(v, 4, PyLong_FromLong((long) st.f_bavail));
PyStructSequence_SET_ITEM(v, 5, PyLong_FromLong((long) st.f_files));
PyStructSequence_SET_ITEM(v, 6, PyLong_FromLong((long) st.f_ffree));
PyStructSequence_SET_ITEM(v, 7, PyLong_FromLong((long) st.f_favail));
#else
PyStructSequence_SET_ITEM(v, 2, PyLong_FromLongLong((long long) st.f_blocks));
PyStructSequence_SET_ITEM(v, 3, PyLong_FromLongLong((long long) st.f_bfree));
PyStructSequence_SET_ITEM(v, 4, PyLong_FromLongLong((long long) st.f_bavail));
PyStructSequence_SET_ITEM(v, 5, PyLong_FromLongLong((long long) st.f_files));
PyStructSequence_SET_ITEM(v, 6, PyLong_FromLongLong((long long) st.f_ffree));
PyStructSequence_SET_ITEM(v, 7, PyLong_FromLongLong((long long) st.f_favail));
#endif
PyStructSequence_SET_ITEM(v, 8, PyLong_FromLong((long) st.f_flag));
PyStructSequence_SET_ITEM(v, 9, PyLong_FromLong((long) st.f_namemax));
if (PyErr_Occurred()) {
Py_DECREF(v);
return NULL;
}
return v;
}
/*[clinic input]
os.fstatvfs
fd: int
/
Perform an fstatvfs system call on the given fd.
Equivalent to statvfs(fd).
[clinic start generated code]*/
static PyObject *
os_fstatvfs_impl(PyObject *module, int fd)
/*[clinic end generated code: output=53547cf0cc55e6c5 input=d8122243ac50975e]*/
{
int result;
int async_err = 0;
struct statvfs st;
do {
Py_BEGIN_ALLOW_THREADS
result = fstatvfs(fd, &st);
Py_END_ALLOW_THREADS
} while (result != 0 && errno == EINTR &&
!(async_err = PyErr_CheckSignals()));
if (result != 0)
return (!async_err) ? posix_error() : NULL;
return _pystatvfs_fromstructstatvfs(st);
}
#endif /* defined(HAVE_FSTATVFS) */
#if defined(HAVE_STATVFS)
/*[clinic input]
os.statvfs
path: path_t(allow_fd='PATH_HAVE_FSTATVFS')
Perform a statvfs system call on the given path.
path may always be specified as a string.
On some platforms, path may also be specified as an open file descriptor.
If this functionality is unavailable, using it raises an exception.
[clinic start generated code]*/
static PyObject *
os_statvfs_impl(PyObject *module, path_t *path)
/*[clinic end generated code: output=87106dd1beb8556e input=3f5c35791c669bd9]*/
{
int result;
struct statvfs st;
Py_BEGIN_ALLOW_THREADS
#ifdef HAVE_FSTATVFS
if (path->fd != -1) {
#ifdef __APPLE__
/* handle weak-linking on Mac OS X 10.3 */
if (fstatvfs == NULL) {
fd_specified("statvfs", path->fd);
return NULL;
}
#endif
result = fstatvfs(path->fd, &st);
}
else
#endif
result = statvfs(path->narrow, &st);
Py_END_ALLOW_THREADS
if (result) {
return path_error(path);
}
return _pystatvfs_fromstructstatvfs(st);
}
#endif /* defined(HAVE_STATVFS) */
#ifdef MS_WINDOWS
/*[clinic input]
os._getdiskusage
path: Py_UNICODE
Return disk usage statistics about the given path as a (total, free) tuple.
[clinic start generated code]*/
static PyObject *
os__getdiskusage_impl(PyObject *module, Py_UNICODE *path)
/*[clinic end generated code: output=76d6adcd86b1db0b input=6458133aed893c78]*/
{
BOOL retval;
ULARGE_INTEGER _, total, free;
Py_BEGIN_ALLOW_THREADS
retval = GetDiskFreeSpaceExW(path, &_, &total, &free);
Py_END_ALLOW_THREADS
if (retval == 0)
return PyErr_SetFromWindowsErr(0);
return Py_BuildValue("(LL)", total.QuadPart, free.QuadPart);
}
#endif /* MS_WINDOWS */
/* This is used for fpathconf(), pathconf(), confstr() and sysconf().
* It maps strings representing configuration variable names to
* integer values, allowing those functions to be called with the
* magic names instead of polluting the module's namespace with tons of
* rarely-used constants. There are three separate tables that use
* these definitions.
*
* This code is always included, even if none of the interfaces that
* need it are included. The #if hackery needed to avoid it would be
* sufficiently pervasive that it's not worth the loss of readability.
*/
struct constdef {
const char *name;
int value;
};
static int
conv_confname(PyObject *arg, int *valuep, struct constdef *table,
size_t tablesize)
{
if (PyLong_Check(arg)) {
int value = _PyLong_AsInt(arg);
if (value == -1 && PyErr_Occurred())
return 0;
*valuep = value;
return 1;
}
else {
/* look up the value in the table using a binary search */
size_t lo = 0;
size_t mid;
size_t hi = tablesize;
int cmp;
const char *confname;
if (!PyUnicode_Check(arg)) {
PyErr_SetString(PyExc_TypeError,
"configuration names must be strings or integers");
return 0;
}
confname = PyUnicode_AsUTF8(arg);
if (confname == NULL)
return 0;
while (lo < hi) {
mid = (lo + hi) / 2;
cmp = strcmp(confname, table[mid].name);
if (cmp < 0)
hi = mid;
else if (cmp > 0)
lo = mid + 1;
else {
*valuep = table[mid].value;
return 1;
}
}
PyErr_SetString(PyExc_ValueError, "unrecognized configuration name");
return 0;
}
}
#if defined(HAVE_FPATHCONF) || defined(HAVE_PATHCONF)
static struct constdef posix_constants_pathconf[] = {
#ifdef _PC_ABI_AIO_XFER_MAX
{"PC_ABI_AIO_XFER_MAX", _PC_ABI_AIO_XFER_MAX},
#endif
#ifdef _PC_ABI_ASYNC_IO
{"PC_ABI_ASYNC_IO", _PC_ABI_ASYNC_IO},
#endif
#ifdef _PC_ASYNC_IO
{"PC_ASYNC_IO", _PC_ASYNC_IO},
#endif
#ifdef _PC_CHOWN_RESTRICTED
{"PC_CHOWN_RESTRICTED", _PC_CHOWN_RESTRICTED},
#endif
#ifdef _PC_FILESIZEBITS
{"PC_FILESIZEBITS", _PC_FILESIZEBITS},
#endif
#ifdef _PC_LAST
{"PC_LAST", _PC_LAST},
#endif
#ifdef _PC_LINK_MAX
{"PC_LINK_MAX", _PC_LINK_MAX},
#endif
#ifdef _PC_MAX_CANON
{"PC_MAX_CANON", _PC_MAX_CANON},
#endif
#ifdef _PC_MAX_INPUT
{"PC_MAX_INPUT", _PC_MAX_INPUT},
#endif
#ifdef _PC_NAME_MAX
{"PC_NAME_MAX", _PC_NAME_MAX},
#endif
#ifdef _PC_NO_TRUNC
{"PC_NO_TRUNC", _PC_NO_TRUNC},
#endif
#ifdef _PC_PATH_MAX
{"PC_PATH_MAX", _PC_PATH_MAX},
#endif
#ifdef _PC_PIPE_BUF
{"PC_PIPE_BUF", _PC_PIPE_BUF},
#endif
#ifdef _PC_PRIO_IO
{"PC_PRIO_IO", _PC_PRIO_IO},
#endif
#ifdef _PC_SOCK_MAXBUF
{"PC_SOCK_MAXBUF", _PC_SOCK_MAXBUF},
#endif
#ifdef _PC_SYNC_IO
{"PC_SYNC_IO", _PC_SYNC_IO},
#endif
#ifdef _PC_VDISABLE
{"PC_VDISABLE", _PC_VDISABLE},
#endif
#ifdef _PC_ACL_ENABLED
{"PC_ACL_ENABLED", _PC_ACL_ENABLED},
#endif
#ifdef _PC_MIN_HOLE_SIZE
{"PC_MIN_HOLE_SIZE", _PC_MIN_HOLE_SIZE},
#endif
#ifdef _PC_ALLOC_SIZE_MIN
{"PC_ALLOC_SIZE_MIN", _PC_ALLOC_SIZE_MIN},
#endif
#ifdef _PC_REC_INCR_XFER_SIZE
{"PC_REC_INCR_XFER_SIZE", _PC_REC_INCR_XFER_SIZE},
#endif
#ifdef _PC_REC_MAX_XFER_SIZE
{"PC_REC_MAX_XFER_SIZE", _PC_REC_MAX_XFER_SIZE},
#endif
#ifdef _PC_REC_MIN_XFER_SIZE
{"PC_REC_MIN_XFER_SIZE", _PC_REC_MIN_XFER_SIZE},
#endif
#ifdef _PC_REC_XFER_ALIGN
{"PC_REC_XFER_ALIGN", _PC_REC_XFER_ALIGN},
#endif
#ifdef _PC_SYMLINK_MAX
{"PC_SYMLINK_MAX", _PC_SYMLINK_MAX},
#endif
#ifdef _PC_XATTR_ENABLED
{"PC_XATTR_ENABLED", _PC_XATTR_ENABLED},
#endif
#ifdef _PC_XATTR_EXISTS
{"PC_XATTR_EXISTS", _PC_XATTR_EXISTS},
#endif
#ifdef _PC_TIMESTAMP_RESOLUTION
{"PC_TIMESTAMP_RESOLUTION", _PC_TIMESTAMP_RESOLUTION},
#endif
};
static int
conv_path_confname(PyObject *arg, int *valuep)
{
return conv_confname(arg, valuep, posix_constants_pathconf,
sizeof(posix_constants_pathconf)
/ sizeof(struct constdef));
}
#endif
#ifdef HAVE_FPATHCONF
/*[clinic input]
os.fpathconf -> long
fd: int
name: path_confname
/
Return the configuration limit name for the file descriptor fd.
If there is no limit, return -1.
[clinic start generated code]*/
static long
os_fpathconf_impl(PyObject *module, int fd, int name)
/*[clinic end generated code: output=d5b7042425fc3e21 input=5942a024d3777810]*/
{
long limit;
errno = 0;
limit = fpathconf(fd, name);
if (limit == -1 && errno != 0)
posix_error();
return limit;
}
#endif /* HAVE_FPATHCONF */
#ifdef HAVE_PATHCONF
/*[clinic input]
os.pathconf -> long
path: path_t(allow_fd='PATH_HAVE_FPATHCONF')
name: path_confname
Return the configuration limit name for the file or directory path.
If there is no limit, return -1.
On some platforms, path may also be specified as an open file descriptor.
If this functionality is unavailable, using it raises an exception.
[clinic start generated code]*/
static long
os_pathconf_impl(PyObject *module, path_t *path, int name)
/*[clinic end generated code: output=5bedee35b293a089 input=bc3e2a985af27e5e]*/
{
long limit;
errno = 0;
#ifdef HAVE_FPATHCONF
if (path->fd != -1)
limit = fpathconf(path->fd, name);
else
#endif
limit = pathconf(path->narrow, name);
if (limit == -1 && errno != 0) {
if (errno == EINVAL)
/* could be a path or name problem */
posix_error();
else
path_error(path);
}
return limit;
}
#endif /* HAVE_PATHCONF */
#ifdef HAVE_CONFSTR
static struct constdef posix_constants_confstr[] = {
#ifdef _CS_ARCHITECTURE
{"CS_ARCHITECTURE", _CS_ARCHITECTURE},
#endif
#ifdef _CS_GNU_LIBC_VERSION
{"CS_GNU_LIBC_VERSION", _CS_GNU_LIBC_VERSION},
#endif
#ifdef _CS_GNU_LIBPTHREAD_VERSION
{"CS_GNU_LIBPTHREAD_VERSION", _CS_GNU_LIBPTHREAD_VERSION},
#endif
#ifdef _CS_HOSTNAME
{"CS_HOSTNAME", _CS_HOSTNAME},
#endif
#ifdef _CS_HW_PROVIDER
{"CS_HW_PROVIDER", _CS_HW_PROVIDER},
#endif
#ifdef _CS_HW_SERIAL
{"CS_HW_SERIAL", _CS_HW_SERIAL},
#endif
#ifdef _CS_INITTAB_NAME
{"CS_INITTAB_NAME", _CS_INITTAB_NAME},
#endif
#ifdef _CS_LFS64_CFLAGS
{"CS_LFS64_CFLAGS", _CS_LFS64_CFLAGS},
#endif
#ifdef _CS_LFS64_LDFLAGS
{"CS_LFS64_LDFLAGS", _CS_LFS64_LDFLAGS},
#endif
#ifdef _CS_LFS64_LIBS
{"CS_LFS64_LIBS", _CS_LFS64_LIBS},
#endif
#ifdef _CS_LFS64_LINTFLAGS
{"CS_LFS64_LINTFLAGS", _CS_LFS64_LINTFLAGS},
#endif
#ifdef _CS_LFS_CFLAGS
{"CS_LFS_CFLAGS", _CS_LFS_CFLAGS},
#endif
#ifdef _CS_LFS_LDFLAGS
{"CS_LFS_LDFLAGS", _CS_LFS_LDFLAGS},
#endif
#ifdef _CS_LFS_LIBS
{"CS_LFS_LIBS", _CS_LFS_LIBS},
#endif
#ifdef _CS_LFS_LINTFLAGS
{"CS_LFS_LINTFLAGS", _CS_LFS_LINTFLAGS},
#endif
#ifdef _CS_MACHINE
{"CS_MACHINE", _CS_MACHINE},
#endif
#ifdef _CS_PATH
{"CS_PATH", _CS_PATH},
#endif
#ifdef _CS_RELEASE
{"CS_RELEASE", _CS_RELEASE},
#endif
#ifdef _CS_SRPC_DOMAIN
{"CS_SRPC_DOMAIN", _CS_SRPC_DOMAIN},
#endif
#ifdef _CS_SYSNAME
{"CS_SYSNAME", _CS_SYSNAME},
#endif
#ifdef _CS_VERSION
{"CS_VERSION", _CS_VERSION},
#endif
#ifdef _CS_XBS5_ILP32_OFF32_CFLAGS
{"CS_XBS5_ILP32_OFF32_CFLAGS", _CS_XBS5_ILP32_OFF32_CFLAGS},
#endif
#ifdef _CS_XBS5_ILP32_OFF32_LDFLAGS
{"CS_XBS5_ILP32_OFF32_LDFLAGS", _CS_XBS5_ILP32_OFF32_LDFLAGS},
#endif
#ifdef _CS_XBS5_ILP32_OFF32_LIBS
{"CS_XBS5_ILP32_OFF32_LIBS", _CS_XBS5_ILP32_OFF32_LIBS},
#endif
#ifdef _CS_XBS5_ILP32_OFF32_LINTFLAGS
{"CS_XBS5_ILP32_OFF32_LINTFLAGS", _CS_XBS5_ILP32_OFF32_LINTFLAGS},
#endif
#ifdef _CS_XBS5_ILP32_OFFBIG_CFLAGS
{"CS_XBS5_ILP32_OFFBIG_CFLAGS", _CS_XBS5_ILP32_OFFBIG_CFLAGS},
#endif
#ifdef _CS_XBS5_ILP32_OFFBIG_LDFLAGS
{"CS_XBS5_ILP32_OFFBIG_LDFLAGS", _CS_XBS5_ILP32_OFFBIG_LDFLAGS},
#endif
#ifdef _CS_XBS5_ILP32_OFFBIG_LIBS
{"CS_XBS5_ILP32_OFFBIG_LIBS", _CS_XBS5_ILP32_OFFBIG_LIBS},
#endif
#ifdef _CS_XBS5_ILP32_OFFBIG_LINTFLAGS
{"CS_XBS5_ILP32_OFFBIG_LINTFLAGS", _CS_XBS5_ILP32_OFFBIG_LINTFLAGS},
#endif
#ifdef _CS_XBS5_LP64_OFF64_CFLAGS
{"CS_XBS5_LP64_OFF64_CFLAGS", _CS_XBS5_LP64_OFF64_CFLAGS},
#endif
#ifdef _CS_XBS5_LP64_OFF64_LDFLAGS
{"CS_XBS5_LP64_OFF64_LDFLAGS", _CS_XBS5_LP64_OFF64_LDFLAGS},
#endif
#ifdef _CS_XBS5_LP64_OFF64_LIBS
{"CS_XBS5_LP64_OFF64_LIBS", _CS_XBS5_LP64_OFF64_LIBS},
#endif
#ifdef _CS_XBS5_LP64_OFF64_LINTFLAGS
{"CS_XBS5_LP64_OFF64_LINTFLAGS", _CS_XBS5_LP64_OFF64_LINTFLAGS},
#endif
#ifdef _CS_XBS5_LPBIG_OFFBIG_CFLAGS
{"CS_XBS5_LPBIG_OFFBIG_CFLAGS", _CS_XBS5_LPBIG_OFFBIG_CFLAGS},
#endif
#ifdef _CS_XBS5_LPBIG_OFFBIG_LDFLAGS
{"CS_XBS5_LPBIG_OFFBIG_LDFLAGS", _CS_XBS5_LPBIG_OFFBIG_LDFLAGS},
#endif
#ifdef _CS_XBS5_LPBIG_OFFBIG_LIBS
{"CS_XBS5_LPBIG_OFFBIG_LIBS", _CS_XBS5_LPBIG_OFFBIG_LIBS},
#endif
#ifdef _CS_XBS5_LPBIG_OFFBIG_LINTFLAGS
{"CS_XBS5_LPBIG_OFFBIG_LINTFLAGS", _CS_XBS5_LPBIG_OFFBIG_LINTFLAGS},
#endif
#ifdef _MIPS_CS_AVAIL_PROCESSORS
{"MIPS_CS_AVAIL_PROCESSORS", _MIPS_CS_AVAIL_PROCESSORS},
#endif
#ifdef _MIPS_CS_BASE
{"MIPS_CS_BASE", _MIPS_CS_BASE},
#endif
#ifdef _MIPS_CS_HOSTID
{"MIPS_CS_HOSTID", _MIPS_CS_HOSTID},
#endif
#ifdef _MIPS_CS_HW_NAME
{"MIPS_CS_HW_NAME", _MIPS_CS_HW_NAME},
#endif
#ifdef _MIPS_CS_NUM_PROCESSORS
{"MIPS_CS_NUM_PROCESSORS", _MIPS_CS_NUM_PROCESSORS},
#endif
#ifdef _MIPS_CS_OSREL_MAJ
{"MIPS_CS_OSREL_MAJ", _MIPS_CS_OSREL_MAJ},
#endif
#ifdef _MIPS_CS_OSREL_MIN
{"MIPS_CS_OSREL_MIN", _MIPS_CS_OSREL_MIN},
#endif
#ifdef _MIPS_CS_OSREL_PATCH
{"MIPS_CS_OSREL_PATCH", _MIPS_CS_OSREL_PATCH},
#endif
#ifdef _MIPS_CS_OS_NAME
{"MIPS_CS_OS_NAME", _MIPS_CS_OS_NAME},
#endif
#ifdef _MIPS_CS_OS_PROVIDER
{"MIPS_CS_OS_PROVIDER", _MIPS_CS_OS_PROVIDER},
#endif
#ifdef _MIPS_CS_PROCESSORS
{"MIPS_CS_PROCESSORS", _MIPS_CS_PROCESSORS},
#endif
#ifdef _MIPS_CS_SERIAL
{"MIPS_CS_SERIAL", _MIPS_CS_SERIAL},
#endif
#ifdef _MIPS_CS_VENDOR
{"MIPS_CS_VENDOR", _MIPS_CS_VENDOR},
#endif
};
static int
conv_confstr_confname(PyObject *arg, int *valuep)
{
return conv_confname(arg, valuep, posix_constants_confstr,
sizeof(posix_constants_confstr)
/ sizeof(struct constdef));
}
/*[clinic input]
os.confstr
name: confstr_confname
/
Return a string-valued system configuration variable.
[clinic start generated code]*/
static PyObject *
os_confstr_impl(PyObject *module, int name)
/*[clinic end generated code: output=bfb0b1b1e49b9383 input=18fb4d0567242e65]*/
{
PyObject *result = NULL;
char buffer[255];
size_t len;
errno = 0;
len = confstr(name, buffer, sizeof(buffer));
if (len == 0) {
if (errno) {
posix_error();
return NULL;
}
else {
Py_RETURN_NONE;
}
}
if (len >= sizeof(buffer)) {
size_t len2;
char *buf = PyMem_Malloc(len);
if (buf == NULL)
return PyErr_NoMemory();
len2 = confstr(name, buf, len);
assert(len == len2);
result = PyUnicode_DecodeFSDefaultAndSize(buf, len2-1);
PyMem_Free(buf);
}
else
result = PyUnicode_DecodeFSDefaultAndSize(buffer, len-1);
return result;
}
#endif /* HAVE_CONFSTR */
#ifdef HAVE_SYSCONF
static struct constdef posix_constants_sysconf[] = {
#ifdef _SC_2_CHAR_TERM
{"SC_2_CHAR_TERM", _SC_2_CHAR_TERM},
#endif
#ifdef _SC_2_C_BIND
{"SC_2_C_BIND", _SC_2_C_BIND},
#endif
#ifdef _SC_2_C_DEV
{"SC_2_C_DEV", _SC_2_C_DEV},
#endif
#ifdef _SC_2_C_VERSION
{"SC_2_C_VERSION", _SC_2_C_VERSION},
#endif
#ifdef _SC_2_FORT_DEV
{"SC_2_FORT_DEV", _SC_2_FORT_DEV},
#endif
#ifdef _SC_2_FORT_RUN
{"SC_2_FORT_RUN", _SC_2_FORT_RUN},
#endif
#ifdef _SC_2_LOCALEDEF
{"SC_2_LOCALEDEF", _SC_2_LOCALEDEF},
#endif
#ifdef _SC_2_SW_DEV
{"SC_2_SW_DEV", _SC_2_SW_DEV},
#endif
#ifdef _SC_2_UPE
{"SC_2_UPE", _SC_2_UPE},
#endif
#ifdef _SC_2_VERSION
{"SC_2_VERSION", _SC_2_VERSION},
#endif
#ifdef _SC_ABI_ASYNCHRONOUS_IO
{"SC_ABI_ASYNCHRONOUS_IO", _SC_ABI_ASYNCHRONOUS_IO},
#endif
#ifdef _SC_ACL
{"SC_ACL", _SC_ACL},
#endif
#ifdef _SC_AIO_LISTIO_MAX
{"SC_AIO_LISTIO_MAX", _SC_AIO_LISTIO_MAX},
#endif
#ifdef _SC_AIO_MAX
{"SC_AIO_MAX", _SC_AIO_MAX},
#endif
#ifdef _SC_AIO_PRIO_DELTA_MAX
{"SC_AIO_PRIO_DELTA_MAX", _SC_AIO_PRIO_DELTA_MAX},
#endif
#ifdef _SC_ARG_MAX
{"SC_ARG_MAX", _SC_ARG_MAX},
#endif
#ifdef _SC_ASYNCHRONOUS_IO
{"SC_ASYNCHRONOUS_IO", _SC_ASYNCHRONOUS_IO},
#endif
#ifdef _SC_ATEXIT_MAX
{"SC_ATEXIT_MAX", _SC_ATEXIT_MAX},
#endif
#ifdef _SC_AUDIT
{"SC_AUDIT", _SC_AUDIT},
#endif
#ifdef _SC_AVPHYS_PAGES
{"SC_AVPHYS_PAGES", _SC_AVPHYS_PAGES},
#endif
#ifdef _SC_BC_BASE_MAX
{"SC_BC_BASE_MAX", _SC_BC_BASE_MAX},
#endif
#ifdef _SC_BC_DIM_MAX
{"SC_BC_DIM_MAX", _SC_BC_DIM_MAX},
#endif
#ifdef _SC_BC_SCALE_MAX
{"SC_BC_SCALE_MAX", _SC_BC_SCALE_MAX},
#endif
#ifdef _SC_BC_STRING_MAX
{"SC_BC_STRING_MAX", _SC_BC_STRING_MAX},
#endif
#ifdef _SC_CAP
{"SC_CAP", _SC_CAP},
#endif
#ifdef _SC_CHARCLASS_NAME_MAX
{"SC_CHARCLASS_NAME_MAX", _SC_CHARCLASS_NAME_MAX},
#endif
#ifdef _SC_CHAR_BIT
{"SC_CHAR_BIT", _SC_CHAR_BIT},
#endif
#ifdef _SC_CHAR_MAX
{"SC_CHAR_MAX", _SC_CHAR_MAX},
#endif
#ifdef _SC_CHAR_MIN
{"SC_CHAR_MIN", _SC_CHAR_MIN},
#endif
#ifdef _SC_CHILD_MAX
{"SC_CHILD_MAX", _SC_CHILD_MAX},
#endif
#ifdef _SC_CLK_TCK
{"SC_CLK_TCK", _SC_CLK_TCK},
#endif
#ifdef _SC_COHER_BLKSZ
{"SC_COHER_BLKSZ", _SC_COHER_BLKSZ},
#endif
#ifdef _SC_COLL_WEIGHTS_MAX
{"SC_COLL_WEIGHTS_MAX", _SC_COLL_WEIGHTS_MAX},
#endif
#ifdef _SC_DCACHE_ASSOC
{"SC_DCACHE_ASSOC", _SC_DCACHE_ASSOC},
#endif
#ifdef _SC_DCACHE_BLKSZ
{"SC_DCACHE_BLKSZ", _SC_DCACHE_BLKSZ},
#endif
#ifdef _SC_DCACHE_LINESZ
{"SC_DCACHE_LINESZ", _SC_DCACHE_LINESZ},
#endif
#ifdef _SC_DCACHE_SZ
{"SC_DCACHE_SZ", _SC_DCACHE_SZ},
#endif
#ifdef _SC_DCACHE_TBLKSZ
{"SC_DCACHE_TBLKSZ", _SC_DCACHE_TBLKSZ},
#endif
#ifdef _SC_DELAYTIMER_MAX
{"SC_DELAYTIMER_MAX", _SC_DELAYTIMER_MAX},
#endif
#ifdef _SC_EQUIV_CLASS_MAX
{"SC_EQUIV_CLASS_MAX", _SC_EQUIV_CLASS_MAX},
#endif
#ifdef _SC_EXPR_NEST_MAX
{"SC_EXPR_NEST_MAX", _SC_EXPR_NEST_MAX},
#endif
#ifdef _SC_FSYNC
{"SC_FSYNC", _SC_FSYNC},
#endif
#ifdef _SC_GETGR_R_SIZE_MAX
{"SC_GETGR_R_SIZE_MAX", _SC_GETGR_R_SIZE_MAX},
#endif
#ifdef _SC_GETPW_R_SIZE_MAX
{"SC_GETPW_R_SIZE_MAX", _SC_GETPW_R_SIZE_MAX},
#endif
#ifdef _SC_ICACHE_ASSOC
{"SC_ICACHE_ASSOC", _SC_ICACHE_ASSOC},
#endif
#ifdef _SC_ICACHE_BLKSZ
{"SC_ICACHE_BLKSZ", _SC_ICACHE_BLKSZ},
#endif
#ifdef _SC_ICACHE_LINESZ
{"SC_ICACHE_LINESZ", _SC_ICACHE_LINESZ},
#endif
#ifdef _SC_ICACHE_SZ
{"SC_ICACHE_SZ", _SC_ICACHE_SZ},
#endif
#ifdef _SC_INF
{"SC_INF", _SC_INF},
#endif
#ifdef _SC_INT_MAX
{"SC_INT_MAX", _SC_INT_MAX},
#endif
#ifdef _SC_INT_MIN
{"SC_INT_MIN", _SC_INT_MIN},
#endif
#ifdef _SC_IOV_MAX
{"SC_IOV_MAX", _SC_IOV_MAX},
#endif
#ifdef _SC_IP_SECOPTS
{"SC_IP_SECOPTS", _SC_IP_SECOPTS},
#endif
#ifdef _SC_JOB_CONTROL
{"SC_JOB_CONTROL", _SC_JOB_CONTROL},
#endif
#ifdef _SC_KERN_POINTERS
{"SC_KERN_POINTERS", _SC_KERN_POINTERS},
#endif
#ifdef _SC_KERN_SIM
{"SC_KERN_SIM", _SC_KERN_SIM},
#endif
#ifdef _SC_LINE_MAX
{"SC_LINE_MAX", _SC_LINE_MAX},
#endif
#ifdef _SC_LOGIN_NAME_MAX
{"SC_LOGIN_NAME_MAX", _SC_LOGIN_NAME_MAX},
#endif
#ifdef _SC_LOGNAME_MAX
{"SC_LOGNAME_MAX", _SC_LOGNAME_MAX},
#endif
#ifdef _SC_LONG_BIT
{"SC_LONG_BIT", _SC_LONG_BIT},
#endif
#ifdef _SC_MAC
{"SC_MAC", _SC_MAC},
#endif
#ifdef _SC_MAPPED_FILES
{"SC_MAPPED_FILES", _SC_MAPPED_FILES},
#endif
#ifdef _SC_MAXPID
{"SC_MAXPID", _SC_MAXPID},
#endif
#ifdef _SC_MB_LEN_MAX
{"SC_MB_LEN_MAX", _SC_MB_LEN_MAX},
#endif
#ifdef _SC_MEMLOCK
{"SC_MEMLOCK", _SC_MEMLOCK},
#endif
#ifdef _SC_MEMLOCK_RANGE
{"SC_MEMLOCK_RANGE", _SC_MEMLOCK_RANGE},
#endif
#ifdef _SC_MEMORY_PROTECTION
{"SC_MEMORY_PROTECTION", _SC_MEMORY_PROTECTION},
#endif
#ifdef _SC_MESSAGE_PASSING
{"SC_MESSAGE_PASSING", _SC_MESSAGE_PASSING},
#endif
#ifdef _SC_MMAP_FIXED_ALIGNMENT
{"SC_MMAP_FIXED_ALIGNMENT", _SC_MMAP_FIXED_ALIGNMENT},
#endif
#ifdef _SC_MQ_OPEN_MAX
{"SC_MQ_OPEN_MAX", _SC_MQ_OPEN_MAX},
#endif
#ifdef _SC_MQ_PRIO_MAX
{"SC_MQ_PRIO_MAX", _SC_MQ_PRIO_MAX},
#endif
#ifdef _SC_NACLS_MAX
{"SC_NACLS_MAX", _SC_NACLS_MAX},
#endif
#ifdef _SC_NGROUPS_MAX
{"SC_NGROUPS_MAX", _SC_NGROUPS_MAX},
#endif
#ifdef _SC_NL_ARGMAX
{"SC_NL_ARGMAX", _SC_NL_ARGMAX},
#endif
#ifdef _SC_NL_LANGMAX
{"SC_NL_LANGMAX", _SC_NL_LANGMAX},
#endif
#ifdef _SC_NL_MSGMAX
{"SC_NL_MSGMAX", _SC_NL_MSGMAX},
#endif
#ifdef _SC_NL_NMAX
{"SC_NL_NMAX", _SC_NL_NMAX},
#endif
#ifdef _SC_NL_SETMAX
{"SC_NL_SETMAX", _SC_NL_SETMAX},
#endif
#ifdef _SC_NL_TEXTMAX
{"SC_NL_TEXTMAX", _SC_NL_TEXTMAX},
#endif
#ifdef _SC_NPROCESSORS_CONF
{"SC_NPROCESSORS_CONF", _SC_NPROCESSORS_CONF},
#endif
#ifdef _SC_NPROCESSORS_ONLN
{"SC_NPROCESSORS_ONLN", _SC_NPROCESSORS_ONLN},
#endif
#ifdef _SC_NPROC_CONF
{"SC_NPROC_CONF", _SC_NPROC_CONF},
#endif
#ifdef _SC_NPROC_ONLN
{"SC_NPROC_ONLN", _SC_NPROC_ONLN},
#endif
#ifdef _SC_NZERO
{"SC_NZERO", _SC_NZERO},
#endif
#ifdef _SC_OPEN_MAX
{"SC_OPEN_MAX", _SC_OPEN_MAX},
#endif
#ifdef _SC_PAGESIZE
{"SC_PAGESIZE", _SC_PAGESIZE},
#endif
#ifdef _SC_PAGE_SIZE
{"SC_PAGE_SIZE", _SC_PAGE_SIZE},
#endif
#ifdef _SC_PASS_MAX
{"SC_PASS_MAX", _SC_PASS_MAX},
#endif
#ifdef _SC_PHYS_PAGES
{"SC_PHYS_PAGES", _SC_PHYS_PAGES},
#endif
#ifdef _SC_PII
{"SC_PII", _SC_PII},
#endif
#ifdef _SC_PII_INTERNET
{"SC_PII_INTERNET", _SC_PII_INTERNET},
#endif
#ifdef _SC_PII_INTERNET_DGRAM
{"SC_PII_INTERNET_DGRAM", _SC_PII_INTERNET_DGRAM},
#endif
#ifdef _SC_PII_INTERNET_STREAM
{"SC_PII_INTERNET_STREAM", _SC_PII_INTERNET_STREAM},
#endif
#ifdef _SC_PII_OSI
{"SC_PII_OSI", _SC_PII_OSI},
#endif
#ifdef _SC_PII_OSI_CLTS
{"SC_PII_OSI_CLTS", _SC_PII_OSI_CLTS},
#endif
#ifdef _SC_PII_OSI_COTS
{"SC_PII_OSI_COTS", _SC_PII_OSI_COTS},
#endif
#ifdef _SC_PII_OSI_M
{"SC_PII_OSI_M", _SC_PII_OSI_M},
#endif
#ifdef _SC_PII_SOCKET
{"SC_PII_SOCKET", _SC_PII_SOCKET},
#endif
#ifdef _SC_PII_XTI
{"SC_PII_XTI", _SC_PII_XTI},
#endif
#ifdef _SC_POLL
{"SC_POLL", _SC_POLL},
#endif
#ifdef _SC_PRIORITIZED_IO
{"SC_PRIORITIZED_IO", _SC_PRIORITIZED_IO},
#endif
#ifdef _SC_PRIORITY_SCHEDULING
{"SC_PRIORITY_SCHEDULING", _SC_PRIORITY_SCHEDULING},
#endif
#ifdef _SC_REALTIME_SIGNALS
{"SC_REALTIME_SIGNALS", _SC_REALTIME_SIGNALS},
#endif
#ifdef _SC_RE_DUP_MAX
{"SC_RE_DUP_MAX", _SC_RE_DUP_MAX},
#endif
#ifdef _SC_RTSIG_MAX
{"SC_RTSIG_MAX", _SC_RTSIG_MAX},
#endif
#ifdef _SC_SAVED_IDS
{"SC_SAVED_IDS", _SC_SAVED_IDS},
#endif
#ifdef _SC_SCHAR_MAX
{"SC_SCHAR_MAX", _SC_SCHAR_MAX},
#endif
#ifdef _SC_SCHAR_MIN
{"SC_SCHAR_MIN", _SC_SCHAR_MIN},
#endif
#ifdef _SC_SELECT
{"SC_SELECT", _SC_SELECT},
#endif
#ifdef _SC_SEMAPHORES
{"SC_SEMAPHORES", _SC_SEMAPHORES},
#endif
#ifdef _SC_SEM_NSEMS_MAX
{"SC_SEM_NSEMS_MAX", _SC_SEM_NSEMS_MAX},
#endif
#ifdef _SC_SEM_VALUE_MAX
{"SC_SEM_VALUE_MAX", _SC_SEM_VALUE_MAX},
#endif
#ifdef _SC_SHARED_MEMORY_OBJECTS
{"SC_SHARED_MEMORY_OBJECTS", _SC_SHARED_MEMORY_OBJECTS},
#endif
#ifdef _SC_SHRT_MAX
{"SC_SHRT_MAX", _SC_SHRT_MAX},
#endif
#ifdef _SC_SHRT_MIN
{"SC_SHRT_MIN", _SC_SHRT_MIN},
#endif
#ifdef _SC_SIGQUEUE_MAX
{"SC_SIGQUEUE_MAX", _SC_SIGQUEUE_MAX},
#endif
#ifdef _SC_SIGRT_MAX
{"SC_SIGRT_MAX", _SC_SIGRT_MAX},
#endif
#ifdef _SC_SIGRT_MIN
{"SC_SIGRT_MIN", _SC_SIGRT_MIN},
#endif
#ifdef _SC_SOFTPOWER
{"SC_SOFTPOWER", _SC_SOFTPOWER},
#endif
#ifdef _SC_SPLIT_CACHE
{"SC_SPLIT_CACHE", _SC_SPLIT_CACHE},
#endif
#ifdef _SC_SSIZE_MAX
{"SC_SSIZE_MAX", _SC_SSIZE_MAX},
#endif
#ifdef _SC_STACK_PROT
{"SC_STACK_PROT", _SC_STACK_PROT},
#endif
#ifdef _SC_STREAM_MAX
{"SC_STREAM_MAX", _SC_STREAM_MAX},
#endif
#ifdef _SC_SYNCHRONIZED_IO
{"SC_SYNCHRONIZED_IO", _SC_SYNCHRONIZED_IO},
#endif
#ifdef _SC_THREADS
{"SC_THREADS", _SC_THREADS},
#endif
#ifdef _SC_THREAD_ATTR_STACKADDR
{"SC_THREAD_ATTR_STACKADDR", _SC_THREAD_ATTR_STACKADDR},
#endif
#ifdef _SC_THREAD_ATTR_STACKSIZE
{"SC_THREAD_ATTR_STACKSIZE", _SC_THREAD_ATTR_STACKSIZE},
#endif
#ifdef _SC_THREAD_DESTRUCTOR_ITERATIONS
{"SC_THREAD_DESTRUCTOR_ITERATIONS", _SC_THREAD_DESTRUCTOR_ITERATIONS},
#endif
#ifdef _SC_THREAD_KEYS_MAX
{"SC_THREAD_KEYS_MAX", _SC_THREAD_KEYS_MAX},
#endif
#ifdef _SC_THREAD_PRIORITY_SCHEDULING
{"SC_THREAD_PRIORITY_SCHEDULING", _SC_THREAD_PRIORITY_SCHEDULING},
#endif
#ifdef _SC_THREAD_PRIO_INHERIT
{"SC_THREAD_PRIO_INHERIT", _SC_THREAD_PRIO_INHERIT},
#endif
#ifdef _SC_THREAD_PRIO_PROTECT
{"SC_THREAD_PRIO_PROTECT", _SC_THREAD_PRIO_PROTECT},
#endif
#ifdef _SC_THREAD_PROCESS_SHARED
{"SC_THREAD_PROCESS_SHARED", _SC_THREAD_PROCESS_SHARED},
#endif
#ifdef _SC_THREAD_SAFE_FUNCTIONS
{"SC_THREAD_SAFE_FUNCTIONS", _SC_THREAD_SAFE_FUNCTIONS},
#endif
#ifdef _SC_THREAD_STACK_MIN
{"SC_THREAD_STACK_MIN", _SC_THREAD_STACK_MIN},
#endif
#ifdef _SC_THREAD_THREADS_MAX
{"SC_THREAD_THREADS_MAX", _SC_THREAD_THREADS_MAX},
#endif
#ifdef _SC_TIMERS
{"SC_TIMERS", _SC_TIMERS},
#endif
#ifdef _SC_TIMER_MAX
{"SC_TIMER_MAX", _SC_TIMER_MAX},
#endif
#ifdef _SC_TTY_NAME_MAX
{"SC_TTY_NAME_MAX", _SC_TTY_NAME_MAX},
#endif
#ifdef _SC_TZNAME_MAX
{"SC_TZNAME_MAX", _SC_TZNAME_MAX},
#endif
#ifdef _SC_T_IOV_MAX
{"SC_T_IOV_MAX", _SC_T_IOV_MAX},
#endif
#ifdef _SC_UCHAR_MAX
{"SC_UCHAR_MAX", _SC_UCHAR_MAX},
#endif
#ifdef _SC_UINT_MAX
{"SC_UINT_MAX", _SC_UINT_MAX},
#endif
#ifdef _SC_UIO_MAXIOV
{"SC_UIO_MAXIOV", _SC_UIO_MAXIOV},
#endif
#ifdef _SC_ULONG_MAX
{"SC_ULONG_MAX", _SC_ULONG_MAX},
#endif
#ifdef _SC_USHRT_MAX
{"SC_USHRT_MAX", _SC_USHRT_MAX},
#endif
#ifdef _SC_VERSION
{"SC_VERSION", _SC_VERSION},
#endif
#ifdef _SC_WORD_BIT
{"SC_WORD_BIT", _SC_WORD_BIT},
#endif
#ifdef _SC_XBS5_ILP32_OFF32
{"SC_XBS5_ILP32_OFF32", _SC_XBS5_ILP32_OFF32},
#endif
#ifdef _SC_XBS5_ILP32_OFFBIG
{"SC_XBS5_ILP32_OFFBIG", _SC_XBS5_ILP32_OFFBIG},
#endif
#ifdef _SC_XBS5_LP64_OFF64
{"SC_XBS5_LP64_OFF64", _SC_XBS5_LP64_OFF64},
#endif
#ifdef _SC_XBS5_LPBIG_OFFBIG
{"SC_XBS5_LPBIG_OFFBIG", _SC_XBS5_LPBIG_OFFBIG},
#endif
#ifdef _SC_XOPEN_CRYPT
{"SC_XOPEN_CRYPT", _SC_XOPEN_CRYPT},
#endif
#ifdef _SC_XOPEN_ENH_I18N
{"SC_XOPEN_ENH_I18N", _SC_XOPEN_ENH_I18N},
#endif
#ifdef _SC_XOPEN_LEGACY
{"SC_XOPEN_LEGACY", _SC_XOPEN_LEGACY},
#endif
#ifdef _SC_XOPEN_REALTIME
{"SC_XOPEN_REALTIME", _SC_XOPEN_REALTIME},
#endif
#ifdef _SC_XOPEN_REALTIME_THREADS
{"SC_XOPEN_REALTIME_THREADS", _SC_XOPEN_REALTIME_THREADS},
#endif
#ifdef _SC_XOPEN_SHM
{"SC_XOPEN_SHM", _SC_XOPEN_SHM},
#endif
#ifdef _SC_XOPEN_UNIX
{"SC_XOPEN_UNIX", _SC_XOPEN_UNIX},
#endif
#ifdef _SC_XOPEN_VERSION
{"SC_XOPEN_VERSION", _SC_XOPEN_VERSION},
#endif
#ifdef _SC_XOPEN_XCU_VERSION
{"SC_XOPEN_XCU_VERSION", _SC_XOPEN_XCU_VERSION},
#endif
#ifdef _SC_XOPEN_XPG2
{"SC_XOPEN_XPG2", _SC_XOPEN_XPG2},
#endif
#ifdef _SC_XOPEN_XPG3
{"SC_XOPEN_XPG3", _SC_XOPEN_XPG3},
#endif
#ifdef _SC_XOPEN_XPG4
{"SC_XOPEN_XPG4", _SC_XOPEN_XPG4},
#endif
};
static int
conv_sysconf_confname(PyObject *arg, int *valuep)
{
return conv_confname(arg, valuep, posix_constants_sysconf,
sizeof(posix_constants_sysconf)
/ sizeof(struct constdef));
}
/*[clinic input]
os.sysconf -> long
name: sysconf_confname
/
Return an integer-valued system configuration variable.
[clinic start generated code]*/
static long
os_sysconf_impl(PyObject *module, int name)
/*[clinic end generated code: output=3662f945fc0cc756 input=279e3430a33f29e4]*/
{
long value;
errno = 0;
value = sysconf(name);
if (value == -1 && errno != 0)
posix_error();
return value;
}
#endif /* HAVE_SYSCONF */
/* This code is used to ensure that the tables of configuration value names
* are in sorted order as required by conv_confname(), and also to build
* the exported dictionaries that are used to publish information about the
* names available on the host platform.
*
* Sorting the table at runtime ensures that the table is properly ordered
* when used, even for platforms we're not able to test on. It also makes
* it easier to add additional entries to the tables.
*/
static int
cmp_constdefs(const void *v1, const void *v2)
{
const struct constdef *c1 =
(const struct constdef *) v1;
const struct constdef *c2 =
(const struct constdef *) v2;
return strcmp(c1->name, c2->name);
}
static int
setup_confname_table(struct constdef *table, size_t tablesize,
const char *tablename, PyObject *module)
{
PyObject *d = NULL;
size_t i;
qsort(table, tablesize, sizeof(struct constdef), cmp_constdefs);
d = PyDict_New();
if (d == NULL)
return -1;
for (i=0; i < tablesize; ++i) {
PyObject *o = PyLong_FromLong(table[i].value);
if (o == NULL || PyDict_SetItemString(d, table[i].name, o) == -1) {
Py_XDECREF(o);
Py_DECREF(d);
return -1;
}
Py_DECREF(o);
}
return PyModule_AddObject(module, tablename, d);
}
/* Return -1 on failure, 0 on success. */
static int
setup_confname_tables(PyObject *module)
{
#if defined(HAVE_FPATHCONF) || defined(HAVE_PATHCONF)
if (setup_confname_table(posix_constants_pathconf,
sizeof(posix_constants_pathconf)
/ sizeof(struct constdef),
"pathconf_names", module))
return -1;
#endif
#ifdef HAVE_CONFSTR
if (setup_confname_table(posix_constants_confstr,
sizeof(posix_constants_confstr)
/ sizeof(struct constdef),
"confstr_names", module))
return -1;
#endif
#ifdef HAVE_SYSCONF
if (setup_confname_table(posix_constants_sysconf,
sizeof(posix_constants_sysconf)
/ sizeof(struct constdef),
"sysconf_names", module))
return -1;
#endif
return 0;
}
/*[clinic input]
os.abort
Abort the interpreter immediately.
This function 'dumps core' or otherwise fails in the hardest way possible
on the hosting operating system. This function never returns.
[clinic start generated code]*/
static PyObject *
os_abort_impl(PyObject *module)
/*[clinic end generated code: output=dcf52586dad2467c input=cf2c7d98bc504047]*/
{
abort();
/*NOTREACHED*/
Py_FatalError("abort() called from Python code didn't abort!");
return NULL;
}
#ifdef MS_WINDOWS
/* Grab ShellExecute dynamically from shell32 */
static int has_ShellExecute = -1;
static int64_t (*Py_ShellExecuteW)(int64_t, const char16_t *, const char16_t *,
const char16_t *, const char16_t *, int);
static int
check_ShellExecute()
{
int64_t hShell32;
/* only recheck */
if (-1 == has_ShellExecute) {
Py_BEGIN_ALLOW_THREADS
hShell32 = LoadLibrary(u"SHELL32");
Py_END_ALLOW_THREADS
if (hShell32) {
Py_ShellExecuteW = GetProcAddress(hShell32, "ShellExecuteW");
has_ShellExecute = Py_ShellExecuteW != NULL;
} else {
has_ShellExecute = 0;
}
}
return has_ShellExecute;
}
/*[clinic input]
os.startfile
filepath: path_t
operation: Py_UNICODE = NULL
startfile(filepath [, operation])
Start a file with its associated application.
When "operation" is not specified or "open", this acts like
double-clicking the file in Explorer, or giving the file name as an
argument to the DOS "start" command: the file is opened with whatever
application (if any) its extension is associated.
When another "operation" is given, it specifies what should be done with
the file. A typical operation is "print".
startfile returns as soon as the associated application is launched.
There is no option to wait for the application to close, and no way
to retrieve the application's exit status.
The filepath is relative to the current directory. If you want to use
an absolute path, make sure the first character is not a slash ("/");
the underlying Win32 ShellExecute function doesn't work if it is.
[clinic start generated code]*/
static PyObject *
os_startfile_impl(PyObject *module, path_t *filepath, Py_UNICODE *operation)
/*[clinic end generated code: output=912ceba79acfa1c9 input=63950bf2986380d0]*/
{
HINSTANCE rc;
if(!check_ShellExecute()) {
/* If the OS doesn't have ShellExecute, return a
NotImplementedError. */
return PyErr_Format(PyExc_NotImplementedError,
"startfile not available on this platform");
}
Py_BEGIN_ALLOW_THREADS
rc = Py_ShellExecuteW(0, operation, filepath->wide, 0, 0, kNtSwShownormal);
Py_END_ALLOW_THREADS
if (rc <= (HINSTANCE)32) {
win32_error_object("startfile", filepath->object);
return NULL;
}
Py_RETURN_NONE;
}
#endif /* MS_WINDOWS */
#ifdef HAVE_GETLOADAVG
/*[clinic input]
os.getloadavg
Return average recent system load information.
Return the number of processes in the system run queue averaged over
the last 1, 5, and 15 minutes as a tuple of three floats.
Raises OSError if the load average was unobtainable.
[clinic start generated code]*/
static PyObject *
os_getloadavg_impl(PyObject *module)
/*[clinic end generated code: output=9ad3a11bfb4f4bd2 input=3d6d826b76d8a34e]*/
{
double loadavg[3];
if (getloadavg(loadavg, 3)!=3) {
PyErr_SetString(PyExc_OSError, "Load averages are unobtainable");
return NULL;
} else
return Py_BuildValue("ddd", loadavg[0], loadavg[1], loadavg[2]);
}
#endif /* HAVE_GETLOADAVG */
/*[clinic input]
os.device_encoding
fd: int
Return a string describing the encoding of a terminal's file descriptor.
The file descriptor must be attached to a terminal.
If the device is not a terminal, return None.
[clinic start generated code]*/
static PyObject *
os_device_encoding_impl(PyObject *module, int fd)
/*[clinic end generated code: output=e0d294bbab7e8c2b input=9e1d4a42b66df312]*/
{
return _Py_device_encoding(fd);
}
#ifdef HAVE_SETRESUID
/*[clinic input]
os.setresuid
ruid: uid_t
euid: uid_t
suid: uid_t
/
Set the current process's real, effective, and saved user ids.
[clinic start generated code]*/
static PyObject *
os_setresuid_impl(PyObject *module, uid_t ruid, uid_t euid, uid_t suid)
/*[clinic end generated code: output=834a641e15373e97 input=9e33cb79a82792f3]*/
{
if (setresuid(ruid, euid, suid) < 0)
return posix_error();
Py_RETURN_NONE;
}
#endif /* HAVE_SETRESUID */
#ifdef HAVE_SETRESGID
/*[clinic input]
os.setresgid
rgid: gid_t
egid: gid_t
sgid: gid_t
/
Set the current process's real, effective, and saved group ids.
[clinic start generated code]*/
static PyObject *
os_setresgid_impl(PyObject *module, gid_t rgid, gid_t egid, gid_t sgid)
/*[clinic end generated code: output=6aa402f3d2e514a9 input=33e9e0785ef426b1]*/
{
if (setresgid(rgid, egid, sgid) < 0)
return posix_error();
Py_RETURN_NONE;
}
#endif /* HAVE_SETRESGID */
#ifdef HAVE_GETRESUID
/*[clinic input]
os.getresuid
Return a tuple of the current process's real, effective, and saved user ids.
[clinic start generated code]*/
static PyObject *
os_getresuid_impl(PyObject *module)
/*[clinic end generated code: output=8e0becff5dece5bf input=41ccfa8e1f6517ad]*/
{
uid_t ruid, euid, suid;
if (getresuid(&ruid, &euid, &suid) < 0)
return posix_error();
return Py_BuildValue("(NNN)", _PyLong_FromUid(ruid),
_PyLong_FromUid(euid),
_PyLong_FromUid(suid));
}
#endif /* HAVE_GETRESUID */
#ifdef HAVE_GETRESGID
/*[clinic input]
os.getresgid
Return a tuple of the current process's real, effective, and saved group ids.
[clinic start generated code]*/
static PyObject *
os_getresgid_impl(PyObject *module)
/*[clinic end generated code: output=2719c4bfcf27fb9f input=517e68db9ca32df6]*/
{
gid_t rgid, egid, sgid;
if (getresgid(&rgid, &egid, &sgid) < 0)
return posix_error();
return Py_BuildValue("(NNN)", _PyLong_FromGid(rgid),
_PyLong_FromGid(egid),
_PyLong_FromGid(sgid));
}
#endif /* HAVE_GETRESGID */
#ifdef USE_XATTRS
/*[clinic input]
os.getxattr
path: path_t(allow_fd=True)
attribute: path_t
*
follow_symlinks: bool = True
Return the value of extended attribute attribute on path.
path may be either a string, a path-like object, or an open file descriptor.
If follow_symlinks is False, and the last element of the path is a symbolic
link, getxattr will examine the symbolic link itself instead of the file
the link points to.
[clinic start generated code]*/
static PyObject *
os_getxattr_impl(PyObject *module, path_t *path, path_t *attribute,
int follow_symlinks)
/*[clinic end generated code: output=5f2f44200a43cff2 input=025789491708f7eb]*/
{
Py_ssize_t i;
PyObject *buffer = NULL;
if (fd_and_follow_symlinks_invalid("getxattr", path->fd, follow_symlinks))
return NULL;
for (i = 0; ; i++) {
void *ptr;
ssize_t result;
static const Py_ssize_t buffer_sizes[] = {128, XATTR_SIZE_MAX, 0};
Py_ssize_t buffer_size = buffer_sizes[i];
if (!buffer_size) {
path_error(path);
return NULL;
}
buffer = PyBytes_FromStringAndSize(NULL, buffer_size);
if (!buffer)
return NULL;
ptr = PyBytes_AS_STRING(buffer);
Py_BEGIN_ALLOW_THREADS;
if (path->fd >= 0)
result = fgetxattr(path->fd, attribute->narrow, ptr, buffer_size);
else if (follow_symlinks)
result = getxattr(path->narrow, attribute->narrow, ptr, buffer_size);
else
result = lgetxattr(path->narrow, attribute->narrow, ptr, buffer_size);
Py_END_ALLOW_THREADS;
if (result < 0) {
Py_DECREF(buffer);
if (errno == ERANGE)
continue;
path_error(path);
return NULL;
}
if (result != buffer_size) {
/* Can only shrink. */
_PyBytes_Resize(&buffer, result);
}
break;
}
return buffer;
}
/*[clinic input]
os.setxattr
path: path_t(allow_fd=True)
attribute: path_t
value: Py_buffer
flags: int = 0
*
follow_symlinks: bool = True
Set extended attribute attribute on path to value.
path may be either a string, a path-like object, or an open file descriptor.
If follow_symlinks is False, and the last element of the path is a symbolic
link, setxattr will modify the symbolic link itself instead of the file
the link points to.
[clinic start generated code]*/
static PyObject *
os_setxattr_impl(PyObject *module, path_t *path, path_t *attribute,
Py_buffer *value, int flags, int follow_symlinks)
/*[clinic end generated code: output=98b83f63fdde26bb input=c17c0103009042f0]*/
{
ssize_t result;
if (fd_and_follow_symlinks_invalid("setxattr", path->fd, follow_symlinks))
return NULL;
Py_BEGIN_ALLOW_THREADS;
if (path->fd > -1)
result = fsetxattr(path->fd, attribute->narrow,
value->buf, value->len, flags);
else if (follow_symlinks)
result = setxattr(path->narrow, attribute->narrow,
value->buf, value->len, flags);
else
result = lsetxattr(path->narrow, attribute->narrow,
value->buf, value->len, flags);
Py_END_ALLOW_THREADS;
if (result) {
path_error(path);
return NULL;
}
Py_RETURN_NONE;
}
/*[clinic input]
os.removexattr
path: path_t(allow_fd=True)
attribute: path_t
*
follow_symlinks: bool = True
Remove extended attribute attribute on path.
path may be either a string, a path-like object, or an open file descriptor.
If follow_symlinks is False, and the last element of the path is a symbolic
link, removexattr will modify the symbolic link itself instead of the file
the link points to.
[clinic start generated code]*/
static PyObject *
os_removexattr_impl(PyObject *module, path_t *path, path_t *attribute,
int follow_symlinks)
/*[clinic end generated code: output=521a51817980cda6 input=3d9a7d36fe2f7c4e]*/
{
ssize_t result;
if (fd_and_follow_symlinks_invalid("removexattr", path->fd, follow_symlinks))
return NULL;
Py_BEGIN_ALLOW_THREADS;
if (path->fd > -1)
result = fremovexattr(path->fd, attribute->narrow);
else if (follow_symlinks)
result = removexattr(path->narrow, attribute->narrow);
else
result = lremovexattr(path->narrow, attribute->narrow);
Py_END_ALLOW_THREADS;
if (result) {
return path_error(path);
}
Py_RETURN_NONE;
}
/*[clinic input]
os.listxattr
path: path_t(allow_fd=True, nullable=True) = None
*
follow_symlinks: bool = True
Return a list of extended attributes on path.
path may be either None, a string, a path-like object, or an open file descriptor.
if path is None, listxattr will examine the current directory.
If follow_symlinks is False, and the last element of the path is a symbolic
link, listxattr will examine the symbolic link itself instead of the file
the link points to.
[clinic start generated code]*/
static PyObject *
os_listxattr_impl(PyObject *module, path_t *path, int follow_symlinks)
/*[clinic end generated code: output=bebdb4e2ad0ce435 input=9826edf9fdb90869]*/
{
Py_ssize_t i;
PyObject *result = NULL;
const char *name;
char *buffer = NULL;
if (fd_and_follow_symlinks_invalid("listxattr", path->fd, follow_symlinks))
goto exit;
name = path->narrow ? path->narrow : ".";
for (i = 0; ; i++) {
const char *start, *trace, *end;
ssize_t length;
static const Py_ssize_t buffer_sizes[] = { 256, XATTR_LIST_MAX, 0 };
Py_ssize_t buffer_size = buffer_sizes[i];
if (!buffer_size) {
/* ERANGE */
path_error(path);
break;
}
buffer = PyMem_MALLOC(buffer_size);
if (!buffer) {
PyErr_NoMemory();
break;
}
Py_BEGIN_ALLOW_THREADS;
if (path->fd > -1)
length = flistxattr(path->fd, buffer, buffer_size);
else if (follow_symlinks)
length = listxattr(name, buffer, buffer_size);
else
length = llistxattr(name, buffer, buffer_size);
Py_END_ALLOW_THREADS;
if (length < 0) {
if (errno == ERANGE) {
PyMem_FREE(buffer);
buffer = NULL;
continue;
}
path_error(path);
break;
}
result = PyList_New(0);
if (!result) {
goto exit;
}
end = buffer + length;
for (trace = start = buffer; trace != end; trace++) {
if (!*trace) {
int error;
PyObject *attribute = PyUnicode_DecodeFSDefaultAndSize(start,
trace - start);
if (!attribute) {
Py_DECREF(result);
result = NULL;
goto exit;
}
error = PyList_Append(result, attribute);
Py_DECREF(attribute);
if (error) {
Py_DECREF(result);
result = NULL;
goto exit;
}
start = trace + 1;
}
}
break;
}
exit:
if (buffer)
PyMem_FREE(buffer);
return result;
}
#endif /* USE_XATTRS */
/*[clinic input]
os.urandom
size: Py_ssize_t
/
Return a bytes object containing random bytes suitable for cryptographic use.
[clinic start generated code]*/
static PyObject *
os_urandom_impl(PyObject *module, Py_ssize_t size)
/*[clinic end generated code: output=42c5cca9d18068e9 input=4067cdb1b6776c29]*/
{
PyObject *bytes;
int result;
if (size < 0)
return PyErr_Format(PyExc_ValueError,
"negative argument not allowed");
bytes = PyBytes_FromStringAndSize(NULL, size);
if (bytes == NULL)
return NULL;
result = _PyOS_URandom(PyBytes_AS_STRING(bytes), PyBytes_GET_SIZE(bytes));
if (result == -1) {
Py_DECREF(bytes);
return NULL;
}
return bytes;
}
/* Terminal size querying */
static PyTypeObject TerminalSizeType;
PyDoc_STRVAR(TerminalSize_docstring,
"A tuple of (columns, lines) for holding terminal window size");
static PyStructSequence_Field TerminalSize_fields[] = {
{"columns", PyDoc_STR("width of the terminal window in characters")},
{"lines", PyDoc_STR("height of the terminal window in characters")},
{NULL, NULL}
};
static PyStructSequence_Desc TerminalSize_desc = {
"os.terminal_size",
TerminalSize_docstring,
TerminalSize_fields,
2,
};
/* AC 3.5: fd should accept None */
PyDoc_STRVAR(termsize__doc__,
"Return the size of the terminal window as (columns, lines).\n" \
"\n" \
"The optional argument fd (default standard output) specifies\n" \
"which file descriptor should be queried.\n" \
"\n" \
"If the file descriptor is not connected to a terminal, an OSError\n" \
"is thrown.\n" \
"\n" \
"This function will only be defined if an implementation is\n" \
"available for this system.\n" \
"\n" \
"shutil.get_terminal_size is the high-level function which should \n" \
"normally be used, os.get_terminal_size is the low-level implementation.");
static PyObject*
get_terminal_size(PyObject *self, PyObject *args)
{
struct winsize w;
int columns, lines;
PyObject *termsize;
int fd = fileno(stdout);
/* Under some conditions stdout may not be connected and
* fileno(stdout) may point to an invalid file descriptor. For example
* GUI apps don't have valid standard streams by default.
*
* If this happens, and the optional fd argument is not present,
* the ioctl below will fail returning EBADF. This is what we want.
*/
if (!PyArg_ParseTuple(args, "|i", &fd))
return NULL;
if (ioctl(fd, TIOCGWINSZ, &w))
return PyErr_SetFromErrno(PyExc_OSError);
columns = w.ws_col;
lines = w.ws_row;
termsize = PyStructSequence_New(&TerminalSizeType);
if (termsize == NULL)
return NULL;
PyStructSequence_SET_ITEM(termsize, 0, PyLong_FromLong(columns));
PyStructSequence_SET_ITEM(termsize, 1, PyLong_FromLong(lines));
if (PyErr_Occurred()) {
Py_DECREF(termsize);
return NULL;
}
return termsize;
}
/*[clinic input]
os.cpu_count
Return the number of CPUs in the system; return None if indeterminable.
This number is not equivalent to the number of CPUs the current process can
use. The number of usable CPUs can be obtained with
``len(os.sched_getaffinity(0))``
[clinic start generated code]*/
static PyObject *
os_cpu_count_impl(PyObject *module)
/*[clinic end generated code: output=5fc29463c3936a9c input=e7c8f4ba6dbbadd3]*/
{
int ncpu;
ncpu = _getcpucount();
if (ncpu >= 1)
return PyLong_FromLong(ncpu);
else
Py_RETURN_NONE;
}
/*[clinic input]
os.get_inheritable -> bool
fd: int
/
Get the close-on-exe flag of the specified file descriptor.
[clinic start generated code]*/
static int
os_get_inheritable_impl(PyObject *module, int fd)
/*[clinic end generated code: output=0445e20e149aa5b8 input=89ac008dc9ab6b95]*/
{
int return_value;
_Py_BEGIN_SUPPRESS_IPH
return_value = _Py_get_inheritable(fd);
_Py_END_SUPPRESS_IPH
return return_value;
}
/*[clinic input]
os.set_inheritable
fd: int
inheritable: int
/
Set the inheritable flag of the specified file descriptor.
[clinic start generated code]*/
static PyObject *
os_set_inheritable_impl(PyObject *module, int fd, int inheritable)
/*[clinic end generated code: output=f1b1918a2f3c38c2 input=9ceaead87a1e2402]*/
{
int result;
_Py_BEGIN_SUPPRESS_IPH
result = _Py_set_inheritable(fd, inheritable, NULL);
_Py_END_SUPPRESS_IPH
if (result < 0)
return NULL;
Py_RETURN_NONE;
}
#ifdef MS_WINDOWS
/*[clinic input]
os.get_handle_inheritable -> bool
handle: intptr_t
/
Get the close-on-exe flag of the specified file descriptor.
[clinic start generated code]*/
static int
os_get_handle_inheritable_impl(PyObject *module, intptr_t handle)
/*[clinic end generated code: output=36be5afca6ea84d8 input=cfe99f9c05c70ad1]*/
{
DWORD flags;
if (!GetHandleInformation((HANDLE)handle, &flags)) {
PyErr_SetFromWindowsErr(0);
return -1;
}
return flags & HANDLE_FLAG_INHERIT;
}
/*[clinic input]
os.set_handle_inheritable
handle: intptr_t
inheritable: bool
/
Set the inheritable flag of the specified handle.
[clinic start generated code]*/
static PyObject *
os_set_handle_inheritable_impl(PyObject *module, intptr_t handle,
int inheritable)
/*[clinic end generated code: output=021d74fe6c96baa3 input=7a7641390d8364fc]*/
{
DWORD flags = inheritable ? HANDLE_FLAG_INHERIT : 0;
if (!SetHandleInformation((HANDLE)handle, HANDLE_FLAG_INHERIT, flags)) {
PyErr_SetFromWindowsErr(0);
return NULL;
}
Py_RETURN_NONE;
}
#endif /* MS_WINDOWS */
#ifndef MS_WINDOWS
PyDoc_STRVAR(get_blocking__doc__,
"get_blocking(fd) -> bool\n" \
"\n" \
"Get the blocking mode of the file descriptor:\n" \
"False if the O_NONBLOCK flag is set, True if the flag is cleared.");
static PyObject*
posix_get_blocking(PyObject *self, PyObject *args)
{
int fd;
int blocking;
if (!PyArg_ParseTuple(args, "i:get_blocking", &fd))
return NULL;
_Py_BEGIN_SUPPRESS_IPH
blocking = _Py_get_blocking(fd);
_Py_END_SUPPRESS_IPH
if (blocking < 0)
return NULL;
return PyBool_FromLong(blocking);
}
PyDoc_STRVAR(set_blocking__doc__,
"set_blocking(fd, blocking)\n" \
"\n" \
"Set the blocking mode of the specified file descriptor.\n" \
"Set the O_NONBLOCK flag if blocking is False,\n" \
"clear the O_NONBLOCK flag otherwise.");
static PyObject*
posix_set_blocking(PyObject *self, PyObject *args)
{
int fd, blocking, result;
if (!PyArg_ParseTuple(args, "ii:set_blocking", &fd, &blocking))
return NULL;
_Py_BEGIN_SUPPRESS_IPH
result = _Py_set_blocking(fd, blocking);
_Py_END_SUPPRESS_IPH
if (result < 0)
return NULL;
Py_RETURN_NONE;
}
#endif /* !MS_WINDOWS */
PyDoc_STRVAR(posix_scandir__doc__,
"scandir(path='.') -> iterator of DirEntry objects for given path");
static char *follow_symlinks_keywords[] = {"follow_symlinks", NULL};
typedef struct {
PyObject_HEAD
PyObject *name;
PyObject *path;
PyObject *stat;
PyObject *lstat;
#ifdef MS_WINDOWS
struct _Py_stat_struct win32_lstat;
uint64_t win32_file_index;
int got_file_index;
#else /* POSIX */
#ifdef HAVE_DIRENT_D_TYPE
unsigned char d_type;
#endif
ino_t d_ino;
#endif
} DirEntry;
static void
DirEntry_dealloc(DirEntry *entry)
{
Py_XDECREF(entry->name);
Py_XDECREF(entry->path);
Py_XDECREF(entry->stat);
Py_XDECREF(entry->lstat);
Py_TYPE(entry)->tp_free((PyObject *)entry);
}
/* Forward reference */
static int
DirEntry_test_mode(DirEntry *self, int follow_symlinks, unsigned short mode_bits);
/* Set exception and return -1 on error, 0 for False, 1 for True */
static int
DirEntry_is_symlink(DirEntry *self)
{
#ifdef MS_WINDOWS
return (self->win32_lstat.st_mode & S_IFMT) == S_IFLNK;
#elif defined(HAVE_DIRENT_D_TYPE)
/* POSIX */
if (self->d_type != DT_UNKNOWN)
return self->d_type == DT_LNK;
else
return DirEntry_test_mode(self, 0, S_IFLNK);
#else
/* POSIX without d_type */
return DirEntry_test_mode(self, 0, S_IFLNK);
#endif
}
static PyObject *
DirEntry_py_is_symlink(DirEntry *self)
{
int result;
result = DirEntry_is_symlink(self);
if (result == -1)
return NULL;
return PyBool_FromLong(result);
}
static PyObject *
DirEntry_fetch_stat(DirEntry *self, int follow_symlinks)
{
int result;
STRUCT_STAT st;
PyObject *ub;
#ifdef MS_WINDOWS
if (PyUnicode_FSDecoder(self->path, &ub)) {
const wchar_t *path = PyUnicode_AsUnicode(ub);
#else /* POSIX */
if (PyUnicode_FSConverter(self->path, &ub)) {
const char *path = PyBytes_AS_STRING(ub);
#endif
if (follow_symlinks)
result = STAT(path, &st);
else
result = LSTAT(path, &st);
Py_DECREF(ub);
} else
return NULL;
if (result != 0)
return path_object_error(self->path);
return _pystat_fromstructstat(&st);
}
static PyObject *
DirEntry_get_lstat(DirEntry *self)
{
if (!self->lstat) {
#ifdef MS_WINDOWS
self->lstat = _pystat_fromstructstat(&self->win32_lstat);
#else /* POSIX */
self->lstat = DirEntry_fetch_stat(self, 0);
#endif
}
Py_XINCREF(self->lstat);
return self->lstat;
}
static PyObject *
DirEntry_get_stat(DirEntry *self, int follow_symlinks)
{
if (!follow_symlinks)
return DirEntry_get_lstat(self);
if (!self->stat) {
int result = DirEntry_is_symlink(self);
if (result == -1)
return NULL;
else if (result)
self->stat = DirEntry_fetch_stat(self, 1);
else
self->stat = DirEntry_get_lstat(self);
}
Py_XINCREF(self->stat);
return self->stat;
}
static PyObject *
DirEntry_stat(DirEntry *self, PyObject *args, PyObject *kwargs)
{
int follow_symlinks = 1;
if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|$p:DirEntry.stat",
follow_symlinks_keywords, &follow_symlinks))
return NULL;
return DirEntry_get_stat(self, follow_symlinks);
}
/* Set exception and return -1 on error, 0 for False, 1 for True */
static int
DirEntry_test_mode(DirEntry *self, int follow_symlinks, unsigned short mode_bits)
{
PyObject *stat = NULL;
PyObject *st_mode = NULL;
long mode;
int result;
#if defined(MS_WINDOWS) || defined(HAVE_DIRENT_D_TYPE)
int is_symlink;
int need_stat;
#endif
#ifdef MS_WINDOWS
unsigned long dir_bits;
#endif
_Py_IDENTIFIER(st_mode);
#ifdef MS_WINDOWS
is_symlink = (self->win32_lstat.st_mode & S_IFMT) == S_IFLNK;
need_stat = follow_symlinks && is_symlink;
#elif defined(HAVE_DIRENT_D_TYPE)
is_symlink = self->d_type == DT_LNK;
need_stat = self->d_type == DT_UNKNOWN || (follow_symlinks && is_symlink);
#endif
#if defined(MS_WINDOWS) || defined(HAVE_DIRENT_D_TYPE)
if (need_stat) {
#endif
stat = DirEntry_get_stat(self, follow_symlinks);
if (!stat) {
if (PyErr_ExceptionMatches(PyExc_FileNotFoundError)) {
/* If file doesn't exist (anymore), then return False
(i.e., say it's not a file/directory) */
PyErr_Clear();
return 0;
}
goto error;
}
st_mode = _PyObject_GetAttrId(stat, &PyId_st_mode);
if (!st_mode)
goto error;
mode = PyLong_AsLong(st_mode);
if (mode == -1 && PyErr_Occurred())
goto error;
Py_CLEAR(st_mode);
Py_CLEAR(stat);
result = (mode & S_IFMT) == mode_bits;
#if defined(MS_WINDOWS) || defined(HAVE_DIRENT_D_TYPE)
}
else if (is_symlink) {
assert(mode_bits != S_IFLNK);
result = 0;
}
else {
assert(mode_bits == S_IFDIR || mode_bits == S_IFREG);
#ifdef MS_WINDOWS
dir_bits = self->win32_lstat.st_file_attributes & FILE_ATTRIBUTE_DIRECTORY;
if (mode_bits == S_IFDIR)
result = dir_bits != 0;
else
result = dir_bits == 0;
#else /* POSIX */
if (mode_bits == S_IFDIR)
result = self->d_type == DT_DIR;
else
result = self->d_type == DT_REG;
#endif
}
#endif
return result;
error:
Py_XDECREF(st_mode);
Py_XDECREF(stat);
return -1;
}
static PyObject *
DirEntry_py_test_mode(DirEntry *self, int follow_symlinks, unsigned short mode_bits)
{
int result;
result = DirEntry_test_mode(self, follow_symlinks, mode_bits);
if (result == -1)
return NULL;
return PyBool_FromLong(result);
}
static PyObject *
DirEntry_is_dir(DirEntry *self, PyObject *args, PyObject *kwargs)
{
int follow_symlinks = 1;
if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|$p:DirEntry.is_dir",
follow_symlinks_keywords, &follow_symlinks))
return NULL;
return DirEntry_py_test_mode(self, follow_symlinks, S_IFDIR);
}
static PyObject *
DirEntry_is_file(DirEntry *self, PyObject *args, PyObject *kwargs)
{
int follow_symlinks = 1;
if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|$p:DirEntry.is_file",
follow_symlinks_keywords, &follow_symlinks))
return NULL;
return DirEntry_py_test_mode(self, follow_symlinks, S_IFREG);
}
static PyObject *
DirEntry_inode(DirEntry *self)
{
#ifdef MS_WINDOWS
if (!self->got_file_index) {
PyObject *unicode;
const wchar_t *path;
STRUCT_STAT stat;
int result;
if (!PyUnicode_FSDecoder(self->path, &unicode))
return NULL;
path = PyUnicode_AsUnicode(unicode);
result = LSTAT(path, &stat);
Py_DECREF(unicode);
if (result != 0)
return path_object_error(self->path);
self->win32_file_index = stat.st_ino;
self->got_file_index = 1;
}
Py_BUILD_ASSERT(sizeof(unsigned long long) >= sizeof(self->win32_file_index));
return PyLong_FromUnsignedLongLong(self->win32_file_index);
#else /* POSIX */
Py_BUILD_ASSERT(sizeof(unsigned long long) >= sizeof(self->d_ino));
return PyLong_FromUnsignedLongLong(self->d_ino);
#endif
}
static PyObject *
DirEntry_repr(DirEntry *self)
{
return PyUnicode_FromFormat("<DirEntry %R>", self->name);
}
static PyObject *
DirEntry_fspath(DirEntry *self)
{
Py_INCREF(self->path);
return self->path;
}
static PyMemberDef DirEntry_members[] = {
{"name", T_OBJECT_EX, offsetof(DirEntry, name), READONLY,
PyDoc_STR("the entry's base filename, relative to scandir() \"path\" argument")},
{"path", T_OBJECT_EX, offsetof(DirEntry, path), READONLY,
PyDoc_STR("the entry's full path name; equivalent to os.path.join(scandir_path, entry.name)")},
{NULL}
};
static PyMethodDef DirEntry_methods[] = {
{"is_dir", (PyCFunction)DirEntry_is_dir, METH_VARARGS | METH_KEYWORDS,
PyDoc_STR("is_dir($self)\n--\n\nreturn True if entry is a directory; cached per entry")},
{"is_file", (PyCFunction)DirEntry_is_file, METH_VARARGS | METH_KEYWORDS,
PyDoc_STR("is_file($self)\n--\n\nreturn True if the entry is a file; cached per entry")},
{"is_symlink", (PyCFunction)DirEntry_py_is_symlink, METH_NOARGS,
PyDoc_STR("is_symlink($self)\n--\n\nreturn True if the entry is a symbolic link; cached per entry")},
{"stat", (PyCFunction)DirEntry_stat, METH_VARARGS | METH_KEYWORDS,
PyDoc_STR("is_stat($self)\n--\n\nreturn stat_result object for the entry; cached per entry")},
{"inode", (PyCFunction)DirEntry_inode, METH_NOARGS,
PyDoc_STR("inode($self)\n--\n\nreturn inode of the entry; cached per entry")},
{"__fspath__", (PyCFunction)DirEntry_fspath, METH_NOARGS,
PyDoc_STR("__fspath__($self)\n--\n\nreturns the path for the entry")},
{NULL}
};
static PyTypeObject DirEntryType = {
PyVarObject_HEAD_INIT(NULL, 0)
MODNAME ".DirEntry", /* tp_name */
sizeof(DirEntry), /* tp_basicsize */
0, /* tp_itemsize */
/* methods */
(destructor)DirEntry_dealloc, /* tp_dealloc */
0, /* tp_print */
0, /* tp_getattr */
0, /* tp_setattr */
0, /* tp_compare */
(reprfunc)DirEntry_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 */
DirEntry_methods, /* tp_methods */
DirEntry_members, /* tp_members */
};
#ifdef MS_WINDOWS
static wchar_t *
join_path_filenameW(const wchar_t *path_wide, const wchar_t *filename)
{
Py_ssize_t path_len;
Py_ssize_t size;
wchar_t *result;
wchar_t ch;
if (!path_wide) { /* Default arg: "." */
path_wide = L".";
path_len = 1;
}
else {
path_len = wcslen(path_wide);
}
/* The +1's are for the path separator and the NUL */
size = path_len + 1 + wcslen(filename) + 1;
result = PyMem_New(wchar_t, size);
if (!result) {
PyErr_NoMemory();
return NULL;
}
wcscpy(result, path_wide);
if (path_len > 0) {
ch = result[path_len - 1];
if (ch != SEP && ch != ALTSEP && ch != L':')
result[path_len++] = SEP;
wcscpy(result + path_len, filename);
}
return result;
}
static PyObject *
DirEntry_from_find_data(path_t *path, WIN32_FIND_DATAW *dataW)
{
DirEntry *entry;
BY_HANDLE_FILE_INFORMATION file_info;
ULONG reparse_tag;
wchar_t *joined_path;
entry = PyObject_New(DirEntry, &DirEntryType);
if (!entry)
return NULL;
entry->name = NULL;
entry->path = NULL;
entry->stat = NULL;
entry->lstat = NULL;
entry->got_file_index = 0;
entry->name = PyUnicode_FromWideChar(dataW->cFileName, -1);
if (!entry->name)
goto error;
if (path->narrow) {
Py_SETREF(entry->name, PyUnicode_EncodeFSDefault(entry->name));
if (!entry->name)
goto error;
}
joined_path = join_path_filenameW(path->wide, dataW->cFileName);
if (!joined_path)
goto error;
entry->path = PyUnicode_FromWideChar(joined_path, -1);
PyMem_Free(joined_path);
if (!entry->path)
goto error;
if (path->narrow) {
Py_SETREF(entry->path, PyUnicode_EncodeFSDefault(entry->path));
if (!entry->path)
goto error;
}
find_data_to_file_info(dataW, &file_info, &reparse_tag);
_Py_attribute_data_to_stat(&file_info, reparse_tag, &entry->win32_lstat);
return (PyObject *)entry;
error:
Py_DECREF(entry);
return NULL;
}
#else /* POSIX */
static char *
join_path_filename(const char *path_narrow, const char* filename, Py_ssize_t filename_len)
{
Py_ssize_t path_len;
Py_ssize_t size;
char *result;
if (!path_narrow) { /* Default arg: "." */
path_narrow = ".";
path_len = 1;
}
else {
path_len = strlen(path_narrow);
}
if (filename_len == -1)
filename_len = strlen(filename);
/* The +1's are for the path separator and the NUL */
size = path_len + 1 + filename_len + 1;
result = PyMem_New(char, size);
if (!result) {
PyErr_NoMemory();
return NULL;
}
strcpy(result, path_narrow);
if (path_len > 0 && result[path_len - 1] != '/')
result[path_len++] = '/';
strcpy(result + path_len, filename);
return result;
}
static PyObject *
DirEntry_from_posix_info(path_t *path, const char *name, Py_ssize_t name_len,
ino_t d_ino
#ifdef HAVE_DIRENT_D_TYPE
, unsigned char d_type
#endif
)
{
DirEntry *entry;
char *joined_path;
entry = PyObject_New(DirEntry, &DirEntryType);
if (!entry)
return NULL;
entry->name = NULL;
entry->path = NULL;
entry->stat = NULL;
entry->lstat = NULL;
joined_path = join_path_filename(path->narrow, name, name_len);
if (!joined_path)
goto error;
if (!path->narrow || !PyObject_CheckBuffer(path->object)) {
entry->name = PyUnicode_DecodeFSDefaultAndSize(name, name_len);
entry->path = PyUnicode_DecodeFSDefault(joined_path);
}
else {
entry->name = PyBytes_FromStringAndSize(name, name_len);
entry->path = PyBytes_FromString(joined_path);
}
PyMem_Free(joined_path);
if (!entry->name || !entry->path)
goto error;
#ifdef HAVE_DIRENT_D_TYPE
entry->d_type = d_type;
#endif
entry->d_ino = d_ino;
return (PyObject *)entry;
error:
Py_XDECREF(entry);
return NULL;
}
#endif
typedef struct {
PyObject_HEAD
path_t path;
#ifdef MS_WINDOWS
HANDLE handle;
WIN32_FIND_DATAW file_data;
int first_time;
#else /* POSIX */
DIR *dirp;
#endif
} ScandirIterator;
#ifdef MS_WINDOWS
static int
ScandirIterator_is_closed(ScandirIterator *iterator)
{
return iterator->handle == INVALID_HANDLE_VALUE;
}
static void
ScandirIterator_closedir(ScandirIterator *iterator)
{
HANDLE handle = iterator->handle;
if (handle == INVALID_HANDLE_VALUE)
return;
iterator->handle = INVALID_HANDLE_VALUE;
Py_BEGIN_ALLOW_THREADS
FindClose(handle);
Py_END_ALLOW_THREADS
}
static PyObject *
ScandirIterator_iternext(ScandirIterator *iterator)
{
WIN32_FIND_DATAW *file_data = &iterator->file_data;
BOOL success;
PyObject *entry;
/* Happens if the iterator is iterated twice, or closed explicitly */
if (iterator->handle == INVALID_HANDLE_VALUE)
return NULL;
while (1) {
if (!iterator->first_time) {
Py_BEGIN_ALLOW_THREADS
success = FindNextFileW(iterator->handle, file_data);
Py_END_ALLOW_THREADS
if (!success) {
/* Error or no more files */
if (GetLastError() != ERROR_NO_MORE_FILES)
path_error(&iterator->path);
break;
}
}
iterator->first_time = 0;
/* Skip over . and .. */
if (wcscmp(file_data->cFileName, L".") != 0 &&
wcscmp(file_data->cFileName, L"..") != 0) {
entry = DirEntry_from_find_data(&iterator->path, file_data);
if (!entry)
break;
return entry;
}
/* Loop till we get a non-dot directory or finish iterating */
}
/* Error or no more files */
ScandirIterator_closedir(iterator);
return NULL;
}
#else /* POSIX */
static int
ScandirIterator_is_closed(ScandirIterator *iterator)
{
return !iterator->dirp;
}
static void
ScandirIterator_closedir(ScandirIterator *iterator)
{
DIR *dirp = iterator->dirp;
if (!dirp)
return;
iterator->dirp = NULL;
Py_BEGIN_ALLOW_THREADS
closedir(dirp);
Py_END_ALLOW_THREADS
return;
}
static PyObject *
ScandirIterator_iternext(ScandirIterator *iterator)
{
struct dirent *direntp;
Py_ssize_t name_len;
int is_dot;
PyObject *entry;
/* Happens if the iterator is iterated twice, or closed explicitly */
if (!iterator->dirp)
return NULL;
while (1) {
errno = 0;
Py_BEGIN_ALLOW_THREADS
direntp = readdir(iterator->dirp);
Py_END_ALLOW_THREADS
if (!direntp) {
/* Error or no more files */
if (errno != 0)
path_error(&iterator->path);
break;
}
/* Skip over . and .. */
name_len = NAMLEN(direntp);
is_dot = direntp->d_name[0] == '.' &&
(name_len == 1 || (direntp->d_name[1] == '.' && name_len == 2));
if (!is_dot) {
entry = DirEntry_from_posix_info(&iterator->path, direntp->d_name,
name_len, direntp->d_ino
#ifdef HAVE_DIRENT_D_TYPE
, direntp->d_type
#endif
);
if (!entry)
break;
return entry;
}
/* Loop till we get a non-dot directory or finish iterating */
}
/* Error or no more files */
ScandirIterator_closedir(iterator);
return NULL;
}
#endif
static PyObject *
ScandirIterator_close(ScandirIterator *self, PyObject *args)
{
ScandirIterator_closedir(self);
Py_RETURN_NONE;
}
static PyObject *
ScandirIterator_enter(PyObject *self, PyObject *args)
{
Py_INCREF(self);
return self;
}
static PyObject *
ScandirIterator_exit(ScandirIterator *self, PyObject *args)
{
ScandirIterator_closedir(self);
Py_RETURN_NONE;
}
static void
ScandirIterator_finalize(ScandirIterator *iterator)
{
PyObject *error_type, *error_value, *error_traceback;
/* Save the current exception, if any. */
PyErr_Fetch(&error_type, &error_value, &error_traceback);
if (!ScandirIterator_is_closed(iterator)) {
ScandirIterator_closedir(iterator);
if (PyErr_ResourceWarning((PyObject *)iterator, 1,
"unclosed scandir iterator %R", iterator)) {
/* Spurious errors can appear at shutdown */
if (PyErr_ExceptionMatches(PyExc_Warning)) {
PyErr_WriteUnraisable((PyObject *) iterator);
}
}
}
path_cleanup(&iterator->path);
/* Restore the saved exception. */
PyErr_Restore(error_type, error_value, error_traceback);
}
static void
ScandirIterator_dealloc(ScandirIterator *iterator)
{
if (PyObject_CallFinalizerFromDealloc((PyObject *)iterator) < 0)
return;
Py_TYPE(iterator)->tp_free((PyObject *)iterator);
}
static PyMethodDef ScandirIterator_methods[] = {
{"__enter__", (PyCFunction)ScandirIterator_enter, METH_NOARGS},
{"__exit__", (PyCFunction)ScandirIterator_exit, METH_VARARGS},
{"close", (PyCFunction)ScandirIterator_close, METH_NOARGS},
{NULL}
};
static PyTypeObject ScandirIteratorType = {
PyVarObject_HEAD_INIT(NULL, 0)
MODNAME ".ScandirIterator", /* tp_name */
sizeof(ScandirIterator), /* tp_basicsize */
0, /* tp_itemsize */
/* methods */
(destructor)ScandirIterator_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_FINALIZE, /* tp_flags */
0, /* tp_doc */
0, /* tp_traverse */
0, /* tp_clear */
0, /* tp_richcompare */
0, /* tp_weaklistoffset */
PyObject_SelfIter, /* tp_iter */
(iternextfunc)ScandirIterator_iternext, /* tp_iternext */
ScandirIterator_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 */
0, /* tp_bases */
0, /* tp_mro */
0, /* tp_cache */
0, /* tp_subclasses */
0, /* tp_weaklist */
0, /* tp_del */
0, /* tp_version_tag */
(destructor)ScandirIterator_finalize, /* tp_finalize */
};
static PyObject *
posix_scandir(PyObject *self, PyObject *args, PyObject *kwargs)
{
ScandirIterator *iterator;
static char *keywords[] = {"path", NULL};
const char *path;
iterator = PyObject_New(ScandirIterator, &ScandirIteratorType);
if (!iterator)
return NULL;
bzero(&iterator->path, sizeof(path_t));
iterator->path.function_name = "scandir";
iterator->path.nullable = 1;
iterator->dirp = NULL;
if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|O&:scandir", keywords,
path_converter, &iterator->path))
goto error;
if (iterator->path.narrow)
path = iterator->path.narrow;
else
path = ".";
errno = 0;
Py_BEGIN_ALLOW_THREADS
iterator->dirp = opendir(path);
Py_END_ALLOW_THREADS
if (!iterator->dirp) {
path_error(&iterator->path);
goto error;
}
return (PyObject *)iterator;
error:
Py_DECREF(iterator);
return NULL;
}
/*[clinic input]
os.fspath
path: object
Return the file system path representation of the object.
If the object is str or bytes, then allow it to pass through as-is. If the
object defines __fspath__(), then return the result of that method. All other
types raise a TypeError.
[clinic start generated code]*/
static PyObject *
os_fspath_impl(PyObject *module, PyObject *path)
/*[clinic end generated code: output=c3c3b78ecff2914f input=e357165f7b22490f]*/
{
return PyOS_FSPath(path);
}
#ifdef HAVE_GETRANDOM_SYSCALL
/*[clinic input]
os.getrandom
size: Py_ssize_t
flags: int=0
Obtain a series of random bytes.
[clinic start generated code]*/
static PyObject *
os_getrandom_impl(PyObject *module, Py_ssize_t size, int flags)
/*[clinic end generated code: output=b3a618196a61409c input=59bafac39c594947]*/
{
PyObject *bytes;
Py_ssize_t n;
if (size < 0) {
errno = EINVAL;
return posix_error();
}
bytes = PyBytes_FromStringAndSize(NULL, size);
if (bytes == NULL) {
PyErr_NoMemory();
return NULL;
}
while (1) {
n = syscall(SYS_getrandom,
PyBytes_AS_STRING(bytes),
PyBytes_GET_SIZE(bytes),
flags);
if (n < 0 && errno == EINTR) {
if (PyErr_CheckSignals() < 0) {
goto error;
}
/* getrandom() was interrupted by a signal: retry */
continue;
}
break;
}
if (n < 0) {
PyErr_SetFromErrno(PyExc_OSError);
goto error;
}
if (n != size) {
_PyBytes_Resize(&bytes, n);
}
return bytes;
error:
Py_DECREF(bytes);
return NULL;
}
#endif /* HAVE_GETRANDOM_SYSCALL */
#include "third_party/python/Modules/clinic/posixmodule.inc"
/*[clinic input]
dump buffer
[clinic start generated code]*/
/*[clinic end generated code: output=da39a3ee5e6b4b0d input=524ce2e021e4eba6]*/
static PyMethodDef posix_methods[] = {
OS_STAT_METHODDEF
OS_ACCESS_METHODDEF
OS_TTYNAME_METHODDEF
OS_CHDIR_METHODDEF
OS_CHFLAGS_METHODDEF
OS_CHMOD_METHODDEF
OS_FCHMOD_METHODDEF
OS_LCHMOD_METHODDEF
OS_CHOWN_METHODDEF
OS_FCHOWN_METHODDEF
OS_LCHOWN_METHODDEF
OS_LCHFLAGS_METHODDEF
OS_CHROOT_METHODDEF
OS_CTERMID_METHODDEF
OS_GETCWD_METHODDEF
OS_GETCWDB_METHODDEF
OS_LINK_METHODDEF
OS_LISTDIR_METHODDEF
OS_LSTAT_METHODDEF
OS_MKDIR_METHODDEF
OS_NICE_METHODDEF
OS_GETPRIORITY_METHODDEF
OS_SETPRIORITY_METHODDEF
#ifdef HAVE_READLINK
{"readlink", (PyCFunction)posix_readlink,
METH_VARARGS | METH_KEYWORDS,
readlink__doc__},
#endif /* HAVE_READLINK */
#if !defined(HAVE_READLINK) && defined(MS_WINDOWS)
{"readlink", (PyCFunction)win_readlink,
METH_VARARGS | METH_KEYWORDS,
readlink__doc__},
#endif /* !defined(HAVE_READLINK) && defined(MS_WINDOWS) */
OS_RENAME_METHODDEF
OS_REPLACE_METHODDEF
OS_RMDIR_METHODDEF
{"stat_float_times", stat_float_times, METH_VARARGS, stat_float_times__doc__},
OS_SYMLINK_METHODDEF
OS_SYSTEM_METHODDEF
OS_UMASK_METHODDEF
OS_UNAME_METHODDEF
OS_UNLINK_METHODDEF
OS_REMOVE_METHODDEF
OS_UTIME_METHODDEF
OS_TIMES_METHODDEF
OS__EXIT_METHODDEF
OS_EXECV_METHODDEF
OS_EXECVE_METHODDEF
OS_SPAWNV_METHODDEF
OS_SPAWNVE_METHODDEF
OS_FORK1_METHODDEF
OS_FORK_METHODDEF
OS_SCHED_GET_PRIORITY_MAX_METHODDEF
OS_SCHED_GET_PRIORITY_MIN_METHODDEF
OS_SCHED_GETPARAM_METHODDEF
OS_SCHED_GETSCHEDULER_METHODDEF
OS_SCHED_RR_GET_INTERVAL_METHODDEF
OS_SCHED_SETPARAM_METHODDEF
OS_SCHED_SETSCHEDULER_METHODDEF
OS_SCHED_YIELD_METHODDEF
OS_SCHED_SETAFFINITY_METHODDEF
OS_SCHED_GETAFFINITY_METHODDEF
OS_OPENPTY_METHODDEF
OS_FORKPTY_METHODDEF
OS_GETEGID_METHODDEF
OS_GETEUID_METHODDEF
OS_GETGID_METHODDEF
#ifdef HAVE_GETGROUPLIST
{"getgrouplist", posix_getgrouplist, METH_VARARGS, posix_getgrouplist__doc__},
#endif
OS_GETGROUPS_METHODDEF
OS_GETPID_METHODDEF
OS_GETPGRP_METHODDEF
OS_GETPPID_METHODDEF
OS_GETUID_METHODDEF
OS_GETLOGIN_METHODDEF
OS_KILL_METHODDEF
OS_KILLPG_METHODDEF
OS_PLOCK_METHODDEF
#ifdef MS_WINDOWS
OS_STARTFILE_METHODDEF
#endif
OS_SETUID_METHODDEF
OS_SETEUID_METHODDEF
OS_SETREUID_METHODDEF
OS_SETGID_METHODDEF
OS_SETEGID_METHODDEF
OS_SETREGID_METHODDEF
OS_SETGROUPS_METHODDEF
#ifdef HAVE_INITGROUPS
{"initgroups", posix_initgroups, METH_VARARGS, posix_initgroups__doc__},
#endif /* HAVE_INITGROUPS */
OS_GETPGID_METHODDEF
OS_SETPGRP_METHODDEF
OS_WAIT_METHODDEF
OS_WAIT3_METHODDEF
OS_WAIT4_METHODDEF
OS_WAITID_METHODDEF
OS_WAITPID_METHODDEF
OS_GETSID_METHODDEF
OS_SETSID_METHODDEF
OS_SETPGID_METHODDEF
OS_TCGETPGRP_METHODDEF
OS_TCSETPGRP_METHODDEF
OS_OPEN_METHODDEF
OS_CLOSE_METHODDEF
OS_CLOSERANGE_METHODDEF
OS_DEVICE_ENCODING_METHODDEF
OS_DUP_METHODDEF
OS_DUP2_METHODDEF
OS_LOCKF_METHODDEF
OS_LSEEK_METHODDEF
OS_READ_METHODDEF
OS_READV_METHODDEF
OS_PREAD_METHODDEF
OS_WRITE_METHODDEF
OS_WRITEV_METHODDEF
OS_PWRITE_METHODDEF
#ifdef HAVE_SENDFILE
{"sendfile", (PyCFunction)posix_sendfile, METH_VARARGS | METH_KEYWORDS,
posix_sendfile__doc__},
#endif
OS_FSTAT_METHODDEF
OS_ISATTY_METHODDEF
OS_PIPE_METHODDEF
OS_PIPE2_METHODDEF
OS_MKFIFO_METHODDEF
OS_MKNOD_METHODDEF
OS_MAJOR_METHODDEF
OS_MINOR_METHODDEF
OS_MAKEDEV_METHODDEF
OS_FTRUNCATE_METHODDEF
OS_TRUNCATE_METHODDEF
OS_POSIX_FALLOCATE_METHODDEF
OS_POSIX_FADVISE_METHODDEF
OS_PUTENV_METHODDEF
OS_UNSETENV_METHODDEF
OS_STRERROR_METHODDEF
OS_FCHDIR_METHODDEF
OS_FSYNC_METHODDEF
OS_SYNC_METHODDEF
OS_FDATASYNC_METHODDEF
OS_WCOREDUMP_METHODDEF
OS_WIFCONTINUED_METHODDEF
OS_WIFSTOPPED_METHODDEF
OS_WIFSIGNALED_METHODDEF
OS_WIFEXITED_METHODDEF
OS_WEXITSTATUS_METHODDEF
OS_WTERMSIG_METHODDEF
OS_WSTOPSIG_METHODDEF
OS_FSTATVFS_METHODDEF
OS_STATVFS_METHODDEF
OS_CONFSTR_METHODDEF
OS_SYSCONF_METHODDEF
OS_FPATHCONF_METHODDEF
OS_PATHCONF_METHODDEF
OS_ABORT_METHODDEF
OS__GETFULLPATHNAME_METHODDEF
OS__ISDIR_METHODDEF
OS__GETDISKUSAGE_METHODDEF
OS__GETFINALPATHNAME_METHODDEF
OS__GETVOLUMEPATHNAME_METHODDEF
OS_GETLOADAVG_METHODDEF
OS_URANDOM_METHODDEF
OS_SETRESUID_METHODDEF
OS_SETRESGID_METHODDEF
OS_GETRESUID_METHODDEF
OS_GETRESGID_METHODDEF
OS_GETXATTR_METHODDEF
OS_SETXATTR_METHODDEF
OS_REMOVEXATTR_METHODDEF
OS_LISTXATTR_METHODDEF
{"get_terminal_size", get_terminal_size, METH_VARARGS, termsize__doc__},
OS_CPU_COUNT_METHODDEF
OS_GET_INHERITABLE_METHODDEF
OS_SET_INHERITABLE_METHODDEF
OS_GET_HANDLE_INHERITABLE_METHODDEF
OS_SET_HANDLE_INHERITABLE_METHODDEF
#ifndef MS_WINDOWS
{"get_blocking", posix_get_blocking, METH_VARARGS, get_blocking__doc__},
{"set_blocking", posix_set_blocking, METH_VARARGS, set_blocking__doc__},
#endif
{"scandir", (PyCFunction)posix_scandir,
METH_VARARGS | METH_KEYWORDS,
posix_scandir__doc__},
OS_FSPATH_METHODDEF
OS_GETRANDOM_METHODDEF
{NULL, NULL} /* Sentinel */
};
static int
all_ins(PyObject *m)
{
if (PyModule_AddIntMacro(m, F_OK)) return -1;
if (PyModule_AddIntMacro(m, R_OK)) return -1;
if (PyModule_AddIntMacro(m, W_OK)) return -1;
if (PyModule_AddIntMacro(m, X_OK)) return -1;
#ifdef NGROUPS_MAX
if (PyModule_AddIntMacro(m, NGROUPS_MAX)) return -1;
#endif
#ifdef TMP_MAX
if (PyModule_AddIntMacro(m, TMP_MAX)) return -1;
#endif
if (PyModule_AddIntMacro(m, WNOHANG)) return -1;
if (WUNTRACED && PyModule_AddIntMacro(m, WUNTRACED)) return -1;
if (WCONTINUED && PyModule_AddIntMacro(m, WCONTINUED)) return -1;
if (PyModule_AddIntMacro(m, O_RDONLY)) return -1;
if (PyModule_AddIntMacro(m, O_WRONLY)) return -1;
if (PyModule_AddIntMacro(m, O_RDWR)) return -1;
if (PyModule_AddIntMacro(m, O_ACCMODE)) return -1;
if (PyModule_AddIntMacro(m, O_NDELAY)) return -1;
if (PyModule_AddIntMacro(m, O_NONBLOCK)) return -1;
if (PyModule_AddIntMacro(m, O_APPEND)) return -1;
if (PyModule_AddIntMacro(m, O_CLOEXEC)) return -1;
if (PyModule_AddIntMacro(m, O_CREAT)) return -1;
if (PyModule_AddIntMacro(m, O_DIRECTORY)) return -1;
if (PyModule_AddIntMacro(m, O_LARGEFILE)) return -1;
if (PyModule_AddIntMacro(m, O_EXCL)) return -1;
if (O_DSYNC && PyModule_AddIntMacro(m, O_DSYNC)) return -1;
if (O_RSYNC && PyModule_AddIntMacro(m, O_RSYNC)) return -1;
if (O_SYNC && PyModule_AddIntMacro(m, O_SYNC)) return -1;
if (O_NOCTTY && PyModule_AddIntMacro(m, O_NOCTTY)) return -1;
if (O_TRUNC && PyModule_AddIntMacro(m, O_TRUNC)) return -1;
if (O_EXEC && PyModule_AddIntMacro(m, O_EXEC)) return -1;
if (O_SEARCH && PyModule_AddIntMacro(m, O_SEARCH)) return -1;
if (O_SHLOCK && PyModule_AddIntMacro(m, O_SHLOCK)) return -1;
if (O_EXLOCK && PyModule_AddIntMacro(m, O_EXLOCK)) return -1;
if (O_TTY_INIT && PyModule_AddIntMacro(m, O_TTY_INIT)) return -1;
if (O_TMPFILE && PyModule_AddIntMacro(m, O_TMPFILE)) return -1;
if (O_PATH && PyModule_AddIntMacro(m, O_PATH)) return -1;
if (O_RANDOM && PyModule_AddIntMacro(m, O_RANDOM)) return -1;
if (O_SEQUENTIAL && PyModule_AddIntMacro(m, O_SEQUENTIAL)) return -1;
if (O_ASYNC && PyModule_AddIntMacro(m, O_ASYNC)) return -1;
if (O_DIRECT && PyModule_AddIntMacro(m, O_DIRECT)) return -1;
if (O_NOFOLLOW && PyModule_AddIntMacro(m, O_NOFOLLOW)) return -1;
if (O_NOFOLLOW_ANY && PyModule_AddIntMacro(m, O_NOFOLLOW_ANY)) return -1;
if (O_NOATIME && PyModule_AddIntMacro(m, O_NOATIME)) return -1;
if (O_VERIFY && PyModule_AddIntMacro(m, O_VERIFY)) return -1;
if (IsWindows() && PyModule_AddIntConstant(m, "O_SHORT_LIVED", kNtFileAttributeTemporary)) return -1;
if (IsWindows() && PyModule_AddIntConstant(m, "O_TEMPORARY", kNtFileFlagDeleteOnClose)) return -1;
#ifdef O_BINARY
if (PyModule_AddIntMacro(m, O_BINARY)) return -1;
#endif
#ifdef O_TEXT
if (PyModule_AddIntMacro(m, O_TEXT)) return -1;
#endif
#ifdef O_XATTR
if (PyModule_AddIntMacro(m, O_XATTR)) return -1;
#endif
#ifdef O_NOINHERIT
if (PyModule_AddIntMacro(m, O_NOINHERIT)) return -1;
#endif
if (PyModule_AddIntMacro(m, PRIO_PROCESS)) return -1;
if (PyModule_AddIntMacro(m, PRIO_PGRP)) return -1;
if (PyModule_AddIntMacro(m, PRIO_USER)) return -1;
#ifdef SEEK_HOLE
if (PyModule_AddIntMacro(m, SEEK_HOLE)) return -1;
#endif
#ifdef SEEK_DATA
if (PyModule_AddIntMacro(m, SEEK_DATA)) return -1;
#endif
/* These come from sysexits.h */
if (PyModule_AddIntMacro(m, EX_OK)) return -1;
if (PyModule_AddIntMacro(m, EX_USAGE)) return -1;
if (PyModule_AddIntMacro(m, EX_DATAERR)) return -1;
if (PyModule_AddIntMacro(m, EX_NOINPUT)) return -1;
if (PyModule_AddIntMacro(m, EX_NOUSER)) return -1;
if (PyModule_AddIntMacro(m, EX_NOHOST)) return -1;
if (PyModule_AddIntMacro(m, EX_UNAVAILABLE)) return -1;
if (PyModule_AddIntMacro(m, EX_SOFTWARE)) return -1;
if (PyModule_AddIntMacro(m, EX_OSERR)) return -1;
if (PyModule_AddIntMacro(m, EX_OSFILE)) return -1;
if (PyModule_AddIntMacro(m, EX_CANTCREAT)) return -1;
if (PyModule_AddIntMacro(m, EX_IOERR)) return -1;
if (PyModule_AddIntMacro(m, EX_TEMPFAIL)) return -1;
if (PyModule_AddIntMacro(m, EX_PROTOCOL)) return -1;
if (PyModule_AddIntMacro(m, EX_NOPERM)) return -1;
if (PyModule_AddIntMacro(m, EX_CONFIG)) return -1;
#if defined(HAVE_STATVFS) || defined(HAVE_FSTATVFS)
/* statvfs */
if (ST_RDONLY && PyModule_AddIntMacro(m, ST_RDONLY)) return -1;
if (ST_NOSUID && PyModule_AddIntMacro(m, ST_NOSUID)) return -1;
if (ST_NODEV && PyModule_AddIntMacro(m, ST_NODEV)) return -1;
if (ST_NOEXEC && PyModule_AddIntMacro(m, ST_NOEXEC)) return -1;
if (ST_SYNCHRONOUS && PyModule_AddIntMacro(m, ST_SYNCHRONOUS)) return -1;
if (ST_MANDLOCK && PyModule_AddIntMacro(m, ST_MANDLOCK)) return -1;
if (ST_WRITE && PyModule_AddIntMacro(m, ST_WRITE)) return -1;
if (ST_APPEND && PyModule_AddIntMacro(m, ST_APPEND)) return -1;
if (ST_NOATIME && PyModule_AddIntMacro(m, ST_NOATIME)) return -1;
if (ST_NODIRATIME && PyModule_AddIntMacro(m, ST_NODIRATIME)) return -1;
if (ST_RELATIME && PyModule_AddIntMacro(m, ST_RELATIME)) return -1;
#endif
/* FreeBSD sendfile() constants */
if (SF_NODISKIO && PyModule_AddIntMacro(m, SF_NODISKIO)) return -1;
if (SF_MNOWAIT && PyModule_AddIntMacro(m, SF_MNOWAIT)) return -1;
if (SF_SYNC && PyModule_AddIntMacro(m, SF_SYNC)) return -1;
/* constants for posix_fadvise */
if (PyModule_AddIntMacro(m, POSIX_FADV_NORMAL)) return -1;
if (POSIX_FADV_SEQUENTIAL && PyModule_AddIntMacro(m, POSIX_FADV_SEQUENTIAL)) return -1;
if (POSIX_FADV_RANDOM && PyModule_AddIntMacro(m, POSIX_FADV_RANDOM)) return -1;
if (POSIX_FADV_NOREUSE && PyModule_AddIntMacro(m, POSIX_FADV_NOREUSE)) return -1;
if (POSIX_FADV_WILLNEED && PyModule_AddIntMacro(m, POSIX_FADV_WILLNEED)) return -1;
if (POSIX_FADV_DONTNEED && PyModule_AddIntMacro(m, POSIX_FADV_DONTNEED)) return -1;
/* constants for waitid */
#if defined(HAVE_WAITID)
if (P_PID && PyModule_AddIntMacro(m, P_PID)) return -1;
if (P_PGID && PyModule_AddIntMacro(m, P_PGID)) return -1;
if (P_ALL && PyModule_AddIntMacro(m, P_ALL)) return -1;
#endif
if (WEXITED && PyModule_AddIntMacro(m, WEXITED)) return -1;
if (WNOWAIT && PyModule_AddIntMacro(m, WNOWAIT)) return -1;
if (WSTOPPED && PyModule_AddIntMacro(m, WSTOPPED)) return -1;
if (PyModule_AddIntMacro(m, CLD_EXITED)) return -1;
if (PyModule_AddIntMacro(m, CLD_DUMPED)) return -1;
if (PyModule_AddIntMacro(m, CLD_TRAPPED)) return -1;
if (PyModule_AddIntMacro(m, CLD_CONTINUED)) return -1;
/* constants for lockf */
if (PyModule_AddIntMacro(m, F_LOCK)) return -1;
if (PyModule_AddIntMacro(m, F_TLOCK)) return -1;
if (PyModule_AddIntMacro(m, F_ULOCK)) return -1;
if (PyModule_AddIntMacro(m, F_TEST)) return -1;
#ifdef HAVE_SPAWNV
if (PyModule_AddIntConstant(m, "P_WAIT", _P_WAIT)) return -1;
if (PyModule_AddIntConstant(m, "P_NOWAIT", _P_NOWAIT)) return -1;
if (PyModule_AddIntConstant(m, "P_OVERLAY", _OLD_P_OVERLAY)) return -1;
if (PyModule_AddIntConstant(m, "P_NOWAITO", _P_NOWAITO)) return -1;
if (PyModule_AddIntConstant(m, "P_DETACH", _P_DETACH)) return -1;
#endif
#ifdef SCHED_OTHER
if (PyModule_AddIntMacro(m, SCHED_OTHER)) return -1;
#endif
#ifdef SCHED_FIFO
if (PyModule_AddIntMacro(m, SCHED_FIFO)) return -1;
#endif
#ifdef SCHED_RR
if (PyModule_AddIntMacro(m, SCHED_RR)) return -1;
#endif
#ifdef SCHED_SPORADIC
if (PyModule_AddIntMacro(m, SCHED_SPORADIC)) return -1;
#endif
#ifdef SCHED_BATCH
if (PyModule_AddIntMacro(m, SCHED_BATCH)) return -1;
#endif
#ifdef SCHED_IDLE
if (PyModule_AddIntMacro(m, SCHED_IDLE)) return -1;
#endif
#ifdef SCHED_RESET_ON_FORK
if (PyModule_AddIntMacro(m, SCHED_RESET_ON_FORK)) return -1;
#endif
#ifdef SCHED_SYS
if (PyModule_AddIntMacro(m, SCHED_SYS)) return -1;
#endif
#ifdef SCHED_IA
if (PyModule_AddIntMacro(m, SCHED_IA)) return -1;
#endif
#ifdef SCHED_FSS
if (PyModule_AddIntMacro(m, SCHED_FSS)) return -1;
#endif
#ifdef SCHED_FX
if (PyModule_AddIntConstant(m, "SCHED_FX", SCHED_FSS)) return -1;
#endif
#ifdef USE_XATTRS
if (PyModule_AddIntMacro(m, XATTR_CREATE)) return -1;
if (PyModule_AddIntMacro(m, XATTR_REPLACE)) return -1;
if (PyModule_AddIntMacro(m, XATTR_SIZE_MAX)) return -1;
#endif
#if HAVE_DECL_RTLD_LAZY
if (PyModule_AddIntMacro(m, RTLD_LAZY)) return -1;
#endif
#if HAVE_DECL_RTLD_NOW
if (PyModule_AddIntMacro(m, RTLD_NOW)) return -1;
#endif
#if HAVE_DECL_RTLD_GLOBAL
if (PyModule_AddIntMacro(m, RTLD_GLOBAL)) return -1;
#endif
#if HAVE_DECL_RTLD_LOCAL
if (PyModule_AddIntMacro(m, RTLD_LOCAL)) return -1;
#endif
#if HAVE_DECL_RTLD_NODELETE
if (PyModule_AddIntMacro(m, RTLD_NODELETE)) return -1;
#endif
#if HAVE_DECL_RTLD_NOLOAD
if (PyModule_AddIntMacro(m, RTLD_NOLOAD)) return -1;
#endif
#if HAVE_DECL_RTLD_DEEPBIND
if (PyModule_AddIntMacro(m, RTLD_DEEPBIND)) return -1;
#endif
if (PyModule_AddIntMacro(m, GRND_RANDOM)) return -1;
if (PyModule_AddIntMacro(m, GRND_NONBLOCK)) return -1;
return 0;
}
static struct PyModuleDef posixmodule = {
PyModuleDef_HEAD_INIT,
MODNAME,
posix__doc__,
-1,
posix_methods,
NULL,
NULL,
NULL,
NULL
};
static const char * const have_functions[] = {
#ifdef HAVE_FACCESSAT
"HAVE_FACCESSAT",
#endif
#ifdef HAVE_FCHDIR
"HAVE_FCHDIR",
#endif
#ifdef HAVE_FCHMOD
"HAVE_FCHMOD",
#endif
#ifdef HAVE_FCHMODAT
"HAVE_FCHMODAT",
#endif
#ifdef HAVE_FCHOWN
"HAVE_FCHOWN",
#endif
#ifdef HAVE_FCHOWNAT
"HAVE_FCHOWNAT",
#endif
#ifdef HAVE_FEXECVE
"HAVE_FEXECVE",
#endif
#ifdef HAVE_FDOPENDIR
"HAVE_FDOPENDIR",
#endif
#ifdef HAVE_FPATHCONF
"HAVE_FPATHCONF",
#endif
#ifdef HAVE_FSTATAT
"HAVE_FSTATAT",
#endif
#ifdef HAVE_FSTATVFS
"HAVE_FSTATVFS",
#endif
#if defined HAVE_FTRUNCATE || defined MS_WINDOWS
"HAVE_FTRUNCATE",
#endif
#ifdef HAVE_FUTIMENS
"HAVE_FUTIMENS",
#endif
#ifdef HAVE_FUTIMES
"HAVE_FUTIMES",
#endif
#ifdef HAVE_FUTIMESAT
"HAVE_FUTIMESAT",
#endif
#ifdef HAVE_LINKAT
"HAVE_LINKAT",
#endif
#ifdef HAVE_LCHFLAGS
"HAVE_LCHFLAGS",
#endif
#ifdef HAVE_LCHMOD
"HAVE_LCHMOD",
#endif
#ifdef HAVE_LCHOWN
"HAVE_LCHOWN",
#endif
#ifdef HAVE_LSTAT
"HAVE_LSTAT",
#endif
#ifdef HAVE_LUTIMES
"HAVE_LUTIMES",
#endif
#ifdef HAVE_MKDIRAT
"HAVE_MKDIRAT",
#endif
#ifdef HAVE_MKFIFOAT
"HAVE_MKFIFOAT",
#endif
#ifdef HAVE_MKNODAT
"HAVE_MKNODAT",
#endif
#ifdef HAVE_OPENAT
"HAVE_OPENAT",
#endif
#ifdef HAVE_READLINKAT
"HAVE_READLINKAT",
#endif
#ifdef HAVE_RENAMEAT
"HAVE_RENAMEAT",
#endif
#ifdef HAVE_SYMLINKAT
"HAVE_SYMLINKAT",
#endif
#ifdef HAVE_UNLINKAT
"HAVE_UNLINKAT",
#endif
#ifdef HAVE_UTIMENSAT
"HAVE_UTIMENSAT",
#endif
#ifdef MS_WINDOWS
"MS_WINDOWS",
#endif
NULL
};
PyMODINIT_FUNC
INITFUNC(void)
{
PyObject *m, *v;
PyObject *list;
const char * const *trace;
m = PyModule_Create(&posixmodule);
if (m == NULL)
return NULL;
/* Initialize environ dictionary */
v = convertenviron();
Py_XINCREF(v);
if (v == NULL || PyModule_AddObject(m, "environ", v) != 0)
return NULL;
Py_DECREF(v);
if (all_ins(m))
return NULL;
if (setup_confname_tables(m))
return NULL;
Py_INCREF(PyExc_OSError);
PyModule_AddObject(m, "error", PyExc_OSError);
#ifdef HAVE_PUTENV
if (posix_putenv_garbage == NULL)
posix_putenv_garbage = PyDict_New();
#endif
if (!initialized) {
#if defined(HAVE_WAITID) && !defined(__APPLE__)
waitid_result_desc.name = MODNAME ".waitid_result";
if (PyStructSequence_InitType2(&WaitidResultType, &waitid_result_desc) < 0)
return NULL;
#endif
stat_result_desc.name = "os.stat_result"; /* see issue #19209 */
stat_result_desc.fields[7].name = PyStructSequence_UnnamedField;
stat_result_desc.fields[8].name = PyStructSequence_UnnamedField;
stat_result_desc.fields[9].name = PyStructSequence_UnnamedField;
if (PyStructSequence_InitType2(&StatResultType, &stat_result_desc) < 0)
return NULL;
structseq_new = StatResultType.tp_new;
StatResultType.tp_new = statresult_new;
statvfs_result_desc.name = "os.statvfs_result"; /* see issue #19209 */
if (PyStructSequence_InitType2(&StatVFSResultType,
&statvfs_result_desc) < 0)
return NULL;
ticks_per_second = sysconf(_SC_CLK_TCK);
#if defined(HAVE_SCHED_SETPARAM) || defined(HAVE_SCHED_SETSCHEDULER)
sched_param_desc.name = MODNAME ".sched_param";
if (PyStructSequence_InitType2(&SchedParamType, &sched_param_desc) < 0)
return NULL;
SchedParamType.tp_new = os_sched_param;
#endif
/* initialize TerminalSize_info */
if (PyStructSequence_InitType2(&TerminalSizeType,
&TerminalSize_desc) < 0)
return NULL;
/* initialize scandir types */
if (PyType_Ready(&ScandirIteratorType) < 0)
return NULL;
if (PyType_Ready(&DirEntryType) < 0)
return NULL;
}
#if defined(HAVE_WAITID) && !defined(__APPLE__)
Py_INCREF((PyObject*) &WaitidResultType);
PyModule_AddObject(m, "waitid_result", (PyObject*) &WaitidResultType);
#endif
Py_INCREF((PyObject*) &StatResultType);
PyModule_AddObject(m, "stat_result", (PyObject*) &StatResultType);
Py_INCREF((PyObject*) &StatVFSResultType);
PyModule_AddObject(m, "statvfs_result",
(PyObject*) &StatVFSResultType);
#if defined(HAVE_SCHED_SETPARAM) || defined(HAVE_SCHED_SETSCHEDULER)
Py_INCREF(&SchedParamType);
PyModule_AddObject(m, "sched_param", (PyObject *)&SchedParamType);
#endif
times_result_desc.name = MODNAME ".times_result";
if (PyStructSequence_InitType2(&TimesResultType, ×_result_desc) < 0)
return NULL;
PyModule_AddObject(m, "times_result", (PyObject *)&TimesResultType);
uname_result_desc.name = MODNAME ".uname_result";
if (PyStructSequence_InitType2(&UnameResultType, &uname_result_desc) < 0)
return NULL;
PyModule_AddObject(m, "uname_result", (PyObject *)&UnameResultType);
Py_INCREF(&TerminalSizeType);
PyModule_AddObject(m, "terminal_size", (PyObject*) &TerminalSizeType);
billion = PyLong_FromLong(1000000000);
if (!billion)
return NULL;
if (IsWindows()) {
if (PyObject_DelAttrString(m, "lchown") == -1) return NULL;
if (PyObject_DelAttrString(m, "chown") == -1) return NULL;
}
/* suppress "function not used" warnings */
{
int ignored;
fd_specified("", -1);
follow_symlinks_specified("", 1);
dir_fd_and_follow_symlinks_invalid("chmod", DEFAULT_DIR_FD, 1);
dir_fd_converter(Py_None, &ignored);
dir_fd_unavailable(Py_None, &ignored);
}
/*
* provide list of locally available functions
* so os.py can populate support_* lists
*/
list = PyList_New(0);
if (!list)
return NULL;
for (trace = have_functions; *trace; trace++) {
PyObject *unicode = PyUnicode_DecodeASCII(*trace, strlen(*trace), NULL);
if (!unicode)
return NULL;
if (PyList_Append(list, unicode))
return NULL;
Py_DECREF(unicode);
}
PyModule_AddObject(m, "_have_functions", list);
Py_INCREF((PyObject *) &DirEntryType);
PyModule_AddObject(m, "DirEntry", (PyObject *)&DirEntryType);
initialized = 1;
return m;
}
| 329,439 | 12,231 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Modules/unicodedata_nfcnfkc.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:8;coding:utf-8 -*-â
âvi: set net ft=c ts=4 sts=4 sw=4 fenc=utf-8 :viâ
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ¡
â Python 3 â
â https://docs.python.org/3/license.html â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
#include "libc/intrin/bits.h"
#include "libc/intrin/likely.h"
#include "third_party/python/Include/pyerrors.h"
#include "third_party/python/Include/pymem.h"
#include "third_party/python/Modules/unicodedata.h"
#include "third_party/python/Modules/unicodedata_unidata.h"
/* clang-format off */
PyObject *
_PyUnicode_NfcNfkc(PyObject *self, PyObject *input, int k)
{
int kind;
void *data;
Py_UCS4 code;
Py_UCS4 *output;
PyObject *result;
int cskipped = 0;
Py_ssize_t skipped[20];
Py_ssize_t i, i1, o, len;
int f,l,index,index1,comb;
result = _PyUnicode_NfdNfkd(self, input, k);
if (!result)
return NULL;
/* result will be "ready". */
kind = PyUnicode_KIND(result);
data = PyUnicode_DATA(result);
len = PyUnicode_GET_LENGTH(result);
/* We allocate a buffer for the output.
If we find that we made no changes, we still return
the NFD result. */
output = PyMem_NEW(Py_UCS4, len);
if (!output) {
PyErr_NoMemory();
Py_DECREF(result);
return 0;
}
i = o = 0;
again:
while (i < len) {
for (index = 0; index < cskipped; index++) {
if (skipped[index] == i) {
/* *i character is skipped.
Remove from list. */
skipped[index] = skipped[cskipped-1];
cskipped--;
i++;
goto again; /* continue while */
}
}
/* Hangul Composition. We don't need to check for <LV,T>
pairs, since we always have decomposed data. */
code = PyUnicode_READ(kind, data, i);
if ((UNLIKELY(_Hanghoul_LBase <= code && code < _Hanghoul_LBase + _Hanghoul_LCount) &&
i + 1 < len && _Hanghoul_VBase <= PyUnicode_READ(kind, data, i+1) &&
PyUnicode_READ(kind, data, i+1) < _Hanghoul_VBase + _Hanghoul_VCount)) {
/* check L character is a modern leading consonant (0x1100 ~ 0x1112)
and V character is a modern vowel (0x1161 ~ 0x1175). */
int LIndex, VIndex;
LIndex = code - _Hanghoul_LBase;
VIndex = PyUnicode_READ(kind, data, i+1) - _Hanghoul_VBase;
code = _Hanghoul_SBase + (LIndex * _Hanghoul_VCount + VIndex) * _Hanghoul_TCount;
i+=2;
if ((i < len &&
_Hanghoul_TBase < PyUnicode_READ(kind, data, i) &&
PyUnicode_READ(kind, data, i) < (_Hanghoul_TBase + _Hanghoul_TCount))) {
/* check T character is a modern trailing consonant
(0x11A8 ~ 0x11C2). */
code += PyUnicode_READ(kind, data, i) - _Hanghoul_TBase;
i++;
}
output[o++] = code;
continue;
}
/* code is still input[i] here */
f = _PyUnicode_FindNfcIndex(_PyUnicode_NfcFirst, code);
if (f == -1) {
output[o++] = code;
i++;
continue;
}
/* Find next unblocked character. */
i1 = i+1;
comb = 0;
/* output base character for now; might be updated later. */
output[o] = PyUnicode_READ(kind, data, i);
while (i1 < len) {
Py_UCS4 code1 = PyUnicode_READ(kind, data, i1);
int comb1 = _PyUnicode_GetRecord(code1)->combining;
if (comb) {
if (comb1 == 0)
break;
if (comb >= comb1) {
/* Character is blocked. */
i1++;
continue;
}
}
l = _PyUnicode_FindNfcIndex(_PyUnicode_NfcLast, code1);
/* i1 cannot be combined with i. If i1
is a starter, we don't need to look further.
Otherwise, record the combining class. */
if (l == -1) {
not_combinable:
if (comb1 == 0)
break;
comb = comb1;
i1++;
continue;
}
index = f * UNIDATA_TOTAL_LAST + l;
index1 = _PyUnicode_CompIndex[index >> _PyUnicode_CompShift];
code = _bextra(_PyUnicode_CompData,
(index1 << _PyUnicode_CompShift)+
(index & ((1 << _PyUnicode_CompShift) - 1)),
_PyUnicode_CompDataBits);
if (code == 0)
goto not_combinable;
/* Replace the original character. */
output[o] = code;
/* Mark the second character unused. */
assert(cskipped < 20);
skipped[cskipped++] = i1;
i1++;
f = _PyUnicode_FindNfcIndex(_PyUnicode_NfcFirst, output[o]);
if (f == -1)
break;
}
/* Output character was already written.
Just advance the indices. */
o++; i++;
}
if (o == len) {
/* No changes. Return original string. */
PyMem_Free(output);
return result;
}
Py_DECREF(result);
result = PyUnicode_FromKindAndData(PyUnicode_4BYTE_KIND,
output, o);
PyMem_Free(output);
return result;
}
| 5,862 | 149 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Modules/_elementtree.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:8;coding:utf-8 -*-â
âvi: set net ft=c ts=4 sts=4 sw=4 fenc=utf-8 :viâ
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ¡
â Python 3 â
â https://docs.python.org/3/license.html â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
#define PY_SSIZE_T_CLEAN
#include "third_party/python/Include/abstract.h"
#include "third_party/python/Include/bytesobject.h"
#include "third_party/python/Include/descrobject.h"
#include "third_party/python/Include/dictobject.h"
#include "third_party/python/Include/import.h"
#include "third_party/python/Include/listobject.h"
#include "third_party/python/Include/longobject.h"
#include "third_party/python/Include/modsupport.h"
#include "third_party/python/Include/moduleobject.h"
#include "third_party/python/Include/object.h"
#include "third_party/python/Include/objimpl.h"
#include "third_party/python/Include/pycapsule.h"
#include "third_party/python/Include/pyexpat.h"
#include "third_party/python/Include/pyhash.h"
#include "third_party/python/Include/pystate.h"
#include "third_party/python/Include/sliceobject.h"
#include "third_party/python/Include/structmember.h"
#include "third_party/python/Include/warnings.h"
#include "third_party/python/Include/yoink.h"
#include "third_party/python/Modules/expat/expat.h"
/* clang-format off */
PYTHON_PROVIDE("_elementtree");
PYTHON_PROVIDE("_elementtree.Element");
PYTHON_PROVIDE("_elementtree.ParseError");
PYTHON_PROVIDE("_elementtree.SubElement");
PYTHON_PROVIDE("_elementtree.TreeBuilder");
PYTHON_PROVIDE("_elementtree.XMLParser");
/*--------------------------------------------------------------------
* Licensed to PSF under a Contributor Agreement.
* See http://www.python.org/psf/license for licensing details.
*
* _elementtree - C accelerator for xml.etree.ElementTree
* Copyright (c) 1999-2009 by Secret Labs AB. All rights reserved.
* Copyright (c) 1999-2009 by Fredrik Lundh.
*
* [email protected]
* http://www.pythonware.com
*--------------------------------------------------------------------
*/
/* -------------------------------------------------------------------- */
/* configuration */
/* An element can hold this many children without extra memory
allocations. */
#define STATIC_CHILDREN 4
/* For best performance, chose a value so that 80-90% of all nodes
have no more than the given number of children. Set this to zero
to minimize the size of the element structure itself (this only
helps if you have lots of leaf nodes with attributes). */
/* Also note that pymalloc always allocates blocks in multiples of
eight bytes. For the current C version of ElementTree, this means
that the number of children should be an even number, at least on
32-bit platforms. */
/* -------------------------------------------------------------------- */
#if 0
static int memory = 0;
#define ALLOC(size, comment)\
do { memory += size; printf("%8d - %s\n", memory, comment); } while (0)
#define RELEASE(size, comment)\
do { memory -= size; printf("%8d - %s\n", memory, comment); } while (0)
#else
#define ALLOC(size, comment)
#define RELEASE(size, comment)
#endif
/* compiler tweaks */
#if defined(_MSC_VER)
#define LOCAL(type) static __inline type __fastcall
#else
#define LOCAL(type) static type
#endif
/* macros used to store 'join' flags in string object pointers. note
that all use of text and tail as object pointers must be wrapped in
JOIN_OBJ. see comments in the ElementObject definition for more
info. */
#define JOIN_GET(p) ((uintptr_t) (p) & 1)
#define JOIN_SET(p, flag) ((void*) ((uintptr_t) (JOIN_OBJ(p)) | (flag)))
#define JOIN_OBJ(p) ((PyObject*) ((uintptr_t) (p) & ~(uintptr_t)1))
/* Py_SETREF for a PyObject* that uses a join flag. */
Py_LOCAL_INLINE(void)
_set_joined_ptr(PyObject **p, PyObject *new_joined_ptr)
{
PyObject *tmp = JOIN_OBJ(*p);
*p = new_joined_ptr;
Py_DECREF(tmp);
}
/* Py_CLEAR for a PyObject* that uses a join flag. Pass the pointer by
* reference since this function sets it to NULL.
*/
static void _clear_joined_ptr(PyObject **p)
{
if (*p) {
_set_joined_ptr(p, NULL);
}
}
/* Types defined by this extension */
static PyTypeObject Element_Type;
static PyTypeObject ElementIter_Type;
static PyTypeObject TreeBuilder_Type;
static PyTypeObject XMLParser_Type;
/* Per-module state; PEP 3121 */
typedef struct {
PyObject *parseerror_obj;
PyObject *deepcopy_obj;
PyObject *elementpath_obj;
} elementtreestate;
static struct PyModuleDef elementtreemodule;
/* Given a module object (assumed to be _elementtree), get its per-module
* state.
*/
#define ET_STATE(mod) ((elementtreestate *) PyModule_GetState(mod))
/* Find the module instance imported in the currently running sub-interpreter
* and get its state.
*/
#define ET_STATE_GLOBAL \
((elementtreestate *) PyModule_GetState(PyState_FindModule(&elementtreemodule)))
static int
elementtree_clear(PyObject *m)
{
elementtreestate *st = ET_STATE(m);
Py_CLEAR(st->parseerror_obj);
Py_CLEAR(st->deepcopy_obj);
Py_CLEAR(st->elementpath_obj);
return 0;
}
static int
elementtree_traverse(PyObject *m, visitproc visit, void *arg)
{
elementtreestate *st = ET_STATE(m);
Py_VISIT(st->parseerror_obj);
Py_VISIT(st->deepcopy_obj);
Py_VISIT(st->elementpath_obj);
return 0;
}
static void
elementtree_free(void *m)
{
elementtree_clear((PyObject *)m);
}
/* helpers */
LOCAL(PyObject*)
list_join(PyObject* list)
{
/* join list elements */
PyObject* joiner;
PyObject* result;
joiner = PyUnicode_FromStringAndSize("", 0);
if (!joiner)
return NULL;
result = PyUnicode_Join(joiner, list);
Py_DECREF(joiner);
return result;
}
/* Is the given object an empty dictionary?
*/
static int
is_empty_dict(PyObject *obj)
{
return PyDict_CheckExact(obj) && PyDict_Size(obj) == 0;
}
/* -------------------------------------------------------------------- */
/* the Element type */
typedef struct {
/* attributes (a dictionary object), or None if no attributes */
PyObject* attrib;
/* child elements */
Py_ssize_t length; /* actual number of items */
Py_ssize_t allocated; /* allocated items */
/* this either points to _children or to a malloced buffer */
PyObject* *children;
PyObject* _children[STATIC_CHILDREN];
} ElementObjectExtra;
typedef struct {
PyObject_HEAD
/* element tag (a string). */
PyObject* tag;
/* text before first child. note that this is a tagged pointer;
use JOIN_OBJ to get the object pointer. the join flag is used
to distinguish lists created by the tree builder from lists
assigned to the attribute by application code; the former
should be joined before being returned to the user, the latter
should be left intact. */
PyObject* text;
/* text after this element, in parent. note that this is a tagged
pointer; use JOIN_OBJ to get the object pointer. */
PyObject* tail;
ElementObjectExtra* extra;
PyObject *weakreflist; /* For tp_weaklistoffset */
} ElementObject;
#define Element_CheckExact(op) (Py_TYPE(op) == &Element_Type)
#define Element_Check(op) PyObject_TypeCheck(op, &Element_Type)
/* -------------------------------------------------------------------- */
/* Element constructors and destructor */
LOCAL(int)
create_extra(ElementObject* self, PyObject* attrib)
{
self->extra = PyObject_Malloc(sizeof(ElementObjectExtra));
if (!self->extra) {
PyErr_NoMemory();
return -1;
}
if (!attrib)
attrib = Py_None;
Py_INCREF(attrib);
self->extra->attrib = attrib;
self->extra->length = 0;
self->extra->allocated = STATIC_CHILDREN;
self->extra->children = self->extra->_children;
return 0;
}
LOCAL(void)
dealloc_extra(ElementObjectExtra *extra)
{
Py_ssize_t i;
if (!extra)
return;
Py_DECREF(extra->attrib);
for (i = 0; i < extra->length; i++)
Py_DECREF(extra->children[i]);
if (extra->children != extra->_children)
PyObject_Free(extra->children);
PyObject_Free(extra);
}
LOCAL(void)
clear_extra(ElementObject* self)
{
ElementObjectExtra *myextra;
if (!self->extra)
return;
/* Avoid DECREFs calling into this code again (cycles, etc.)
*/
myextra = self->extra;
self->extra = NULL;
dealloc_extra(myextra);
}
/* Convenience internal function to create new Element objects with the given
* tag and attributes.
*/
LOCAL(PyObject*)
create_new_element(PyObject* tag, PyObject* attrib)
{
ElementObject* self;
self = PyObject_GC_New(ElementObject, &Element_Type);
if (self == NULL)
return NULL;
self->extra = NULL;
Py_INCREF(tag);
self->tag = tag;
Py_INCREF(Py_None);
self->text = Py_None;
Py_INCREF(Py_None);
self->tail = Py_None;
self->weakreflist = NULL;
ALLOC(sizeof(ElementObject), "create element");
PyObject_GC_Track(self);
if (attrib != Py_None && !is_empty_dict(attrib)) {
if (create_extra(self, attrib) < 0) {
Py_DECREF(self);
return NULL;
}
}
return (PyObject*) self;
}
static PyObject *
element_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
ElementObject *e = (ElementObject *)type->tp_alloc(type, 0);
if (e != NULL) {
Py_INCREF(Py_None);
e->tag = Py_None;
Py_INCREF(Py_None);
e->text = Py_None;
Py_INCREF(Py_None);
e->tail = Py_None;
e->extra = NULL;
e->weakreflist = NULL;
}
return (PyObject *)e;
}
/* Helper function for extracting the attrib dictionary from a keywords dict.
* This is required by some constructors/functions in this module that can
* either accept attrib as a keyword argument or all attributes splashed
* directly into *kwds.
*
* Return a dictionary with the content of kwds merged into the content of
* attrib. If there is no attrib keyword, return a copy of kwds.
*/
static PyObject*
get_attrib_from_keywords(PyObject *kwds)
{
PyObject *attrib_str = PyUnicode_FromString("attrib");
if (attrib_str == NULL) {
return NULL;
}
PyObject *attrib = PyDict_GetItem(kwds, attrib_str);
if (attrib) {
/* If attrib was found in kwds, copy its value and remove it from
* kwds
*/
if (!PyDict_Check(attrib)) {
Py_DECREF(attrib_str);
PyErr_Format(PyExc_TypeError, "attrib must be dict, not %.100s",
Py_TYPE(attrib)->tp_name);
return NULL;
}
attrib = PyDict_Copy(attrib);
if (attrib && PyDict_DelItem(kwds, attrib_str) < 0) {
Py_DECREF(attrib);
attrib = NULL;
}
} else {
attrib = PyDict_New();
}
Py_DECREF(attrib_str);
if (attrib != NULL && PyDict_Update(attrib, kwds) < 0) {
Py_DECREF(attrib);
return NULL;
}
return attrib;
}
/*[clinic input]
module _elementtree
class _elementtree.Element "ElementObject *" "&Element_Type"
class _elementtree.TreeBuilder "TreeBuilderObject *" "&TreeBuilder_Type"
class _elementtree.XMLParser "XMLParserObject *" "&XMLParser_Type"
[clinic start generated code]*/
/*[clinic end generated code: output=da39a3ee5e6b4b0d input=159aa50a54061c22]*/
static int
element_init(PyObject *self, PyObject *args, PyObject *kwds)
{
PyObject *tag;
PyObject *attrib = NULL;
ElementObject *self_elem;
if (!PyArg_ParseTuple(args, "O|O!:Element", &tag, &PyDict_Type, &attrib))
return -1;
if (attrib) {
/* attrib passed as positional arg */
attrib = PyDict_Copy(attrib);
if (!attrib)
return -1;
if (kwds) {
if (PyDict_Update(attrib, kwds) < 0) {
Py_DECREF(attrib);
return -1;
}
}
} else if (kwds) {
/* have keywords args */
attrib = get_attrib_from_keywords(kwds);
if (!attrib)
return -1;
}
self_elem = (ElementObject *)self;
if (attrib != NULL && !is_empty_dict(attrib)) {
if (create_extra(self_elem, attrib) < 0) {
Py_DECREF(attrib);
return -1;
}
}
/* We own a reference to attrib here and it's no longer needed. */
Py_XDECREF(attrib);
/* Replace the objects already pointed to by tag, text and tail. */
Py_INCREF(tag);
Py_XSETREF(self_elem->tag, tag);
Py_INCREF(Py_None);
_set_joined_ptr(&self_elem->text, Py_None);
Py_INCREF(Py_None);
_set_joined_ptr(&self_elem->tail, Py_None);
return 0;
}
LOCAL(int)
element_resize(ElementObject* self, Py_ssize_t extra)
{
Py_ssize_t size;
PyObject* *children;
assert(extra >= 0);
/* make sure self->children can hold the given number of extra
elements. set an exception and return -1 if allocation failed */
if (!self->extra) {
if (create_extra(self, NULL) < 0)
return -1;
}
size = self->extra->length + extra; /* never overflows */
if (size > self->extra->allocated) {
/* use Python 2.4's list growth strategy */
size = (size >> 3) + (size < 9 ? 3 : 6) + size;
/* Coverity CID #182 size_error: Allocating 1 bytes to pointer "children"
* which needs at least 4 bytes.
* Although it's a false alarm always assume at least one child to
* be safe.
*/
size = size ? size : 1;
if ((size_t)size > PY_SSIZE_T_MAX/sizeof(PyObject*))
goto nomemory;
if (self->extra->children != self->extra->_children) {
/* Coverity CID #182 size_error: Allocating 1 bytes to pointer
* "children", which needs at least 4 bytes. Although it's a
* false alarm always assume at least one child to be safe.
*/
children = PyObject_Realloc(self->extra->children,
size * sizeof(PyObject*));
if (!children)
goto nomemory;
} else {
children = PyObject_Malloc(size * sizeof(PyObject*));
if (!children)
goto nomemory;
/* copy existing children from static area to malloc buffer */
memcpy(children, self->extra->children,
self->extra->length * sizeof(PyObject*));
}
self->extra->children = children;
self->extra->allocated = size;
}
return 0;
nomemory:
PyErr_NoMemory();
return -1;
}
LOCAL(int)
element_add_subelement(ElementObject* self, PyObject* element)
{
/* add a child element to a parent */
if (element_resize(self, 1) < 0)
return -1;
Py_INCREF(element);
self->extra->children[self->extra->length] = element;
self->extra->length++;
return 0;
}
LOCAL(PyObject*)
element_get_attrib(ElementObject* self)
{
/* return borrowed reference to attrib dictionary */
/* note: this function assumes that the extra section exists */
PyObject* res = self->extra->attrib;
if (res == Py_None) {
/* create missing dictionary */
res = PyDict_New();
if (!res)
return NULL;
Py_DECREF(Py_None);
self->extra->attrib = res;
}
return res;
}
LOCAL(PyObject*)
element_get_text(ElementObject* self)
{
/* return borrowed reference to text attribute */
PyObject *res = self->text;
if (JOIN_GET(res)) {
res = JOIN_OBJ(res);
if (PyList_CheckExact(res)) {
PyObject *tmp = list_join(res);
if (!tmp)
return NULL;
self->text = tmp;
Py_DECREF(res);
res = tmp;
}
}
return res;
}
LOCAL(PyObject*)
element_get_tail(ElementObject* self)
{
/* return borrowed reference to text attribute */
PyObject *res = self->tail;
if (JOIN_GET(res)) {
res = JOIN_OBJ(res);
if (PyList_CheckExact(res)) {
PyObject *tmp = list_join(res);
if (!tmp)
return NULL;
self->tail = tmp;
Py_DECREF(res);
res = tmp;
}
}
return res;
}
static PyObject*
subelement(PyObject *self, PyObject *args, PyObject *kwds)
{
PyObject* elem;
ElementObject* parent;
PyObject* tag;
PyObject* attrib = NULL;
if (!PyArg_ParseTuple(args, "O!O|O!:SubElement",
&Element_Type, &parent, &tag,
&PyDict_Type, &attrib)) {
return NULL;
}
if (attrib) {
/* attrib passed as positional arg */
attrib = PyDict_Copy(attrib);
if (!attrib)
return NULL;
if (kwds != NULL && PyDict_Update(attrib, kwds) < 0) {
Py_DECREF(attrib);
return NULL;
}
} else if (kwds) {
/* have keyword args */
attrib = get_attrib_from_keywords(kwds);
if (!attrib)
return NULL;
} else {
/* no attrib arg, no kwds, so no attribute */
Py_INCREF(Py_None);
attrib = Py_None;
}
elem = create_new_element(tag, attrib);
Py_DECREF(attrib);
if (elem == NULL)
return NULL;
if (element_add_subelement(parent, elem) < 0) {
Py_DECREF(elem);
return NULL;
}
return elem;
}
static int
element_gc_traverse(ElementObject *self, visitproc visit, void *arg)
{
Py_VISIT(self->tag);
Py_VISIT(JOIN_OBJ(self->text));
Py_VISIT(JOIN_OBJ(self->tail));
if (self->extra) {
Py_ssize_t i;
Py_VISIT(self->extra->attrib);
for (i = 0; i < self->extra->length; ++i)
Py_VISIT(self->extra->children[i]);
}
return 0;
}
static int
element_gc_clear(ElementObject *self)
{
Py_CLEAR(self->tag);
_clear_joined_ptr(&self->text);
_clear_joined_ptr(&self->tail);
/* After dropping all references from extra, it's no longer valid anyway,
* so fully deallocate it.
*/
clear_extra(self);
return 0;
}
static void
element_dealloc(ElementObject* self)
{
/* bpo-31095: UnTrack is needed before calling any callbacks */
PyObject_GC_UnTrack(self);
Py_TRASHCAN_SAFE_BEGIN(self)
if (self->weakreflist != NULL)
PyObject_ClearWeakRefs((PyObject *) self);
/* element_gc_clear clears all references and deallocates extra
*/
element_gc_clear(self);
RELEASE(sizeof(ElementObject), "destroy element");
Py_TYPE(self)->tp_free((PyObject *)self);
Py_TRASHCAN_SAFE_END(self)
}
/* -------------------------------------------------------------------- */
/*[clinic input]
_elementtree.Element.append
subelement: object(subclass_of='&Element_Type')
/
[clinic start generated code]*/
static PyObject *
_elementtree_Element_append_impl(ElementObject *self, PyObject *subelement)
/*[clinic end generated code: output=54a884b7cf2295f4 input=3ed648beb5bfa22a]*/
{
if (element_add_subelement(self, subelement) < 0)
return NULL;
Py_RETURN_NONE;
}
/*[clinic input]
_elementtree.Element.clear
[clinic start generated code]*/
static PyObject *
_elementtree_Element_clear_impl(ElementObject *self)
/*[clinic end generated code: output=8bcd7a51f94cfff6 input=3c719ff94bf45dd6]*/
{
clear_extra(self);
Py_INCREF(Py_None);
_set_joined_ptr(&self->text, Py_None);
Py_INCREF(Py_None);
_set_joined_ptr(&self->tail, Py_None);
Py_RETURN_NONE;
}
/*[clinic input]
_elementtree.Element.__copy__
[clinic start generated code]*/
static PyObject *
_elementtree_Element___copy___impl(ElementObject *self)
/*[clinic end generated code: output=2c701ebff7247781 input=ad87aaebe95675bf]*/
{
Py_ssize_t i;
ElementObject* element;
element = (ElementObject*) create_new_element(
self->tag, (self->extra) ? self->extra->attrib : Py_None);
if (!element)
return NULL;
Py_INCREF(JOIN_OBJ(self->text));
_set_joined_ptr(&element->text, self->text);
Py_INCREF(JOIN_OBJ(self->tail));
_set_joined_ptr(&element->tail, self->tail);
assert(!element->extra || !element->extra->length);
if (self->extra) {
if (element_resize(element, self->extra->length) < 0) {
Py_DECREF(element);
return NULL;
}
for (i = 0; i < self->extra->length; i++) {
Py_INCREF(self->extra->children[i]);
element->extra->children[i] = self->extra->children[i];
}
assert(!element->extra->length);
element->extra->length = self->extra->length;
}
return (PyObject*) element;
}
/* Helper for a deep copy. */
LOCAL(PyObject *) deepcopy(PyObject *, PyObject *);
/*[clinic input]
_elementtree.Element.__deepcopy__
memo: object
/
[clinic start generated code]*/
static PyObject *
_elementtree_Element___deepcopy__(ElementObject *self, PyObject *memo)
/*[clinic end generated code: output=d1f19851d17bf239 input=df24c2b602430b77]*/
{
Py_ssize_t i;
ElementObject* element;
PyObject* tag;
PyObject* attrib;
PyObject* text;
PyObject* tail;
PyObject* id;
tag = deepcopy(self->tag, memo);
if (!tag)
return NULL;
if (self->extra) {
attrib = deepcopy(self->extra->attrib, memo);
if (!attrib) {
Py_DECREF(tag);
return NULL;
}
} else {
Py_INCREF(Py_None);
attrib = Py_None;
}
element = (ElementObject*) create_new_element(tag, attrib);
Py_DECREF(tag);
Py_DECREF(attrib);
if (!element)
return NULL;
text = deepcopy(JOIN_OBJ(self->text), memo);
if (!text)
goto error;
_set_joined_ptr(&element->text, JOIN_SET(text, JOIN_GET(self->text)));
tail = deepcopy(JOIN_OBJ(self->tail), memo);
if (!tail)
goto error;
_set_joined_ptr(&element->tail, JOIN_SET(tail, JOIN_GET(self->tail)));
assert(!element->extra || !element->extra->length);
if (self->extra) {
if (element_resize(element, self->extra->length) < 0)
goto error;
for (i = 0; i < self->extra->length; i++) {
PyObject* child = deepcopy(self->extra->children[i], memo);
if (!child) {
element->extra->length = i;
goto error;
}
element->extra->children[i] = child;
}
assert(!element->extra->length);
element->extra->length = self->extra->length;
}
/* add object to memo dictionary (so deepcopy won't visit it again) */
id = PyLong_FromSsize_t((uintptr_t) self);
if (!id)
goto error;
i = PyDict_SetItem(memo, id, (PyObject*) element);
Py_DECREF(id);
if (i < 0)
goto error;
return (PyObject*) element;
error:
Py_DECREF(element);
return NULL;
}
LOCAL(PyObject *)
deepcopy(PyObject *object, PyObject *memo)
{
/* do a deep copy of the given object */
elementtreestate *st;
PyObject *stack[2];
/* Fast paths */
if (object == Py_None || PyUnicode_CheckExact(object)) {
Py_INCREF(object);
return object;
}
if (Py_REFCNT(object) == 1) {
if (PyDict_CheckExact(object)) {
PyObject *key, *value;
Py_ssize_t pos = 0;
int simple = 1;
while (PyDict_Next(object, &pos, &key, &value)) {
if (!PyUnicode_CheckExact(key) || !PyUnicode_CheckExact(value)) {
simple = 0;
break;
}
}
if (simple)
return PyDict_Copy(object);
/* Fall through to general case */
}
else if (Element_CheckExact(object)) {
return _elementtree_Element___deepcopy__((ElementObject *)object, memo);
}
}
/* General case */
st = ET_STATE_GLOBAL;
if (!st->deepcopy_obj) {
PyErr_SetString(PyExc_RuntimeError,
"deepcopy helper not found");
return NULL;
}
stack[0] = object;
stack[1] = memo;
return _PyObject_FastCall(st->deepcopy_obj, stack, 2);
}
/*[clinic input]
_elementtree.Element.__sizeof__ -> Py_ssize_t
[clinic start generated code]*/
static Py_ssize_t
_elementtree_Element___sizeof___impl(ElementObject *self)
/*[clinic end generated code: output=bf73867721008000 input=70f4b323d55a17c1]*/
{
Py_ssize_t result = _PyObject_SIZE(Py_TYPE(self));
if (self->extra) {
result += sizeof(ElementObjectExtra);
if (self->extra->children != self->extra->_children)
result += sizeof(PyObject*) * self->extra->allocated;
}
return result;
}
/* dict keys for getstate/setstate. */
#define PICKLED_TAG "tag"
#define PICKLED_CHILDREN "_children"
#define PICKLED_ATTRIB "attrib"
#define PICKLED_TAIL "tail"
#define PICKLED_TEXT "text"
/* __getstate__ returns a fabricated instance dict as in the pure-Python
* Element implementation, for interoperability/interchangeability. This
* makes the pure-Python implementation details an API, but (a) there aren't
* any unnecessary structures there; and (b) it buys compatibility with 3.2
* pickles. See issue #16076.
*/
/*[clinic input]
_elementtree.Element.__getstate__
[clinic start generated code]*/
static PyObject *
_elementtree_Element___getstate___impl(ElementObject *self)
/*[clinic end generated code: output=37279aeeb6bb5b04 input=f0d16d7ec2f7adc1]*/
{
Py_ssize_t i, noattrib;
PyObject *instancedict = NULL, *children;
/* Build a list of children. */
children = PyList_New(self->extra ? self->extra->length : 0);
if (!children)
return NULL;
for (i = 0; i < PyList_GET_SIZE(children); i++) {
PyObject *child = self->extra->children[i];
Py_INCREF(child);
PyList_SET_ITEM(children, i, child);
}
/* Construct the state object. */
noattrib = (self->extra == NULL || self->extra->attrib == Py_None);
if (noattrib)
instancedict = Py_BuildValue("{sOsOs{}sOsO}",
PICKLED_TAG, self->tag,
PICKLED_CHILDREN, children,
PICKLED_ATTRIB,
PICKLED_TEXT, JOIN_OBJ(self->text),
PICKLED_TAIL, JOIN_OBJ(self->tail));
else
instancedict = Py_BuildValue("{sOsOsOsOsO}",
PICKLED_TAG, self->tag,
PICKLED_CHILDREN, children,
PICKLED_ATTRIB, self->extra->attrib,
PICKLED_TEXT, JOIN_OBJ(self->text),
PICKLED_TAIL, JOIN_OBJ(self->tail));
if (instancedict) {
Py_DECREF(children);
return instancedict;
}
else {
for (i = 0; i < PyList_GET_SIZE(children); i++)
Py_DECREF(PyList_GET_ITEM(children, i));
Py_DECREF(children);
return NULL;
}
}
static PyObject *
element_setstate_from_attributes(ElementObject *self,
PyObject *tag,
PyObject *attrib,
PyObject *text,
PyObject *tail,
PyObject *children)
{
Py_ssize_t i, nchildren;
ElementObjectExtra *oldextra = NULL;
if (!tag) {
PyErr_SetString(PyExc_TypeError, "tag may not be NULL");
return NULL;
}
Py_INCREF(tag);
Py_XSETREF(self->tag, tag);
text = text ? JOIN_SET(text, PyList_CheckExact(text)) : Py_None;
Py_INCREF(JOIN_OBJ(text));
_set_joined_ptr(&self->text, text);
tail = tail ? JOIN_SET(tail, PyList_CheckExact(tail)) : Py_None;
Py_INCREF(JOIN_OBJ(tail));
_set_joined_ptr(&self->tail, tail);
/* Handle ATTRIB and CHILDREN. */
if (!children && !attrib) {
Py_RETURN_NONE;
}
/* Compute 'nchildren'. */
if (children) {
if (!PyList_Check(children)) {
PyErr_SetString(PyExc_TypeError, "'_children' is not a list");
return NULL;
}
nchildren = PyList_GET_SIZE(children);
/* (Re-)allocate 'extra'.
Avoid DECREFs calling into this code again (cycles, etc.)
*/
oldextra = self->extra;
self->extra = NULL;
if (element_resize(self, nchildren)) {
assert(!self->extra || !self->extra->length);
clear_extra(self);
self->extra = oldextra;
return NULL;
}
assert(self->extra);
assert(self->extra->allocated >= nchildren);
if (oldextra) {
assert(self->extra->attrib == Py_None);
self->extra->attrib = oldextra->attrib;
oldextra->attrib = Py_None;
}
/* Copy children */
for (i = 0; i < nchildren; i++) {
self->extra->children[i] = PyList_GET_ITEM(children, i);
Py_INCREF(self->extra->children[i]);
}
assert(!self->extra->length);
self->extra->length = nchildren;
}
else {
if (element_resize(self, 0)) {
return NULL;
}
}
/* Stash attrib. */
if (attrib) {
Py_INCREF(attrib);
Py_XSETREF(self->extra->attrib, attrib);
}
dealloc_extra(oldextra);
Py_RETURN_NONE;
}
/* __setstate__ for Element instance from the Python implementation.
* 'state' should be the instance dict.
*/
static PyObject *
element_setstate_from_Python(ElementObject *self, PyObject *state)
{
static char *kwlist[] = {PICKLED_TAG, PICKLED_ATTRIB, PICKLED_TEXT,
PICKLED_TAIL, PICKLED_CHILDREN, 0};
PyObject *args;
PyObject *tag, *attrib, *text, *tail, *children;
PyObject *retval;
tag = attrib = text = tail = children = NULL;
args = PyTuple_New(0);
if (!args)
return NULL;
if (PyArg_ParseTupleAndKeywords(args, state, "|$OOOOO", kwlist, &tag,
&attrib, &text, &tail, &children))
retval = element_setstate_from_attributes(self, tag, attrib, text,
tail, children);
else
retval = NULL;
Py_DECREF(args);
return retval;
}
/*[clinic input]
_elementtree.Element.__setstate__
state: object
/
[clinic start generated code]*/
static PyObject *
_elementtree_Element___setstate__(ElementObject *self, PyObject *state)
/*[clinic end generated code: output=ea28bf3491b1f75e input=aaf80abea7c1e3b9]*/
{
if (!PyDict_CheckExact(state)) {
PyErr_Format(PyExc_TypeError,
"Don't know how to unpickle \"%.200R\" as an Element",
state);
return NULL;
}
else
return element_setstate_from_Python(self, state);
}
LOCAL(int)
checkpath(PyObject* tag)
{
Py_ssize_t i;
int check = 1;
/* check if a tag contains an xpath character */
#define PATHCHAR(ch) \
(ch == '/' || ch == '*' || ch == '[' || ch == '@' || ch == '.')
if (PyUnicode_Check(tag)) {
const Py_ssize_t len = PyUnicode_GET_LENGTH(tag);
void *data = PyUnicode_DATA(tag);
unsigned int kind = PyUnicode_KIND(tag);
for (i = 0; i < len; i++) {
Py_UCS4 ch = PyUnicode_READ(kind, data, i);
if (ch == '{')
check = 0;
else if (ch == '}')
check = 1;
else if (check && PATHCHAR(ch))
return 1;
}
return 0;
}
if (PyBytes_Check(tag)) {
char *p = PyBytes_AS_STRING(tag);
for (i = 0; i < PyBytes_GET_SIZE(tag); i++) {
if (p[i] == '{')
check = 0;
else if (p[i] == '}')
check = 1;
else if (check && PATHCHAR(p[i]))
return 1;
}
return 0;
}
return 1; /* unknown type; might be path expression */
}
/*[clinic input]
_elementtree.Element.extend
elements: object
/
[clinic start generated code]*/
static PyObject *
_elementtree_Element_extend(ElementObject *self, PyObject *elements)
/*[clinic end generated code: output=f6e67fc2ff529191 input=807bc4f31c69f7c0]*/
{
PyObject* seq;
Py_ssize_t i;
seq = PySequence_Fast(elements, "");
if (!seq) {
PyErr_Format(
PyExc_TypeError,
"expected sequence, not \"%.200s\"", Py_TYPE(elements)->tp_name
);
return NULL;
}
for (i = 0; i < PySequence_Fast_GET_SIZE(seq); i++) {
PyObject* element = PySequence_Fast_GET_ITEM(seq, i);
Py_INCREF(element);
if (!Element_Check(element)) {
PyErr_Format(
PyExc_TypeError,
"expected an Element, not \"%.200s\"",
Py_TYPE(element)->tp_name);
Py_DECREF(seq);
Py_DECREF(element);
return NULL;
}
if (element_add_subelement(self, element) < 0) {
Py_DECREF(seq);
Py_DECREF(element);
return NULL;
}
Py_DECREF(element);
}
Py_DECREF(seq);
Py_RETURN_NONE;
}
/*[clinic input]
_elementtree.Element.find
path: object
namespaces: object = None
[clinic start generated code]*/
static PyObject *
_elementtree_Element_find_impl(ElementObject *self, PyObject *path,
PyObject *namespaces)
/*[clinic end generated code: output=41b43f0f0becafae input=359b6985f6489d2e]*/
{
Py_ssize_t i;
elementtreestate *st = ET_STATE_GLOBAL;
if (checkpath(path) || namespaces != Py_None) {
_Py_IDENTIFIER(find);
return _PyObject_CallMethodId(
st->elementpath_obj, &PyId_find, "OOO", self, path, namespaces
);
}
if (!self->extra)
Py_RETURN_NONE;
for (i = 0; i < self->extra->length; i++) {
PyObject* item = self->extra->children[i];
int rc;
if (!Element_Check(item))
continue;
Py_INCREF(item);
rc = PyObject_RichCompareBool(((ElementObject*)item)->tag, path, Py_EQ);
if (rc > 0)
return item;
Py_DECREF(item);
if (rc < 0)
return NULL;
}
Py_RETURN_NONE;
}
/*[clinic input]
_elementtree.Element.findtext
path: object
default: object = None
namespaces: object = None
[clinic start generated code]*/
static PyObject *
_elementtree_Element_findtext_impl(ElementObject *self, PyObject *path,
PyObject *default_value,
PyObject *namespaces)
/*[clinic end generated code: output=83b3ba4535d308d2 input=b53a85aa5aa2a916]*/
{
Py_ssize_t i;
_Py_IDENTIFIER(findtext);
elementtreestate *st = ET_STATE_GLOBAL;
if (checkpath(path) || namespaces != Py_None)
return _PyObject_CallMethodId(
st->elementpath_obj, &PyId_findtext, "OOOO", self, path, default_value, namespaces
);
if (!self->extra) {
Py_INCREF(default_value);
return default_value;
}
for (i = 0; i < self->extra->length; i++) {
PyObject *item = self->extra->children[i];
int rc;
if (!Element_Check(item))
continue;
Py_INCREF(item);
rc = PyObject_RichCompareBool(((ElementObject*)item)->tag, path, Py_EQ);
if (rc > 0) {
PyObject* text = element_get_text((ElementObject*)item);
if (text == Py_None) {
Py_DECREF(item);
return PyUnicode_New(0, 0);
}
Py_XINCREF(text);
Py_DECREF(item);
return text;
}
Py_DECREF(item);
if (rc < 0)
return NULL;
}
Py_INCREF(default_value);
return default_value;
}
/*[clinic input]
_elementtree.Element.findall
path: object
namespaces: object = None
[clinic start generated code]*/
static PyObject *
_elementtree_Element_findall_impl(ElementObject *self, PyObject *path,
PyObject *namespaces)
/*[clinic end generated code: output=1a0bd9f5541b711d input=4d9e6505a638550c]*/
{
Py_ssize_t i;
PyObject* out;
elementtreestate *st = ET_STATE_GLOBAL;
if (checkpath(path) || namespaces != Py_None) {
_Py_IDENTIFIER(findall);
return _PyObject_CallMethodId(
st->elementpath_obj, &PyId_findall, "OOO", self, path, namespaces
);
}
out = PyList_New(0);
if (!out)
return NULL;
if (!self->extra)
return out;
for (i = 0; i < self->extra->length; i++) {
PyObject* item = self->extra->children[i];
int rc;
if (!Element_Check(item))
continue;
Py_INCREF(item);
rc = PyObject_RichCompareBool(((ElementObject*)item)->tag, path, Py_EQ);
if (rc != 0 && (rc < 0 || PyList_Append(out, item) < 0)) {
Py_DECREF(item);
Py_DECREF(out);
return NULL;
}
Py_DECREF(item);
}
return out;
}
/*[clinic input]
_elementtree.Element.iterfind
path: object
namespaces: object = None
[clinic start generated code]*/
static PyObject *
_elementtree_Element_iterfind_impl(ElementObject *self, PyObject *path,
PyObject *namespaces)
/*[clinic end generated code: output=ecdd56d63b19d40f input=abb974e350fb65c7]*/
{
PyObject* tag = path;
_Py_IDENTIFIER(iterfind);
elementtreestate *st = ET_STATE_GLOBAL;
return _PyObject_CallMethodId(
st->elementpath_obj, &PyId_iterfind, "OOO", self, tag, namespaces);
}
/*[clinic input]
_elementtree.Element.get
key: object
default: object = None
[clinic start generated code]*/
static PyObject *
_elementtree_Element_get_impl(ElementObject *self, PyObject *key,
PyObject *default_value)
/*[clinic end generated code: output=523c614142595d75 input=ee153bbf8cdb246e]*/
{
PyObject* value;
if (!self->extra || self->extra->attrib == Py_None)
value = default_value;
else {
value = PyDict_GetItem(self->extra->attrib, key);
if (!value)
value = default_value;
}
Py_INCREF(value);
return value;
}
/*[clinic input]
_elementtree.Element.getchildren
[clinic start generated code]*/
static PyObject *
_elementtree_Element_getchildren_impl(ElementObject *self)
/*[clinic end generated code: output=e50ffe118637b14f input=0f754dfded150d5f]*/
{
Py_ssize_t i;
PyObject* list;
/* FIXME: report as deprecated? */
if (!self->extra)
return PyList_New(0);
list = PyList_New(self->extra->length);
if (!list)
return NULL;
for (i = 0; i < self->extra->length; i++) {
PyObject* item = self->extra->children[i];
Py_INCREF(item);
PyList_SET_ITEM(list, i, item);
}
return list;
}
static PyObject *
create_elementiter(ElementObject *self, PyObject *tag, int gettext);
/*[clinic input]
_elementtree.Element.iter
tag: object = None
[clinic start generated code]*/
static PyObject *
_elementtree_Element_iter_impl(ElementObject *self, PyObject *tag)
/*[clinic end generated code: output=3f49f9a862941cc5 input=774d5b12e573aedd]*/
{
if (PyUnicode_Check(tag)) {
if (PyUnicode_READY(tag) < 0)
return NULL;
if (PyUnicode_GET_LENGTH(tag) == 1 && PyUnicode_READ_CHAR(tag, 0) == '*')
tag = Py_None;
}
else if (PyBytes_Check(tag)) {
if (PyBytes_GET_SIZE(tag) == 1 && *PyBytes_AS_STRING(tag) == '*')
tag = Py_None;
}
return create_elementiter(self, tag, 0);
}
/*[clinic input]
_elementtree.Element.itertext
[clinic start generated code]*/
static PyObject *
_elementtree_Element_itertext_impl(ElementObject *self)
/*[clinic end generated code: output=5fa34b2fbcb65df6 input=af8f0e42cb239c89]*/
{
return create_elementiter(self, Py_None, 1);
}
static PyObject*
element_getitem(PyObject* self_, Py_ssize_t index)
{
ElementObject* self = (ElementObject*) self_;
if (!self->extra || index < 0 || index >= self->extra->length) {
PyErr_SetString(
PyExc_IndexError,
"child index out of range"
);
return NULL;
}
Py_INCREF(self->extra->children[index]);
return self->extra->children[index];
}
/*[clinic input]
_elementtree.Element.insert
index: Py_ssize_t
subelement: object(subclass_of='&Element_Type')
/
[clinic start generated code]*/
static PyObject *
_elementtree_Element_insert_impl(ElementObject *self, Py_ssize_t index,
PyObject *subelement)
/*[clinic end generated code: output=990adfef4d424c0b input=cd6fbfcdab52d7a8]*/
{
Py_ssize_t i;
if (!self->extra) {
if (create_extra(self, NULL) < 0)
return NULL;
}
if (index < 0) {
index += self->extra->length;
if (index < 0)
index = 0;
}
if (index > self->extra->length)
index = self->extra->length;
if (element_resize(self, 1) < 0)
return NULL;
for (i = self->extra->length; i > index; i--)
self->extra->children[i] = self->extra->children[i-1];
Py_INCREF(subelement);
self->extra->children[index] = subelement;
self->extra->length++;
Py_RETURN_NONE;
}
/*[clinic input]
_elementtree.Element.items
[clinic start generated code]*/
static PyObject *
_elementtree_Element_items_impl(ElementObject *self)
/*[clinic end generated code: output=6db2c778ce3f5a4d input=adbe09aaea474447]*/
{
if (!self->extra || self->extra->attrib == Py_None)
return PyList_New(0);
return PyDict_Items(self->extra->attrib);
}
/*[clinic input]
_elementtree.Element.keys
[clinic start generated code]*/
static PyObject *
_elementtree_Element_keys_impl(ElementObject *self)
/*[clinic end generated code: output=bc5bfabbf20eeb3c input=f02caf5b496b5b0b]*/
{
if (!self->extra || self->extra->attrib == Py_None)
return PyList_New(0);
return PyDict_Keys(self->extra->attrib);
}
static Py_ssize_t
element_length(ElementObject* self)
{
if (!self->extra)
return 0;
return self->extra->length;
}
/*[clinic input]
_elementtree.Element.makeelement
tag: object
attrib: object
/
[clinic start generated code]*/
static PyObject *
_elementtree_Element_makeelement_impl(ElementObject *self, PyObject *tag,
PyObject *attrib)
/*[clinic end generated code: output=4109832d5bb789ef input=9480d1d2e3e68235]*/
{
PyObject* elem;
attrib = PyDict_Copy(attrib);
if (!attrib)
return NULL;
elem = create_new_element(tag, attrib);
Py_DECREF(attrib);
return elem;
}
/*[clinic input]
_elementtree.Element.remove
subelement: object(subclass_of='&Element_Type')
/
[clinic start generated code]*/
static PyObject *
_elementtree_Element_remove_impl(ElementObject *self, PyObject *subelement)
/*[clinic end generated code: output=38fe6c07d6d87d1f input=d52fc28ededc0bd8]*/
{
Py_ssize_t i;
int rc;
PyObject *found;
if (!self->extra) {
/* element has no children, so raise exception */
PyErr_SetString(
PyExc_ValueError,
"list.remove(x): x not in list"
);
return NULL;
}
for (i = 0; i < self->extra->length; i++) {
if (self->extra->children[i] == subelement)
break;
rc = PyObject_RichCompareBool(self->extra->children[i], subelement, Py_EQ);
if (rc > 0)
break;
if (rc < 0)
return NULL;
}
if (i >= self->extra->length) {
/* subelement is not in children, so raise exception */
PyErr_SetString(
PyExc_ValueError,
"list.remove(x): x not in list"
);
return NULL;
}
found = self->extra->children[i];
self->extra->length--;
for (; i < self->extra->length; i++)
self->extra->children[i] = self->extra->children[i+1];
Py_DECREF(found);
Py_RETURN_NONE;
}
static PyObject*
element_repr(ElementObject* self)
{
int status;
if (self->tag == NULL)
return PyUnicode_FromFormat("<Element at %p>", self);
status = Py_ReprEnter((PyObject *)self);
if (status == 0) {
PyObject *res;
res = PyUnicode_FromFormat("<Element %R at %p>", self->tag, self);
Py_ReprLeave((PyObject *)self);
return res;
}
if (status > 0)
PyErr_Format(PyExc_RuntimeError,
"reentrant call inside %s.__repr__",
Py_TYPE(self)->tp_name);
return NULL;
}
/*[clinic input]
_elementtree.Element.set
key: object
value: object
/
[clinic start generated code]*/
static PyObject *
_elementtree_Element_set_impl(ElementObject *self, PyObject *key,
PyObject *value)
/*[clinic end generated code: output=fb938806be3c5656 input=1efe90f7d82b3fe9]*/
{
PyObject* attrib;
if (!self->extra) {
if (create_extra(self, NULL) < 0)
return NULL;
}
attrib = element_get_attrib(self);
if (!attrib)
return NULL;
if (PyDict_SetItem(attrib, key, value) < 0)
return NULL;
Py_RETURN_NONE;
}
static int
element_setitem(PyObject* self_, Py_ssize_t index, PyObject* item)
{
ElementObject* self = (ElementObject*) self_;
Py_ssize_t i;
PyObject* old;
if (!self->extra || index < 0 || index >= self->extra->length) {
PyErr_SetString(
PyExc_IndexError,
"child assignment index out of range");
return -1;
}
old = self->extra->children[index];
if (item) {
Py_INCREF(item);
self->extra->children[index] = item;
} else {
self->extra->length--;
for (i = index; i < self->extra->length; i++)
self->extra->children[i] = self->extra->children[i+1];
}
Py_DECREF(old);
return 0;
}
static PyObject*
element_subscr(PyObject* self_, PyObject* item)
{
ElementObject* self = (ElementObject*) 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 && self->extra)
i += self->extra->length;
return element_getitem(self_, i);
}
else if (PySlice_Check(item)) {
Py_ssize_t start, stop, step, slicelen, cur, i;
PyObject* list;
if (!self->extra)
return PyList_New(0);
if (PySlice_Unpack(item, &start, &stop, &step) < 0) {
return NULL;
}
slicelen = PySlice_AdjustIndices(self->extra->length, &start, &stop,
step);
if (slicelen <= 0)
return PyList_New(0);
else {
list = PyList_New(slicelen);
if (!list)
return NULL;
for (cur = start, i = 0; i < slicelen;
cur += step, i++) {
PyObject* item = self->extra->children[cur];
Py_INCREF(item);
PyList_SET_ITEM(list, i, item);
}
return list;
}
}
else {
PyErr_SetString(PyExc_TypeError,
"element indices must be integers");
return NULL;
}
}
static int
element_ass_subscr(PyObject* self_, PyObject* item, PyObject* value)
{
ElementObject* self = (ElementObject*) self_;
if (PyIndex_Check(item)) {
Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
if (i == -1 && PyErr_Occurred()) {
return -1;
}
if (i < 0 && self->extra)
i += self->extra->length;
return element_setitem(self_, i, value);
}
else if (PySlice_Check(item)) {
Py_ssize_t start, stop, step, slicelen, newlen, cur, i;
PyObject* recycle = NULL;
PyObject* seq;
if (!self->extra) {
if (create_extra(self, NULL) < 0)
return -1;
}
if (PySlice_Unpack(item, &start, &stop, &step) < 0) {
return -1;
}
slicelen = PySlice_AdjustIndices(self->extra->length, &start, &stop,
step);
if (value == NULL) {
/* Delete slice */
size_t cur;
Py_ssize_t i;
if (slicelen <= 0)
return 0;
/* Since we're deleting, the direction of the range doesn't matter,
* so for simplicity make it always ascending.
*/
if (step < 0) {
stop = start + 1;
start = stop + step * (slicelen - 1) - 1;
step = -step;
}
assert((size_t)slicelen <= SIZE_MAX / sizeof(PyObject *));
/* recycle is a list that will contain all the children
* scheduled for removal.
*/
if (!(recycle = PyList_New(slicelen))) {
return -1;
}
/* This loop walks over all the children that have to be deleted,
* with cur pointing at them. num_moved is the amount of children
* until the next deleted child that have to be "shifted down" to
* occupy the deleted's places.
* Note that in the ith iteration, shifting is done i+i places down
* because i children were already removed.
*/
for (cur = start, i = 0; cur < (size_t)stop; cur += step, ++i) {
/* Compute how many children have to be moved, clipping at the
* list end.
*/
Py_ssize_t num_moved = step - 1;
if (cur + step >= (size_t)self->extra->length) {
num_moved = self->extra->length - cur - 1;
}
PyList_SET_ITEM(recycle, i, self->extra->children[cur]);
memmove(
self->extra->children + cur - i,
self->extra->children + cur + 1,
num_moved * sizeof(PyObject *));
}
/* Leftover "tail" after the last removed child */
cur = start + (size_t)slicelen * step;
if (cur < (size_t)self->extra->length) {
memmove(
self->extra->children + cur - slicelen,
self->extra->children + cur,
(self->extra->length - cur) * sizeof(PyObject *));
}
self->extra->length -= slicelen;
/* Discard the recycle list with all the deleted sub-elements */
Py_DECREF(recycle);
return 0;
}
/* A new slice is actually being assigned */
seq = PySequence_Fast(value, "");
if (!seq) {
PyErr_Format(
PyExc_TypeError,
"expected sequence, not \"%.200s\"", Py_TYPE(value)->tp_name
);
return -1;
}
newlen = PySequence_Size(seq);
if (step != 1 && newlen != slicelen)
{
Py_DECREF(seq);
PyErr_Format(PyExc_ValueError,
"attempt to assign sequence of size %zd "
"to extended slice of size %zd",
newlen, slicelen
);
return -1;
}
/* Resize before creating the recycle bin, to prevent refleaks. */
if (newlen > slicelen) {
if (element_resize(self, newlen - slicelen) < 0) {
Py_DECREF(seq);
return -1;
}
}
if (slicelen > 0) {
/* to avoid recursive calls to this method (via decref), move
old items to the recycle bin here, and get rid of them when
we're done modifying the element */
recycle = PyList_New(slicelen);
if (!recycle) {
Py_DECREF(seq);
return -1;
}
for (cur = start, i = 0; i < slicelen;
cur += step, i++)
PyList_SET_ITEM(recycle, i, self->extra->children[cur]);
}
if (newlen < slicelen) {
/* delete slice */
for (i = stop; i < self->extra->length; i++)
self->extra->children[i + newlen - slicelen] = self->extra->children[i];
} else if (newlen > slicelen) {
/* insert slice */
for (i = self->extra->length-1; i >= stop; i--)
self->extra->children[i + newlen - slicelen] = self->extra->children[i];
}
/* replace the slice */
for (cur = start, i = 0; i < newlen;
cur += step, i++) {
PyObject* element = PySequence_Fast_GET_ITEM(seq, i);
Py_INCREF(element);
self->extra->children[cur] = element;
}
self->extra->length += newlen - slicelen;
Py_DECREF(seq);
/* discard the recycle bin, and everything in it */
Py_XDECREF(recycle);
return 0;
}
else {
PyErr_SetString(PyExc_TypeError,
"element indices must be integers");
return -1;
}
}
static PyObject*
element_tag_getter(ElementObject *self, void *closure)
{
PyObject *res = self->tag;
Py_INCREF(res);
return res;
}
static PyObject*
element_text_getter(ElementObject *self, void *closure)
{
PyObject *res = element_get_text(self);
Py_XINCREF(res);
return res;
}
static PyObject*
element_tail_getter(ElementObject *self, void *closure)
{
PyObject *res = element_get_tail(self);
Py_XINCREF(res);
return res;
}
static PyObject*
element_attrib_getter(ElementObject *self, void *closure)
{
PyObject *res;
if (!self->extra) {
if (create_extra(self, NULL) < 0)
return NULL;
}
res = element_get_attrib(self);
Py_XINCREF(res);
return res;
}
/* macro for setter validation */
#define _VALIDATE_ATTR_VALUE(V) \
if ((V) == NULL) { \
PyErr_SetString( \
PyExc_AttributeError, \
"can't delete element attribute"); \
return -1; \
}
static int
element_tag_setter(ElementObject *self, PyObject *value, void *closure)
{
_VALIDATE_ATTR_VALUE(value);
Py_INCREF(value);
Py_SETREF(self->tag, value);
return 0;
}
static int
element_text_setter(ElementObject *self, PyObject *value, void *closure)
{
_VALIDATE_ATTR_VALUE(value);
Py_INCREF(value);
_set_joined_ptr(&self->text, value);
return 0;
}
static int
element_tail_setter(ElementObject *self, PyObject *value, void *closure)
{
_VALIDATE_ATTR_VALUE(value);
Py_INCREF(value);
_set_joined_ptr(&self->tail, value);
return 0;
}
static int
element_attrib_setter(ElementObject *self, PyObject *value, void *closure)
{
_VALIDATE_ATTR_VALUE(value);
if (!self->extra) {
if (create_extra(self, NULL) < 0)
return -1;
}
Py_INCREF(value);
Py_SETREF(self->extra->attrib, value);
return 0;
}
static PySequenceMethods element_as_sequence = {
(lenfunc) element_length,
0, /* sq_concat */
0, /* sq_repeat */
element_getitem,
0,
element_setitem,
0,
};
/******************************* Element iterator ****************************/
/* ElementIterObject represents the iteration state over an XML element in
* pre-order traversal. To keep track of which sub-element should be returned
* next, a stack of parents is maintained. This is a standard stack-based
* iterative pre-order traversal of a tree.
* The stack is managed using a continuous array.
* Each stack item contains the saved parent to which we should return after
* the current one is exhausted, and the next child to examine in that parent.
*/
typedef struct ParentLocator_t {
ElementObject *parent;
Py_ssize_t child_index;
} ParentLocator;
typedef struct {
PyObject_HEAD
ParentLocator *parent_stack;
Py_ssize_t parent_stack_used;
Py_ssize_t parent_stack_size;
ElementObject *root_element;
PyObject *sought_tag;
int gettext;
} ElementIterObject;
static void
elementiter_dealloc(ElementIterObject *it)
{
Py_ssize_t i = it->parent_stack_used;
it->parent_stack_used = 0;
/* bpo-31095: UnTrack is needed before calling any callbacks */
PyObject_GC_UnTrack(it);
while (i--)
Py_XDECREF(it->parent_stack[i].parent);
PyMem_Free(it->parent_stack);
Py_XDECREF(it->sought_tag);
Py_XDECREF(it->root_element);
PyObject_GC_Del(it);
}
static int
elementiter_traverse(ElementIterObject *it, visitproc visit, void *arg)
{
Py_ssize_t i = it->parent_stack_used;
while (i--)
Py_VISIT(it->parent_stack[i].parent);
Py_VISIT(it->root_element);
Py_VISIT(it->sought_tag);
return 0;
}
/* Helper function for elementiter_next. Add a new parent to the parent stack.
*/
static int
parent_stack_push_new(ElementIterObject *it, ElementObject *parent)
{
ParentLocator *item;
if (it->parent_stack_used >= it->parent_stack_size) {
Py_ssize_t new_size = it->parent_stack_size * 2; /* never overflow */
ParentLocator *parent_stack = it->parent_stack;
PyMem_Resize(parent_stack, ParentLocator, new_size);
if (parent_stack == NULL)
return -1;
it->parent_stack = parent_stack;
it->parent_stack_size = new_size;
}
item = it->parent_stack + it->parent_stack_used++;
Py_INCREF(parent);
item->parent = parent;
item->child_index = 0;
return 0;
}
static PyObject *
elementiter_next(ElementIterObject *it)
{
/* Sub-element iterator.
*
* A short note on gettext: this function serves both the iter() and
* itertext() methods to avoid code duplication. However, there are a few
* small differences in the way these iterations work. Namely:
* - itertext() only yields text from nodes that have it, and continues
* iterating when a node doesn't have text (so it doesn't return any
* node like iter())
* - itertext() also has to handle tail, after finishing with all the
* children of a node.
*/
int rc;
ElementObject *elem;
PyObject *text;
while (1) {
/* Handle the case reached in the beginning and end of iteration, where
* the parent stack is empty. If root_element is NULL and we're here, the
* iterator is exhausted.
*/
if (!it->parent_stack_used) {
if (!it->root_element) {
PyErr_SetNone(PyExc_StopIteration);
return NULL;
}
elem = it->root_element; /* steals a reference */
it->root_element = NULL;
}
else {
/* See if there are children left to traverse in the current parent. If
* yes, visit the next child. If not, pop the stack and try again.
*/
ParentLocator *item = &it->parent_stack[it->parent_stack_used - 1];
Py_ssize_t child_index = item->child_index;
ElementObjectExtra *extra;
elem = item->parent;
extra = elem->extra;
if (!extra || child_index >= extra->length) {
it->parent_stack_used--;
/* Note that extra condition on it->parent_stack_used here;
* this is because itertext() is supposed to only return *inner*
* text, not text following the element it began iteration with.
*/
if (it->gettext && it->parent_stack_used) {
text = element_get_tail(elem);
goto gettext;
}
Py_DECREF(elem);
continue;
}
if (!Element_Check(extra->children[child_index])) {
PyErr_Format(PyExc_AttributeError,
"'%.100s' object has no attribute 'iter'",
Py_TYPE(extra->children[child_index])->tp_name);
return NULL;
}
elem = (ElementObject *)extra->children[child_index];
item->child_index++;
Py_INCREF(elem);
}
if (parent_stack_push_new(it, elem) < 0) {
Py_DECREF(elem);
PyErr_NoMemory();
return NULL;
}
if (it->gettext) {
text = element_get_text(elem);
goto gettext;
}
if (it->sought_tag == Py_None)
return (PyObject *)elem;
rc = PyObject_RichCompareBool(elem->tag, it->sought_tag, Py_EQ);
if (rc > 0)
return (PyObject *)elem;
Py_DECREF(elem);
if (rc < 0)
return NULL;
continue;
gettext:
if (!text) {
Py_DECREF(elem);
return NULL;
}
if (text == Py_None) {
Py_DECREF(elem);
}
else {
Py_INCREF(text);
Py_DECREF(elem);
rc = PyObject_IsTrue(text);
if (rc > 0)
return text;
Py_DECREF(text);
if (rc < 0)
return NULL;
}
}
return NULL;
}
static PyTypeObject ElementIter_Type = {
PyVarObject_HEAD_INIT(NULL, 0)
/* Using the module's name since the pure-Python implementation does not
have such a type. */
"_elementtree._element_iterator", /* tp_name */
sizeof(ElementIterObject), /* tp_basicsize */
0, /* tp_itemsize */
/* methods */
(destructor)elementiter_dealloc, /* tp_dealloc */
0, /* tp_print */
0, /* tp_getattr */
0, /* tp_setattr */
0, /* tp_reserved */
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)elementiter_traverse, /* tp_traverse */
0, /* tp_clear */
0, /* tp_richcompare */
0, /* tp_weaklistoffset */
PyObject_SelfIter, /* tp_iter */
(iternextfunc)elementiter_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 */
};
#define INIT_PARENT_STACK_SIZE 8
static PyObject *
create_elementiter(ElementObject *self, PyObject *tag, int gettext)
{
ElementIterObject *it;
it = PyObject_GC_New(ElementIterObject, &ElementIter_Type);
if (!it)
return NULL;
Py_INCREF(tag);
it->sought_tag = tag;
it->gettext = gettext;
Py_INCREF(self);
it->root_element = self;
PyObject_GC_Track(it);
it->parent_stack = PyMem_New(ParentLocator, INIT_PARENT_STACK_SIZE);
if (it->parent_stack == NULL) {
Py_DECREF(it);
PyErr_NoMemory();
return NULL;
}
it->parent_stack_used = 0;
it->parent_stack_size = INIT_PARENT_STACK_SIZE;
return (PyObject *)it;
}
/* ==================================================================== */
/* the tree builder type */
typedef struct {
PyObject_HEAD
PyObject *root; /* root node (first created node) */
PyObject *this; /* current node */
PyObject *last; /* most recently created node */
PyObject *data; /* data collector (string or list), or NULL */
PyObject *stack; /* element stack */
Py_ssize_t index; /* current stack size (0 means empty) */
PyObject *element_factory;
/* element tracing */
PyObject *events_append; /* the append method of the list of events, or NULL */
PyObject *start_event_obj; /* event objects (NULL to ignore) */
PyObject *end_event_obj;
PyObject *start_ns_event_obj;
PyObject *end_ns_event_obj;
} TreeBuilderObject;
#define TreeBuilder_CheckExact(op) (Py_TYPE(op) == &TreeBuilder_Type)
/* -------------------------------------------------------------------- */
/* constructor and destructor */
static PyObject *
treebuilder_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
TreeBuilderObject *t = (TreeBuilderObject *)type->tp_alloc(type, 0);
if (t != NULL) {
t->root = NULL;
Py_INCREF(Py_None);
t->this = Py_None;
Py_INCREF(Py_None);
t->last = Py_None;
t->data = NULL;
t->element_factory = NULL;
t->stack = PyList_New(20);
if (!t->stack) {
Py_DECREF(t->this);
Py_DECREF(t->last);
Py_DECREF((PyObject *) t);
return NULL;
}
t->index = 0;
t->events_append = NULL;
t->start_event_obj = t->end_event_obj = NULL;
t->start_ns_event_obj = t->end_ns_event_obj = NULL;
}
return (PyObject *)t;
}
/*[clinic input]
_elementtree.TreeBuilder.__init__
element_factory: object = NULL
[clinic start generated code]*/
static int
_elementtree_TreeBuilder___init___impl(TreeBuilderObject *self,
PyObject *element_factory)
/*[clinic end generated code: output=91cfa7558970ee96 input=1b424eeefc35249c]*/
{
if (element_factory) {
Py_INCREF(element_factory);
Py_XSETREF(self->element_factory, element_factory);
}
return 0;
}
static int
treebuilder_gc_traverse(TreeBuilderObject *self, visitproc visit, void *arg)
{
Py_VISIT(self->root);
Py_VISIT(self->this);
Py_VISIT(self->last);
Py_VISIT(self->data);
Py_VISIT(self->stack);
Py_VISIT(self->element_factory);
return 0;
}
static int
treebuilder_gc_clear(TreeBuilderObject *self)
{
Py_CLEAR(self->end_ns_event_obj);
Py_CLEAR(self->start_ns_event_obj);
Py_CLEAR(self->end_event_obj);
Py_CLEAR(self->start_event_obj);
Py_CLEAR(self->events_append);
Py_CLEAR(self->stack);
Py_CLEAR(self->data);
Py_CLEAR(self->last);
Py_CLEAR(self->this);
Py_CLEAR(self->element_factory);
Py_CLEAR(self->root);
return 0;
}
static void
treebuilder_dealloc(TreeBuilderObject *self)
{
PyObject_GC_UnTrack(self);
treebuilder_gc_clear(self);
Py_TYPE(self)->tp_free((PyObject *)self);
}
/* -------------------------------------------------------------------- */
/* helpers for handling of arbitrary element-like objects */
static int
treebuilder_set_element_text_or_tail(PyObject *element, PyObject **data,
PyObject **dest, _Py_Identifier *name)
{
if (Element_CheckExact(element)) {
PyObject *tmp = JOIN_OBJ(*dest);
*dest = JOIN_SET(*data, PyList_CheckExact(*data));
*data = NULL;
Py_DECREF(tmp);
return 0;
}
else {
PyObject *joined = list_join(*data);
int r;
if (joined == NULL)
return -1;
r = _PyObject_SetAttrId(element, name, joined);
Py_DECREF(joined);
if (r < 0)
return -1;
Py_CLEAR(*data);
return 0;
}
}
LOCAL(int)
treebuilder_flush_data(TreeBuilderObject* self)
{
PyObject *element = self->last;
if (!self->data) {
return 0;
}
if (self->this == element) {
_Py_IDENTIFIER(text);
return treebuilder_set_element_text_or_tail(
element, &self->data,
&((ElementObject *) element)->text, &PyId_text);
}
else {
_Py_IDENTIFIER(tail);
return treebuilder_set_element_text_or_tail(
element, &self->data,
&((ElementObject *) element)->tail, &PyId_tail);
}
}
static int
treebuilder_add_subelement(PyObject *element, PyObject *child)
{
_Py_IDENTIFIER(append);
if (Element_CheckExact(element)) {
ElementObject *elem = (ElementObject *) element;
return element_add_subelement(elem, child);
}
else {
PyObject *res;
res = _PyObject_CallMethodId(element, &PyId_append, "O", child);
if (res == NULL)
return -1;
Py_DECREF(res);
return 0;
}
}
LOCAL(int)
treebuilder_append_event(TreeBuilderObject *self, PyObject *action,
PyObject *node)
{
if (action != NULL) {
PyObject *res;
PyObject *event = PyTuple_Pack(2, action, node);
if (event == NULL)
return -1;
res = PyObject_CallFunctionObjArgs(self->events_append, event, NULL);
Py_DECREF(event);
if (res == NULL)
return -1;
Py_DECREF(res);
}
return 0;
}
/* -------------------------------------------------------------------- */
/* handlers */
LOCAL(PyObject*)
treebuilder_handle_start(TreeBuilderObject* self, PyObject* tag,
PyObject* attrib)
{
PyObject* node;
PyObject* this;
elementtreestate *st = ET_STATE_GLOBAL;
if (treebuilder_flush_data(self) < 0) {
return NULL;
}
if (!self->element_factory || self->element_factory == Py_None) {
node = create_new_element(tag, attrib);
} else if (attrib == Py_None) {
attrib = PyDict_New();
if (!attrib)
return NULL;
node = PyObject_CallFunction(self->element_factory, "OO", tag, attrib);
Py_DECREF(attrib);
}
else {
node = PyObject_CallFunction(self->element_factory, "OO", tag, attrib);
}
if (!node) {
return NULL;
}
this = self->this;
if (this != Py_None) {
if (treebuilder_add_subelement(this, node) < 0)
goto error;
} else {
if (self->root) {
PyErr_SetString(
st->parseerror_obj,
"multiple elements on top level"
);
goto error;
}
Py_INCREF(node);
self->root = node;
}
if (self->index < PyList_GET_SIZE(self->stack)) {
if (PyList_SetItem(self->stack, self->index, this) < 0)
goto error;
Py_INCREF(this);
} else {
if (PyList_Append(self->stack, this) < 0)
goto error;
}
self->index++;
Py_INCREF(node);
Py_SETREF(self->this, node);
Py_INCREF(node);
Py_SETREF(self->last, node);
if (treebuilder_append_event(self, self->start_event_obj, node) < 0)
goto error;
return node;
error:
Py_DECREF(node);
return NULL;
}
LOCAL(PyObject*)
treebuilder_handle_data(TreeBuilderObject* self, PyObject* data)
{
if (!self->data) {
if (self->last == Py_None) {
/* ignore calls to data before the first call to start */
Py_RETURN_NONE;
}
/* store the first item as is */
Py_INCREF(data); self->data = data;
} else {
/* more than one item; use a list to collect items */
if (PyBytes_CheckExact(self->data) && Py_REFCNT(self->data) == 1 &&
PyBytes_CheckExact(data) && PyBytes_GET_SIZE(data) == 1) {
/* XXX this code path unused in Python 3? */
/* expat often generates single character data sections; handle
the most common case by resizing the existing string... */
Py_ssize_t size = PyBytes_GET_SIZE(self->data);
if (_PyBytes_Resize(&self->data, size + 1) < 0)
return NULL;
PyBytes_AS_STRING(self->data)[size] = PyBytes_AS_STRING(data)[0];
} else if (PyList_CheckExact(self->data)) {
if (PyList_Append(self->data, data) < 0)
return NULL;
} else {
PyObject* list = PyList_New(2);
if (!list)
return NULL;
PyList_SET_ITEM(list, 0, self->data);
Py_INCREF(data); PyList_SET_ITEM(list, 1, data);
self->data = list;
}
}
Py_RETURN_NONE;
}
LOCAL(PyObject*)
treebuilder_handle_end(TreeBuilderObject* self, PyObject* tag)
{
PyObject* item;
if (treebuilder_flush_data(self) < 0) {
return NULL;
}
if (self->index == 0) {
PyErr_SetString(
PyExc_IndexError,
"pop from empty stack"
);
return NULL;
}
item = self->last;
self->last = self->this;
self->index--;
self->this = PyList_GET_ITEM(self->stack, self->index);
Py_INCREF(self->this);
Py_DECREF(item);
if (treebuilder_append_event(self, self->end_event_obj, self->last) < 0)
return NULL;
Py_INCREF(self->last);
return (PyObject*) self->last;
}
/* -------------------------------------------------------------------- */
/* methods (in alphabetical order) */
/*[clinic input]
_elementtree.TreeBuilder.data
data: object
/
[clinic start generated code]*/
static PyObject *
_elementtree_TreeBuilder_data(TreeBuilderObject *self, PyObject *data)
/*[clinic end generated code: output=69144c7100795bb2 input=a0540c532b284d29]*/
{
return treebuilder_handle_data(self, data);
}
/*[clinic input]
_elementtree.TreeBuilder.end
tag: object
/
[clinic start generated code]*/
static PyObject *
_elementtree_TreeBuilder_end(TreeBuilderObject *self, PyObject *tag)
/*[clinic end generated code: output=9a98727cc691cd9d input=22dc3674236f5745]*/
{
return treebuilder_handle_end(self, tag);
}
LOCAL(PyObject*)
treebuilder_done(TreeBuilderObject* self)
{
PyObject* res;
/* FIXME: check stack size? */
if (self->root)
res = self->root;
else
res = Py_None;
Py_INCREF(res);
return res;
}
/*[clinic input]
_elementtree.TreeBuilder.close
[clinic start generated code]*/
static PyObject *
_elementtree_TreeBuilder_close_impl(TreeBuilderObject *self)
/*[clinic end generated code: output=b441fee3202f61ee input=f7c9c65dc718de14]*/
{
return treebuilder_done(self);
}
/*[clinic input]
_elementtree.TreeBuilder.start
tag: object
attrs: object = None
/
[clinic start generated code]*/
static PyObject *
_elementtree_TreeBuilder_start_impl(TreeBuilderObject *self, PyObject *tag,
PyObject *attrs)
/*[clinic end generated code: output=e7e9dc2861349411 input=95fc1758dd042c65]*/
{
return treebuilder_handle_start(self, tag, attrs);
}
/* ==================================================================== */
/* the expat interface */
/* The PyExpat_CAPI structure is an immutable dispatch table, so it can be
* cached globally without being in per-module state.
*/
static struct PyExpat_CAPI *expat_capi;
#define EXPAT(func) (expat_capi->func)
static XML_Memory_Handling_Suite ExpatMemoryHandler = {
PyObject_Malloc, PyObject_Realloc, PyObject_Free};
typedef struct {
PyObject_HEAD
XML_Parser parser;
PyObject *target;
PyObject *entity;
PyObject *names;
PyObject *handle_start;
PyObject *handle_data;
PyObject *handle_end;
PyObject *handle_comment;
PyObject *handle_pi;
PyObject *handle_doctype;
PyObject *handle_close;
} XMLParserObject;
static PyObject *
_elementtree_XMLParser_doctype(XMLParserObject* self, PyObject** args,
Py_ssize_t nargs);
static PyObject *
_elementtree_XMLParser_doctype_impl(XMLParserObject *self, PyObject *name,
PyObject *pubid, PyObject *system);
/* helpers */
LOCAL(PyObject*)
makeuniversal(XMLParserObject* self, const char* string)
{
/* convert a UTF-8 tag/attribute name from the expat parser
to a universal name string */
Py_ssize_t size = (Py_ssize_t) strlen(string);
PyObject* key;
PyObject* value;
/* look the 'raw' name up in the names dictionary */
key = PyBytes_FromStringAndSize(string, size);
if (!key)
return NULL;
value = PyDict_GetItem(self->names, key);
if (value) {
Py_INCREF(value);
} else {
/* new name. convert to universal name, and decode as
necessary */
PyObject* tag;
char* p;
Py_ssize_t i;
/* look for namespace separator */
for (i = 0; i < size; i++)
if (string[i] == '}')
break;
if (i != size) {
/* convert to universal name */
tag = PyBytes_FromStringAndSize(NULL, size+1);
if (tag == NULL) {
Py_DECREF(key);
return NULL;
}
p = PyBytes_AS_STRING(tag);
p[0] = '{';
memcpy(p+1, string, size);
size++;
} else {
/* plain name; use key as tag */
Py_INCREF(key);
tag = key;
}
/* decode universal name */
p = PyBytes_AS_STRING(tag);
value = PyUnicode_DecodeUTF8(p, size, "strict");
Py_DECREF(tag);
if (!value) {
Py_DECREF(key);
return NULL;
}
/* add to names dictionary */
if (PyDict_SetItem(self->names, key, value) < 0) {
Py_DECREF(key);
Py_DECREF(value);
return NULL;
}
}
Py_DECREF(key);
return value;
}
/* Set the ParseError exception with the given parameters.
* If message is not NULL, it's used as the error string. Otherwise, the
* message string is the default for the given error_code.
*/
static void
expat_set_error(enum XML_Error error_code, Py_ssize_t line, Py_ssize_t column,
const char *message)
{
PyObject *errmsg, *error, *position, *code;
elementtreestate *st = ET_STATE_GLOBAL;
errmsg = PyUnicode_FromFormat("%s: line %zd, column %zd",
message ? message : EXPAT(ErrorString)(error_code),
line, column);
if (errmsg == NULL)
return;
error = PyObject_CallFunction(st->parseerror_obj, "O", errmsg);
Py_DECREF(errmsg);
if (!error)
return;
/* Add code and position attributes */
code = PyLong_FromLong((long)error_code);
if (!code) {
Py_DECREF(error);
return;
}
if (PyObject_SetAttrString(error, "code", code) == -1) {
Py_DECREF(error);
Py_DECREF(code);
return;
}
Py_DECREF(code);
position = Py_BuildValue("(nn)", line, column);
if (!position) {
Py_DECREF(error);
return;
}
if (PyObject_SetAttrString(error, "position", position) == -1) {
Py_DECREF(error);
Py_DECREF(position);
return;
}
Py_DECREF(position);
PyErr_SetObject(st->parseerror_obj, error);
Py_DECREF(error);
}
/* -------------------------------------------------------------------- */
/* handlers */
static void
expat_default_handler(XMLParserObject* self, const XML_Char* data_in,
int data_len)
{
PyObject* key;
PyObject* value;
PyObject* res;
if (data_len < 2 || data_in[0] != '&')
return;
if (PyErr_Occurred())
return;
key = PyUnicode_DecodeUTF8(data_in + 1, data_len - 2, "strict");
if (!key)
return;
value = PyDict_GetItem(self->entity, key);
if (value) {
if (TreeBuilder_CheckExact(self->target))
res = treebuilder_handle_data(
(TreeBuilderObject*) self->target, value
);
else if (self->handle_data)
res = PyObject_CallFunction(self->handle_data, "O", value);
else
res = NULL;
Py_XDECREF(res);
} else if (!PyErr_Occurred()) {
/* Report the first error, not the last */
char message[128] = "undefined entity ";
strncat(message, data_in, data_len < 100?data_len:100);
expat_set_error(
XML_ERROR_UNDEFINED_ENTITY,
EXPAT(GetErrorLineNumber)(self->parser),
EXPAT(GetErrorColumnNumber)(self->parser),
message
);
}
Py_DECREF(key);
}
static void
expat_start_handler(XMLParserObject* self, const XML_Char* tag_in,
const XML_Char **attrib_in)
{
PyObject* res;
PyObject* tag;
PyObject* attrib;
int ok;
if (PyErr_Occurred())
return;
/* tag name */
tag = makeuniversal(self, tag_in);
if (!tag)
return; /* parser will look for errors */
/* attributes */
if (attrib_in[0]) {
attrib = PyDict_New();
if (!attrib) {
Py_DECREF(tag);
return;
}
while (attrib_in[0] && attrib_in[1]) {
PyObject* key = makeuniversal(self, attrib_in[0]);
PyObject* value = PyUnicode_DecodeUTF8(attrib_in[1], strlen(attrib_in[1]), "strict");
if (!key || !value) {
Py_XDECREF(value);
Py_XDECREF(key);
Py_DECREF(attrib);
Py_DECREF(tag);
return;
}
ok = PyDict_SetItem(attrib, key, value);
Py_DECREF(value);
Py_DECREF(key);
if (ok < 0) {
Py_DECREF(attrib);
Py_DECREF(tag);
return;
}
attrib_in += 2;
}
} else {
Py_INCREF(Py_None);
attrib = Py_None;
}
if (TreeBuilder_CheckExact(self->target)) {
/* shortcut */
res = treebuilder_handle_start((TreeBuilderObject*) self->target,
tag, attrib);
}
else if (self->handle_start) {
if (attrib == Py_None) {
Py_DECREF(attrib);
attrib = PyDict_New();
if (!attrib) {
Py_DECREF(tag);
return;
}
}
res = PyObject_CallFunction(self->handle_start, "OO", tag, attrib);
} else
res = NULL;
Py_DECREF(tag);
Py_DECREF(attrib);
Py_XDECREF(res);
}
static void
expat_data_handler(XMLParserObject* self, const XML_Char* data_in,
int data_len)
{
PyObject* data;
PyObject* res;
if (PyErr_Occurred())
return;
data = PyUnicode_DecodeUTF8(data_in, data_len, "strict");
if (!data)
return; /* parser will look for errors */
if (TreeBuilder_CheckExact(self->target))
/* shortcut */
res = treebuilder_handle_data((TreeBuilderObject*) self->target, data);
else if (self->handle_data)
res = PyObject_CallFunction(self->handle_data, "O", data);
else
res = NULL;
Py_DECREF(data);
Py_XDECREF(res);
}
static void
expat_end_handler(XMLParserObject* self, const XML_Char* tag_in)
{
PyObject* tag;
PyObject* res = NULL;
if (PyErr_Occurred())
return;
if (TreeBuilder_CheckExact(self->target))
/* shortcut */
/* the standard tree builder doesn't look at the end tag */
res = treebuilder_handle_end(
(TreeBuilderObject*) self->target, Py_None
);
else if (self->handle_end) {
tag = makeuniversal(self, tag_in);
if (tag) {
res = PyObject_CallFunction(self->handle_end, "O", tag);
Py_DECREF(tag);
}
}
Py_XDECREF(res);
}
static void
expat_start_ns_handler(XMLParserObject* self, const XML_Char* prefix,
const XML_Char *uri)
{
TreeBuilderObject *target = (TreeBuilderObject*) self->target;
PyObject *parcel;
if (PyErr_Occurred())
return;
if (!target->events_append || !target->start_ns_event_obj)
return;
if (!uri)
uri = "";
if (!prefix)
prefix = "";
parcel = Py_BuildValue("ss", prefix, uri);
if (!parcel)
return;
treebuilder_append_event(target, target->start_ns_event_obj, parcel);
Py_DECREF(parcel);
}
static void
expat_end_ns_handler(XMLParserObject* self, const XML_Char* prefix_in)
{
TreeBuilderObject *target = (TreeBuilderObject*) self->target;
if (PyErr_Occurred())
return;
if (!target->events_append)
return;
treebuilder_append_event(target, target->end_ns_event_obj, Py_None);
}
static void
expat_comment_handler(XMLParserObject* self, const XML_Char* comment_in)
{
PyObject* comment;
PyObject* res;
if (PyErr_Occurred())
return;
if (self->handle_comment) {
comment = PyUnicode_DecodeUTF8(comment_in, strlen(comment_in), "strict");
if (comment) {
res = PyObject_CallFunction(self->handle_comment, "O", comment);
Py_XDECREF(res);
Py_DECREF(comment);
}
}
}
static void
expat_start_doctype_handler(XMLParserObject *self,
const XML_Char *doctype_name,
const XML_Char *sysid,
const XML_Char *pubid,
int has_internal_subset)
{
PyObject *self_pyobj = (PyObject *)self;
PyObject *doctype_name_obj, *sysid_obj, *pubid_obj;
PyObject *parser_doctype = NULL;
PyObject *res = NULL;
if (PyErr_Occurred())
return;
doctype_name_obj = makeuniversal(self, doctype_name);
if (!doctype_name_obj)
return;
if (sysid) {
sysid_obj = makeuniversal(self, sysid);
if (!sysid_obj) {
Py_DECREF(doctype_name_obj);
return;
}
} else {
Py_INCREF(Py_None);
sysid_obj = Py_None;
}
if (pubid) {
pubid_obj = makeuniversal(self, pubid);
if (!pubid_obj) {
Py_DECREF(doctype_name_obj);
Py_DECREF(sysid_obj);
return;
}
} else {
Py_INCREF(Py_None);
pubid_obj = Py_None;
}
/* If the target has a handler for doctype, call it. */
if (self->handle_doctype) {
res = PyObject_CallFunction(self->handle_doctype, "OOO",
doctype_name_obj, pubid_obj, sysid_obj);
Py_CLEAR(res);
}
else {
/* Now see if the parser itself has a doctype method. If yes and it's
* a custom method, call it but warn about deprecation. If it's only
* the vanilla XMLParser method, do nothing.
*/
parser_doctype = PyObject_GetAttrString(self_pyobj, "doctype");
if (parser_doctype &&
!(PyCFunction_Check(parser_doctype) &&
PyCFunction_GET_SELF(parser_doctype) == self_pyobj &&
PyCFunction_GET_FUNCTION(parser_doctype) ==
(PyCFunction) _elementtree_XMLParser_doctype)) {
res = _elementtree_XMLParser_doctype_impl(self, doctype_name_obj,
pubid_obj, sysid_obj);
if (!res)
goto clear;
Py_DECREF(res);
res = PyObject_CallFunction(parser_doctype, "OOO",
doctype_name_obj, pubid_obj, sysid_obj);
Py_CLEAR(res);
}
}
clear:
Py_XDECREF(parser_doctype);
Py_DECREF(doctype_name_obj);
Py_DECREF(pubid_obj);
Py_DECREF(sysid_obj);
}
static void
expat_pi_handler(XMLParserObject* self, const XML_Char* target_in,
const XML_Char* data_in)
{
PyObject* target;
PyObject* data;
PyObject* res;
if (PyErr_Occurred())
return;
if (self->handle_pi) {
target = PyUnicode_DecodeUTF8(target_in, strlen(target_in), "strict");
data = PyUnicode_DecodeUTF8(data_in, strlen(data_in), "strict");
if (target && data) {
res = PyObject_CallFunction(self->handle_pi, "OO", target, data);
Py_XDECREF(res);
Py_DECREF(data);
Py_DECREF(target);
} else {
Py_XDECREF(data);
Py_XDECREF(target);
}
}
}
/* -------------------------------------------------------------------- */
static PyObject *
xmlparser_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
XMLParserObject *self = (XMLParserObject *)type->tp_alloc(type, 0);
if (self) {
self->parser = NULL;
self->target = self->entity = self->names = NULL;
self->handle_start = self->handle_data = self->handle_end = NULL;
self->handle_comment = self->handle_pi = self->handle_close = NULL;
self->handle_doctype = NULL;
}
return (PyObject *)self;
}
static int
ignore_attribute_error(PyObject *value)
{
if (value == NULL) {
if (!PyErr_ExceptionMatches(PyExc_AttributeError)) {
return -1;
}
PyErr_Clear();
}
return 0;
}
/*[clinic input]
_elementtree.XMLParser.__init__
html: object = NULL
target: object = NULL
encoding: str(accept={str, NoneType}) = NULL
[clinic start generated code]*/
static int
_elementtree_XMLParser___init___impl(XMLParserObject *self, PyObject *html,
PyObject *target, const char *encoding)
/*[clinic end generated code: output=d6a16c63dda54441 input=155bc5695baafffd]*/
{
self->entity = PyDict_New();
if (!self->entity)
return -1;
self->names = PyDict_New();
if (!self->names) {
Py_CLEAR(self->entity);
return -1;
}
self->parser = EXPAT(ParserCreate_MM)(encoding, &ExpatMemoryHandler, "}");
if (!self->parser) {
Py_CLEAR(self->entity);
Py_CLEAR(self->names);
PyErr_NoMemory();
return -1;
}
/* expat < 2.1.0 has no XML_SetHashSalt() */
if (EXPAT(SetHashSalt) != NULL) {
EXPAT(SetHashSalt)(self->parser,
(unsigned long)_Py_HashSecret.expat.hashsalt);
}
if (target) {
Py_INCREF(target);
} else {
target = treebuilder_new(&TreeBuilder_Type, NULL, NULL);
if (!target) {
Py_CLEAR(self->entity);
Py_CLEAR(self->names);
return -1;
}
}
self->target = target;
self->handle_start = PyObject_GetAttrString(target, "start");
if (ignore_attribute_error(self->handle_start)) {
return -1;
}
self->handle_data = PyObject_GetAttrString(target, "data");
if (ignore_attribute_error(self->handle_data)) {
return -1;
}
self->handle_end = PyObject_GetAttrString(target, "end");
if (ignore_attribute_error(self->handle_end)) {
return -1;
}
self->handle_comment = PyObject_GetAttrString(target, "comment");
if (ignore_attribute_error(self->handle_comment)) {
return -1;
}
self->handle_pi = PyObject_GetAttrString(target, "pi");
if (ignore_attribute_error(self->handle_pi)) {
return -1;
}
self->handle_close = PyObject_GetAttrString(target, "close");
if (ignore_attribute_error(self->handle_close)) {
return -1;
}
self->handle_doctype = PyObject_GetAttrString(target, "doctype");
if (ignore_attribute_error(self->handle_doctype)) {
return -1;
}
/* configure parser */
EXPAT(SetUserData)(self->parser, self);
EXPAT(SetElementHandler)(
self->parser,
(XML_StartElementHandler) expat_start_handler,
(XML_EndElementHandler) expat_end_handler
);
EXPAT(SetDefaultHandlerExpand)(
self->parser,
(XML_DefaultHandler) expat_default_handler
);
EXPAT(SetCharacterDataHandler)(
self->parser,
(XML_CharacterDataHandler) expat_data_handler
);
if (self->handle_comment)
EXPAT(SetCommentHandler)(
self->parser,
(XML_CommentHandler) expat_comment_handler
);
if (self->handle_pi)
EXPAT(SetProcessingInstructionHandler)(
self->parser,
(XML_ProcessingInstructionHandler) expat_pi_handler
);
EXPAT(SetStartDoctypeDeclHandler)(
self->parser,
(XML_StartDoctypeDeclHandler) expat_start_doctype_handler
);
EXPAT(SetUnknownEncodingHandler)(
self->parser,
EXPAT(DefaultUnknownEncodingHandler), NULL
);
return 0;
}
static int
xmlparser_gc_traverse(XMLParserObject *self, visitproc visit, void *arg)
{
Py_VISIT(self->handle_close);
Py_VISIT(self->handle_pi);
Py_VISIT(self->handle_comment);
Py_VISIT(self->handle_end);
Py_VISIT(self->handle_data);
Py_VISIT(self->handle_start);
Py_VISIT(self->target);
Py_VISIT(self->entity);
Py_VISIT(self->names);
return 0;
}
static int
xmlparser_gc_clear(XMLParserObject *self)
{
if (self->parser != NULL) {
XML_Parser parser = self->parser;
self->parser = NULL;
EXPAT(ParserFree)(parser);
}
Py_CLEAR(self->handle_close);
Py_CLEAR(self->handle_pi);
Py_CLEAR(self->handle_comment);
Py_CLEAR(self->handle_end);
Py_CLEAR(self->handle_data);
Py_CLEAR(self->handle_start);
Py_CLEAR(self->handle_doctype);
Py_CLEAR(self->target);
Py_CLEAR(self->entity);
Py_CLEAR(self->names);
return 0;
}
static void
xmlparser_dealloc(XMLParserObject* self)
{
PyObject_GC_UnTrack(self);
xmlparser_gc_clear(self);
Py_TYPE(self)->tp_free((PyObject *)self);
}
LOCAL(PyObject*)
expat_parse(XMLParserObject* self, const char* data, int data_len, int final)
{
int ok;
assert(!PyErr_Occurred());
ok = EXPAT(Parse)(self->parser, data, data_len, final);
if (PyErr_Occurred())
return NULL;
if (!ok) {
expat_set_error(
EXPAT(GetErrorCode)(self->parser),
EXPAT(GetErrorLineNumber)(self->parser),
EXPAT(GetErrorColumnNumber)(self->parser),
NULL
);
return NULL;
}
Py_RETURN_NONE;
}
/*[clinic input]
_elementtree.XMLParser.close
[clinic start generated code]*/
static PyObject *
_elementtree_XMLParser_close_impl(XMLParserObject *self)
/*[clinic end generated code: output=d68d375dd23bc7fb input=ca7909ca78c3abfe]*/
{
/* end feeding data to parser */
PyObject* res;
res = expat_parse(self, "", 0, 1);
if (!res)
return NULL;
if (TreeBuilder_CheckExact(self->target)) {
Py_DECREF(res);
return treebuilder_done((TreeBuilderObject*) self->target);
}
else if (self->handle_close) {
Py_DECREF(res);
return _PyObject_CallNoArg(self->handle_close);
}
else {
return res;
}
}
/*[clinic input]
_elementtree.XMLParser.feed
data: object
/
[clinic start generated code]*/
static PyObject *
_elementtree_XMLParser_feed(XMLParserObject *self, PyObject *data)
/*[clinic end generated code: output=e42b6a78eec7446d input=fe231b6b8de3ce1f]*/
{
/* feed data to parser */
if (PyUnicode_Check(data)) {
Py_ssize_t data_len;
const char *data_ptr = PyUnicode_AsUTF8AndSize(data, &data_len);
if (data_ptr == NULL)
return NULL;
if (data_len > INT_MAX) {
PyErr_SetString(PyExc_OverflowError, "size does not fit in an int");
return NULL;
}
/* Explicitly set UTF-8 encoding. Return code ignored. */
(void)EXPAT(SetEncoding)(self->parser, "utf-8");
return expat_parse(self, data_ptr, (int)data_len, 0);
}
else {
Py_buffer view;
PyObject *res;
if (PyObject_GetBuffer(data, &view, PyBUF_SIMPLE) < 0)
return NULL;
if (view.len > INT_MAX) {
PyBuffer_Release(&view);
PyErr_SetString(PyExc_OverflowError, "size does not fit in an int");
return NULL;
}
res = expat_parse(self, view.buf, (int)view.len, 0);
PyBuffer_Release(&view);
return res;
}
}
/*[clinic input]
_elementtree.XMLParser._parse_whole
file: object
/
[clinic start generated code]*/
static PyObject *
_elementtree_XMLParser__parse_whole(XMLParserObject *self, PyObject *file)
/*[clinic end generated code: output=f797197bb818dda3 input=19ecc893b6f3e752]*/
{
/* (internal) parse the whole input, until end of stream */
PyObject* reader;
PyObject* buffer;
PyObject* temp;
PyObject* res;
reader = PyObject_GetAttrString(file, "read");
if (!reader)
return NULL;
/* read from open file object */
for (;;) {
buffer = PyObject_CallFunction(reader, "i", 64*1024);
if (!buffer) {
/* read failed (e.g. due to KeyboardInterrupt) */
Py_DECREF(reader);
return NULL;
}
if (PyUnicode_CheckExact(buffer)) {
/* A unicode object is encoded into bytes using UTF-8 */
if (PyUnicode_GET_LENGTH(buffer) == 0) {
Py_DECREF(buffer);
break;
}
temp = PyUnicode_AsEncodedString(buffer, "utf-8", "surrogatepass");
Py_DECREF(buffer);
if (!temp) {
/* Propagate exception from PyUnicode_AsEncodedString */
Py_DECREF(reader);
return NULL;
}
buffer = temp;
}
else if (!PyBytes_CheckExact(buffer) || PyBytes_GET_SIZE(buffer) == 0) {
Py_DECREF(buffer);
break;
}
if (PyBytes_GET_SIZE(buffer) > INT_MAX) {
Py_DECREF(buffer);
Py_DECREF(reader);
PyErr_SetString(PyExc_OverflowError, "size does not fit in an int");
return NULL;
}
res = expat_parse(
self, PyBytes_AS_STRING(buffer), (int)PyBytes_GET_SIZE(buffer), 0
);
Py_DECREF(buffer);
if (!res) {
Py_DECREF(reader);
return NULL;
}
Py_DECREF(res);
}
Py_DECREF(reader);
res = expat_parse(self, "", 0, 1);
if (res && TreeBuilder_CheckExact(self->target)) {
Py_DECREF(res);
return treebuilder_done((TreeBuilderObject*) self->target);
}
return res;
}
/*[clinic input]
_elementtree.XMLParser.doctype
name: object
pubid: object
system: object
/
[clinic start generated code]*/
static PyObject *
_elementtree_XMLParser_doctype_impl(XMLParserObject *self, PyObject *name,
PyObject *pubid, PyObject *system)
/*[clinic end generated code: output=10fb50c2afded88d input=84050276cca045e1]*/
{
if (PyErr_WarnEx(PyExc_DeprecationWarning,
"This method of XMLParser is deprecated. Define"
" doctype() method on the TreeBuilder target.",
1) < 0) {
return NULL;
}
Py_RETURN_NONE;
}
/*[clinic input]
_elementtree.XMLParser._setevents
events_queue: object
events_to_report: object = None
/
[clinic start generated code]*/
static PyObject *
_elementtree_XMLParser__setevents_impl(XMLParserObject *self,
PyObject *events_queue,
PyObject *events_to_report)
/*[clinic end generated code: output=1440092922b13ed1 input=abf90830a1c3b0fc]*/
{
/* activate element event reporting */
Py_ssize_t i;
TreeBuilderObject *target;
PyObject *events_append, *events_seq;
if (!TreeBuilder_CheckExact(self->target)) {
PyErr_SetString(
PyExc_TypeError,
"event handling only supported for ElementTree.TreeBuilder "
"targets"
);
return NULL;
}
target = (TreeBuilderObject*) self->target;
events_append = PyObject_GetAttrString(events_queue, "append");
if (events_append == NULL)
return NULL;
Py_XSETREF(target->events_append, events_append);
/* clear out existing events */
Py_CLEAR(target->start_event_obj);
Py_CLEAR(target->end_event_obj);
Py_CLEAR(target->start_ns_event_obj);
Py_CLEAR(target->end_ns_event_obj);
if (events_to_report == Py_None) {
/* default is "end" only */
target->end_event_obj = PyUnicode_FromString("end");
Py_RETURN_NONE;
}
if (!(events_seq = PySequence_Fast(events_to_report,
"events must be a sequence"))) {
return NULL;
}
for (i = 0; i < PySequence_Size(events_seq); ++i) {
PyObject *event_name_obj = PySequence_Fast_GET_ITEM(events_seq, i);
char *event_name = NULL;
if (PyUnicode_Check(event_name_obj)) {
event_name = PyUnicode_AsUTF8(event_name_obj);
} else if (PyBytes_Check(event_name_obj)) {
event_name = PyBytes_AS_STRING(event_name_obj);
}
if (event_name == NULL) {
Py_DECREF(events_seq);
PyErr_Format(PyExc_ValueError, "invalid events sequence");
return NULL;
}
Py_INCREF(event_name_obj);
if (strcmp(event_name, "start") == 0) {
Py_XSETREF(target->start_event_obj, event_name_obj);
} else if (strcmp(event_name, "end") == 0) {
Py_XSETREF(target->end_event_obj, event_name_obj);
} else if (strcmp(event_name, "start-ns") == 0) {
Py_XSETREF(target->start_ns_event_obj, event_name_obj);
EXPAT(SetNamespaceDeclHandler)(
self->parser,
(XML_StartNamespaceDeclHandler) expat_start_ns_handler,
(XML_EndNamespaceDeclHandler) expat_end_ns_handler
);
} else if (strcmp(event_name, "end-ns") == 0) {
Py_XSETREF(target->end_ns_event_obj, event_name_obj);
EXPAT(SetNamespaceDeclHandler)(
self->parser,
(XML_StartNamespaceDeclHandler) expat_start_ns_handler,
(XML_EndNamespaceDeclHandler) expat_end_ns_handler
);
} else {
Py_DECREF(event_name_obj);
Py_DECREF(events_seq);
PyErr_Format(PyExc_ValueError, "unknown event '%s'", event_name);
return NULL;
}
}
Py_DECREF(events_seq);
Py_RETURN_NONE;
}
static PyObject*
xmlparser_getattro(XMLParserObject* self, PyObject* nameobj)
{
if (PyUnicode_Check(nameobj)) {
PyObject* res;
if (_PyUnicode_EqualToASCIIString(nameobj, "entity"))
res = self->entity;
else if (_PyUnicode_EqualToASCIIString(nameobj, "target"))
res = self->target;
else if (_PyUnicode_EqualToASCIIString(nameobj, "version")) {
return PyUnicode_FromFormat(
"Expat %d.%d.%d", XML_MAJOR_VERSION,
XML_MINOR_VERSION, XML_MICRO_VERSION);
}
else
goto generic;
Py_INCREF(res);
return res;
}
generic:
return PyObject_GenericGetAttr((PyObject*) self, nameobj);
}
#include "third_party/python/Modules/clinic/_elementtree.inc"
static PyMethodDef element_methods[] = {
_ELEMENTTREE_ELEMENT_CLEAR_METHODDEF
_ELEMENTTREE_ELEMENT_GET_METHODDEF
_ELEMENTTREE_ELEMENT_SET_METHODDEF
_ELEMENTTREE_ELEMENT_FIND_METHODDEF
_ELEMENTTREE_ELEMENT_FINDTEXT_METHODDEF
_ELEMENTTREE_ELEMENT_FINDALL_METHODDEF
_ELEMENTTREE_ELEMENT_APPEND_METHODDEF
_ELEMENTTREE_ELEMENT_EXTEND_METHODDEF
_ELEMENTTREE_ELEMENT_INSERT_METHODDEF
_ELEMENTTREE_ELEMENT_REMOVE_METHODDEF
_ELEMENTTREE_ELEMENT_ITER_METHODDEF
_ELEMENTTREE_ELEMENT_ITERTEXT_METHODDEF
_ELEMENTTREE_ELEMENT_ITERFIND_METHODDEF
{"getiterator", (PyCFunction)_elementtree_Element_iter, METH_FASTCALL | METH_KEYWORDS, _elementtree_Element_iter__doc__},
_ELEMENTTREE_ELEMENT_GETCHILDREN_METHODDEF
_ELEMENTTREE_ELEMENT_ITEMS_METHODDEF
_ELEMENTTREE_ELEMENT_KEYS_METHODDEF
_ELEMENTTREE_ELEMENT_MAKEELEMENT_METHODDEF
_ELEMENTTREE_ELEMENT___COPY___METHODDEF
_ELEMENTTREE_ELEMENT___DEEPCOPY___METHODDEF
_ELEMENTTREE_ELEMENT___SIZEOF___METHODDEF
_ELEMENTTREE_ELEMENT___GETSTATE___METHODDEF
_ELEMENTTREE_ELEMENT___SETSTATE___METHODDEF
{NULL, NULL}
};
static PyMappingMethods element_as_mapping = {
(lenfunc) element_length,
(binaryfunc) element_subscr,
(objobjargproc) element_ass_subscr,
};
static PyGetSetDef element_getsetlist[] = {
{"tag",
(getter)element_tag_getter,
(setter)element_tag_setter,
"A string identifying what kind of data this element represents"},
{"text",
(getter)element_text_getter,
(setter)element_text_setter,
"A string of text directly after the start tag, or None"},
{"tail",
(getter)element_tail_getter,
(setter)element_tail_setter,
"A string of text directly after the end tag, or None"},
{"attrib",
(getter)element_attrib_getter,
(setter)element_attrib_setter,
"A dictionary containing the element's attributes"},
{NULL},
};
static PyTypeObject Element_Type = {
PyVarObject_HEAD_INIT(NULL, 0)
"xml.etree.ElementTree.Element", sizeof(ElementObject), 0,
/* methods */
(destructor)element_dealloc, /* tp_dealloc */
0, /* tp_print */
0, /* tp_getattr */
0, /* tp_setattr */
0, /* tp_reserved */
(reprfunc)element_repr, /* tp_repr */
0, /* tp_as_number */
&element_as_sequence, /* tp_as_sequence */
&element_as_mapping, /* 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 */
0, /* tp_doc */
(traverseproc)element_gc_traverse, /* tp_traverse */
(inquiry)element_gc_clear, /* tp_clear */
0, /* tp_richcompare */
offsetof(ElementObject, weakreflist), /* tp_weaklistoffset */
0, /* tp_iter */
0, /* tp_iternext */
element_methods, /* tp_methods */
0, /* tp_members */
element_getsetlist, /* tp_getset */
0, /* tp_base */
0, /* tp_dict */
0, /* tp_descr_get */
0, /* tp_descr_set */
0, /* tp_dictoffset */
(initproc)element_init, /* tp_init */
PyType_GenericAlloc, /* tp_alloc */
element_new, /* tp_new */
0, /* tp_free */
};
static PyMethodDef treebuilder_methods[] = {
_ELEMENTTREE_TREEBUILDER_DATA_METHODDEF
_ELEMENTTREE_TREEBUILDER_START_METHODDEF
_ELEMENTTREE_TREEBUILDER_END_METHODDEF
_ELEMENTTREE_TREEBUILDER_CLOSE_METHODDEF
{NULL, NULL}
};
static PyTypeObject TreeBuilder_Type = {
PyVarObject_HEAD_INIT(NULL, 0)
"xml.etree.ElementTree.TreeBuilder", sizeof(TreeBuilderObject), 0,
/* methods */
(destructor)treebuilder_dealloc, /* tp_dealloc */
0, /* tp_print */
0, /* tp_getattr */
0, /* tp_setattr */
0, /* tp_reserved */
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,
/* tp_flags */
0, /* tp_doc */
(traverseproc)treebuilder_gc_traverse, /* tp_traverse */
(inquiry)treebuilder_gc_clear, /* tp_clear */
0, /* tp_richcompare */
0, /* tp_weaklistoffset */
0, /* tp_iter */
0, /* tp_iternext */
treebuilder_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 */
_elementtree_TreeBuilder___init__, /* tp_init */
PyType_GenericAlloc, /* tp_alloc */
treebuilder_new, /* tp_new */
0, /* tp_free */
};
static PyMethodDef xmlparser_methods[] = {
_ELEMENTTREE_XMLPARSER_FEED_METHODDEF
_ELEMENTTREE_XMLPARSER_CLOSE_METHODDEF
_ELEMENTTREE_XMLPARSER__PARSE_WHOLE_METHODDEF
_ELEMENTTREE_XMLPARSER__SETEVENTS_METHODDEF
_ELEMENTTREE_XMLPARSER_DOCTYPE_METHODDEF
{NULL, NULL}
};
static PyTypeObject XMLParser_Type = {
PyVarObject_HEAD_INIT(NULL, 0)
"xml.etree.ElementTree.XMLParser", sizeof(XMLParserObject), 0,
/* methods */
(destructor)xmlparser_dealloc, /* tp_dealloc */
0, /* tp_print */
0, /* tp_getattr */
0, /* tp_setattr */
0, /* tp_reserved */
0, /* tp_repr */
0, /* tp_as_number */
0, /* tp_as_sequence */
0, /* tp_as_mapping */
0, /* tp_hash */
0, /* tp_call */
0, /* tp_str */
(getattrofunc)xmlparser_getattro, /* tp_getattro */
0, /* tp_setattro */
0, /* tp_as_buffer */
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
/* tp_flags */
0, /* tp_doc */
(traverseproc)xmlparser_gc_traverse, /* tp_traverse */
(inquiry)xmlparser_gc_clear, /* tp_clear */
0, /* tp_richcompare */
0, /* tp_weaklistoffset */
0, /* tp_iter */
0, /* tp_iternext */
xmlparser_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 */
_elementtree_XMLParser___init__, /* tp_init */
PyType_GenericAlloc, /* tp_alloc */
xmlparser_new, /* tp_new */
0, /* tp_free */
};
/* ==================================================================== */
/* python module interface */
static PyMethodDef _functions[] = {
{"SubElement", (PyCFunction) subelement, METH_VARARGS | METH_KEYWORDS},
{NULL, NULL}
};
static struct PyModuleDef elementtreemodule = {
PyModuleDef_HEAD_INIT,
"_elementtree",
NULL,
sizeof(elementtreestate),
_functions,
NULL,
elementtree_traverse,
elementtree_clear,
elementtree_free
};
PyMODINIT_FUNC
PyInit__elementtree(void)
{
PyObject *m, *temp;
elementtreestate *st;
m = PyState_FindModule(&elementtreemodule);
if (m) {
Py_INCREF(m);
return m;
}
/* Initialize object types */
if (PyType_Ready(&ElementIter_Type) < 0)
return NULL;
if (PyType_Ready(&TreeBuilder_Type) < 0)
return NULL;
if (PyType_Ready(&Element_Type) < 0)
return NULL;
if (PyType_Ready(&XMLParser_Type) < 0)
return NULL;
m = PyModule_Create(&elementtreemodule);
if (!m)
return NULL;
st = ET_STATE(m);
if (!(temp = PyImport_ImportModule("copy")))
return NULL;
st->deepcopy_obj = PyObject_GetAttrString(temp, "deepcopy");
Py_XDECREF(temp);
if (st->deepcopy_obj == NULL) {
return NULL;
}
assert(!PyErr_Occurred());
if (!(st->elementpath_obj = PyImport_ImportModule("xml.etree.ElementPath")))
return NULL;
/* link against pyexpat */
expat_capi = PyCapsule_Import(PyExpat_CAPSULE_NAME, 0);
if (expat_capi) {
/* check that it's usable */
if (strcmp(expat_capi->magic, PyExpat_CAPI_MAGIC) != 0 ||
(size_t)expat_capi->size < sizeof(struct PyExpat_CAPI) ||
expat_capi->MAJOR_VERSION != XML_MAJOR_VERSION ||
expat_capi->MINOR_VERSION != XML_MINOR_VERSION ||
expat_capi->MICRO_VERSION != XML_MICRO_VERSION) {
PyErr_SetString(PyExc_ImportError,
"pyexpat version is incompatible");
return NULL;
}
} else {
return NULL;
}
st->parseerror_obj = PyErr_NewException(
"xml.etree.ElementTree.ParseError", PyExc_SyntaxError, NULL
);
Py_INCREF(st->parseerror_obj);
PyModule_AddObject(m, "ParseError", st->parseerror_obj);
Py_INCREF((PyObject *)&Element_Type);
PyModule_AddObject(m, "Element", (PyObject *)&Element_Type);
Py_INCREF((PyObject *)&TreeBuilder_Type);
PyModule_AddObject(m, "TreeBuilder", (PyObject *)&TreeBuilder_Type);
Py_INCREF((PyObject *)&XMLParser_Type);
PyModule_AddObject(m, "XMLParser", (PyObject *)&XMLParser_Type);
return m;
}
_Section(".rodata.pytab.1") const struct _inittab _PyImport_Inittab__elementtree = {
"_elementtree",
PyInit__elementtree,
};
| 117,829 | 4,099 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Modules/_codecsmodule.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:8;coding:utf-8 -*-â
âvi: set net ft=c ts=4 sts=4 sw=4 fenc=utf-8 :viâ
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ¡
â Python 3 â
â https://docs.python.org/3/license.html â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
#define PY_SSIZE_T_CLEAN
#include "third_party/python/Include/abstract.h"
#include "third_party/python/Include/bytesobject.h"
#include "third_party/python/Include/codecs.h"
#include "third_party/python/Include/import.h"
#include "third_party/python/Include/modsupport.h"
#include "third_party/python/Include/object.h"
#include "third_party/python/Include/pyerrors.h"
#include "third_party/python/Include/pymacro.h"
#include "third_party/python/Include/unicodeobject.h"
#include "third_party/python/Include/warnings.h"
#include "third_party/python/Include/yoink.h"
/* clang-format off */
PYTHON_PROVIDE("_codecs");
PYTHON_PROVIDE("_codecs._forget_codec");
PYTHON_PROVIDE("_codecs.ascii_decode");
PYTHON_PROVIDE("_codecs.ascii_encode");
PYTHON_PROVIDE("_codecs.charmap_build");
PYTHON_PROVIDE("_codecs.charmap_decode");
PYTHON_PROVIDE("_codecs.charmap_encode");
PYTHON_PROVIDE("_codecs.decode");
PYTHON_PROVIDE("_codecs.encode");
PYTHON_PROVIDE("_codecs.escape_decode");
PYTHON_PROVIDE("_codecs.escape_encode");
PYTHON_PROVIDE("_codecs.latin_1_decode");
PYTHON_PROVIDE("_codecs.latin_1_encode");
PYTHON_PROVIDE("_codecs.lookup");
PYTHON_PROVIDE("_codecs.lookup_error");
PYTHON_PROVIDE("_codecs.raw_unicode_escape_decode");
PYTHON_PROVIDE("_codecs.raw_unicode_escape_encode");
PYTHON_PROVIDE("_codecs.readbuffer_encode");
PYTHON_PROVIDE("_codecs.register");
PYTHON_PROVIDE("_codecs.register_error");
PYTHON_PROVIDE("_codecs.unicode_escape_decode");
PYTHON_PROVIDE("_codecs.unicode_escape_encode");
PYTHON_PROVIDE("_codecs.unicode_internal_decode");
PYTHON_PROVIDE("_codecs.unicode_internal_encode");
PYTHON_PROVIDE("_codecs.utf_16_be_decode");
PYTHON_PROVIDE("_codecs.utf_16_be_encode");
PYTHON_PROVIDE("_codecs.utf_16_decode");
PYTHON_PROVIDE("_codecs.utf_16_encode");
PYTHON_PROVIDE("_codecs.utf_16_ex_decode");
PYTHON_PROVIDE("_codecs.utf_16_le_decode");
PYTHON_PROVIDE("_codecs.utf_16_le_encode");
PYTHON_PROVIDE("_codecs.utf_32_be_decode");
PYTHON_PROVIDE("_codecs.utf_32_be_encode");
PYTHON_PROVIDE("_codecs.utf_32_decode");
PYTHON_PROVIDE("_codecs.utf_32_encode");
PYTHON_PROVIDE("_codecs.utf_32_ex_decode");
PYTHON_PROVIDE("_codecs.utf_32_le_decode");
PYTHON_PROVIDE("_codecs.utf_32_le_encode");
PYTHON_PROVIDE("_codecs.utf_7_decode");
PYTHON_PROVIDE("_codecs.utf_7_encode");
PYTHON_PROVIDE("_codecs.utf_8_decode");
PYTHON_PROVIDE("_codecs.utf_8_encode");
/* ------------------------------------------------------------------------
_codecs -- Provides access to the codec registry and the builtin
codecs.
This module should never be imported directly. The standard library
module "codecs" wraps this builtin module for use within Python.
The codec registry is accessible via:
register(search_function) -> None
lookup(encoding) -> CodecInfo object
The builtin Unicode codecs use the following interface:
<encoding>_encode(Unicode_object[,errors='strict']) ->
(string object, bytes consumed)
<encoding>_decode(char_buffer_obj[,errors='strict']) ->
(Unicode object, bytes consumed)
These <encoding>s are available: utf_8, unicode_escape,
raw_unicode_escape, unicode_internal, latin_1, ascii (7-bit),
mbcs (on win32).
Written by Marc-Andre Lemburg ([email protected]).
Copyright (c) Corporation for National Research Initiatives.
------------------------------------------------------------------------ */
/*[clinic input]
module _codecs
[clinic start generated code]*/
/*[clinic end generated code: output=da39a3ee5e6b4b0d input=e1390e3da3cb9deb]*/
#include "third_party/python/Modules/clinic/_codecsmodule.inc"
/* --- Registry ----------------------------------------------------------- */
/*[clinic input]
_codecs.register
search_function: object
/
Register a codec search function.
Search functions are expected to take one argument, the encoding name in
all lower case letters, and either return None, or a tuple of functions
(encoder, decoder, stream_reader, stream_writer) (or a CodecInfo object).
[clinic start generated code]*/
static PyObject *
_codecs_register(PyObject *module, PyObject *search_function)
/*[clinic end generated code: output=d1bf21e99db7d6d3 input=369578467955cae4]*/
{
if (PyCodec_Register(search_function))
return NULL;
Py_RETURN_NONE;
}
/*[clinic input]
_codecs.lookup
encoding: str
/
Looks up a codec tuple in the Python codec registry and returns a CodecInfo object.
[clinic start generated code]*/
static PyObject *
_codecs_lookup_impl(PyObject *module, const char *encoding)
/*[clinic end generated code: output=9f0afa572080c36d input=3c572c0db3febe9c]*/
{
return _PyCodec_Lookup(encoding);
}
/*[clinic input]
_codecs.encode
obj: object
encoding: str(c_default="NULL") = "utf-8"
errors: str(c_default="NULL") = "strict"
Encodes obj using the codec registered for encoding.
The default encoding is 'utf-8'. errors may be given to set a
different error handling scheme. Default is 'strict' meaning that encoding
errors raise a ValueError. Other possible values are 'ignore', 'replace'
and 'backslashreplace' as well as any other name registered with
codecs.register_error that can handle ValueErrors.
[clinic start generated code]*/
static PyObject *
_codecs_encode_impl(PyObject *module, PyObject *obj, const char *encoding,
const char *errors)
/*[clinic end generated code: output=385148eb9a067c86 input=cd5b685040ff61f0]*/
{
if (encoding == NULL)
encoding = PyUnicode_GetDefaultEncoding();
/* Encode via the codec registry */
return PyCodec_Encode(obj, encoding, errors);
}
/*[clinic input]
_codecs.decode
obj: object
encoding: str(c_default="NULL") = "utf-8"
errors: str(c_default="NULL") = "strict"
Decodes obj using the codec registered for encoding.
Default encoding is 'utf-8'. errors may be given to set a
different error handling scheme. Default is 'strict' meaning that encoding
errors raise a ValueError. Other possible values are 'ignore', 'replace'
and 'backslashreplace' as well as any other name registered with
codecs.register_error that can handle ValueErrors.
[clinic start generated code]*/
static PyObject *
_codecs_decode_impl(PyObject *module, PyObject *obj, const char *encoding,
const char *errors)
/*[clinic end generated code: output=679882417dc3a0bd input=7702c0cc2fa1add6]*/
{
if (encoding == NULL)
encoding = PyUnicode_GetDefaultEncoding();
/* Decode via the codec registry */
return PyCodec_Decode(obj, encoding, errors);
}
/* --- Helpers ------------------------------------------------------------ */
/*[clinic input]
_codecs._forget_codec
encoding: str
/
Purge the named codec from the internal codec lookup cache
[clinic start generated code]*/
static PyObject *
_codecs__forget_codec_impl(PyObject *module, const char *encoding)
/*[clinic end generated code: output=0bde9f0a5b084aa2 input=18d5d92d0e386c38]*/
{
if (_PyCodec_Forget(encoding) < 0) {
return NULL;
};
Py_RETURN_NONE;
}
static
PyObject *codec_tuple(PyObject *decoded,
Py_ssize_t len)
{
if (decoded == NULL)
return NULL;
return Py_BuildValue("Nn", decoded, len);
}
/* --- String codecs ------------------------------------------------------ */
/*[clinic input]
_codecs.escape_decode
data: Py_buffer(accept={str, buffer})
errors: str(accept={str, NoneType}) = NULL
/
[clinic start generated code]*/
static PyObject *
_codecs_escape_decode_impl(PyObject *module, Py_buffer *data,
const char *errors)
/*[clinic end generated code: output=505200ba8056979a input=0018edfd99db714d]*/
{
PyObject *decoded = PyBytes_DecodeEscape(data->buf, data->len,
errors, 0, NULL);
return codec_tuple(decoded, data->len);
}
/*[clinic input]
_codecs.escape_encode
data: object(subclass_of='&PyBytes_Type')
errors: str(accept={str, NoneType}) = NULL
/
[clinic start generated code]*/
static PyObject *
_codecs_escape_encode_impl(PyObject *module, PyObject *data,
const char *errors)
/*[clinic end generated code: output=4af1d477834bab34 input=da9ded00992f32f2]*/
{
Py_ssize_t size;
Py_ssize_t newsize;
PyObject *v;
size = PyBytes_GET_SIZE(data);
if (size > PY_SSIZE_T_MAX / 4) {
PyErr_SetString(PyExc_OverflowError,
"string is too large to encode");
return NULL;
}
newsize = 4*size;
v = PyBytes_FromStringAndSize(NULL, newsize);
if (v == NULL) {
return NULL;
}
else {
Py_ssize_t i;
char c;
char *p = PyBytes_AS_STRING(v);
for (i = 0; i < size; i++) {
/* There's at least enough room for a hex escape */
assert(newsize - (p - PyBytes_AS_STRING(v)) >= 4);
c = PyBytes_AS_STRING(data)[i];
if (c == '\'' || 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) {
*p++ = '\\';
*p++ = 'x';
*p++ = Py_hexdigits[(c & 0xf0) >> 4];
*p++ = Py_hexdigits[c & 0xf];
}
else
*p++ = c;
}
*p = '\0';
if (_PyBytes_Resize(&v, (p - PyBytes_AS_STRING(v)))) {
return NULL;
}
}
return codec_tuple(v, size);
}
/* --- Decoder ------------------------------------------------------------ */
/*[clinic input]
_codecs.unicode_internal_decode
obj: object
errors: str(accept={str, NoneType}) = NULL
/
[clinic start generated code]*/
static PyObject *
_codecs_unicode_internal_decode_impl(PyObject *module, PyObject *obj,
const char *errors)
/*[clinic end generated code: output=edbfe175e09eff9a input=8d57930aeda170c6]*/
{
if (PyUnicode_Check(obj)) {
if (PyUnicode_READY(obj) < 0)
return NULL;
Py_INCREF(obj);
return codec_tuple(obj, PyUnicode_GET_LENGTH(obj));
}
else {
Py_buffer view;
PyObject *result;
if (PyObject_GetBuffer(obj, &view, PyBUF_SIMPLE) != 0)
return NULL;
result = codec_tuple(
_PyUnicode_DecodeUnicodeInternal(view.buf, view.len, errors),
view.len);
PyBuffer_Release(&view);
return result;
}
}
/*[clinic input]
_codecs.utf_7_decode
data: Py_buffer
errors: str(accept={str, NoneType}) = NULL
final: int(c_default="0") = False
/
[clinic start generated code]*/
static PyObject *
_codecs_utf_7_decode_impl(PyObject *module, Py_buffer *data,
const char *errors, int final)
/*[clinic end generated code: output=0cd3a944a32a4089 input=bc4d6247ecdb01e6]*/
{
Py_ssize_t consumed = data->len;
PyObject *decoded = PyUnicode_DecodeUTF7Stateful(data->buf, data->len,
errors,
final ? NULL : &consumed);
return codec_tuple(decoded, consumed);
}
/*[clinic input]
_codecs.utf_8_decode
data: Py_buffer
errors: str(accept={str, NoneType}) = NULL
final: int(c_default="0") = False
/
[clinic start generated code]*/
static PyObject *
_codecs_utf_8_decode_impl(PyObject *module, Py_buffer *data,
const char *errors, int final)
/*[clinic end generated code: output=10f74dec8d9bb8bf input=39161d71e7422ee2]*/
{
Py_ssize_t consumed = data->len;
PyObject *decoded = PyUnicode_DecodeUTF8Stateful(data->buf, data->len,
errors,
final ? NULL : &consumed);
return codec_tuple(decoded, consumed);
}
/*[clinic input]
_codecs.utf_16_decode
data: Py_buffer
errors: str(accept={str, NoneType}) = NULL
final: int(c_default="0") = False
/
[clinic start generated code]*/
static PyObject *
_codecs_utf_16_decode_impl(PyObject *module, Py_buffer *data,
const char *errors, int final)
/*[clinic end generated code: output=783b442abcbcc2d0 input=f3cf01d1461007ce]*/
{
int byteorder = 0;
/* This is overwritten unless final is true. */
Py_ssize_t consumed = data->len;
PyObject *decoded = PyUnicode_DecodeUTF16Stateful(data->buf, data->len,
errors, &byteorder,
final ? NULL : &consumed);
return codec_tuple(decoded, consumed);
}
/*[clinic input]
_codecs.utf_16_le_decode
data: Py_buffer
errors: str(accept={str, NoneType}) = NULL
final: int(c_default="0") = False
/
[clinic start generated code]*/
static PyObject *
_codecs_utf_16_le_decode_impl(PyObject *module, Py_buffer *data,
const char *errors, int final)
/*[clinic end generated code: output=899b9e6364379dcd input=a77e3bf97335d94e]*/
{
int byteorder = -1;
/* This is overwritten unless final is true. */
Py_ssize_t consumed = data->len;
PyObject *decoded = PyUnicode_DecodeUTF16Stateful(data->buf, data->len,
errors, &byteorder,
final ? NULL : &consumed);
return codec_tuple(decoded, consumed);
}
/*[clinic input]
_codecs.utf_16_be_decode
data: Py_buffer
errors: str(accept={str, NoneType}) = NULL
final: int(c_default="0") = False
/
[clinic start generated code]*/
static PyObject *
_codecs_utf_16_be_decode_impl(PyObject *module, Py_buffer *data,
const char *errors, int final)
/*[clinic end generated code: output=49f6465ea07669c8 input=606f69fae91b5563]*/
{
int byteorder = 1;
/* This is overwritten unless final is true. */
Py_ssize_t consumed = data->len;
PyObject *decoded = PyUnicode_DecodeUTF16Stateful(data->buf, data->len,
errors, &byteorder,
final ? NULL : &consumed);
return codec_tuple(decoded, consumed);
}
/* This non-standard version also provides access to the byteorder
parameter of the builtin UTF-16 codec.
It returns a tuple (unicode, bytesread, byteorder) with byteorder
being the value in effect at the end of data.
*/
/*[clinic input]
_codecs.utf_16_ex_decode
data: Py_buffer
errors: str(accept={str, NoneType}) = NULL
byteorder: int = 0
final: int(c_default="0") = False
/
[clinic start generated code]*/
static PyObject *
_codecs_utf_16_ex_decode_impl(PyObject *module, Py_buffer *data,
const char *errors, int byteorder, int final)
/*[clinic end generated code: output=0f385f251ecc1988 input=f6e7f697658c013e]*/
{
/* This is overwritten unless final is true. */
Py_ssize_t consumed = data->len;
PyObject *decoded = PyUnicode_DecodeUTF16Stateful(data->buf, data->len,
errors, &byteorder,
final ? NULL : &consumed);
if (decoded == NULL)
return NULL;
return Py_BuildValue("Nni", decoded, consumed, byteorder);
}
/*[clinic input]
_codecs.utf_32_decode
data: Py_buffer
errors: str(accept={str, NoneType}) = NULL
final: int(c_default="0") = False
/
[clinic start generated code]*/
static PyObject *
_codecs_utf_32_decode_impl(PyObject *module, Py_buffer *data,
const char *errors, int final)
/*[clinic end generated code: output=2fc961807f7b145f input=86d4f41c6c2e763d]*/
{
int byteorder = 0;
/* This is overwritten unless final is true. */
Py_ssize_t consumed = data->len;
PyObject *decoded = PyUnicode_DecodeUTF32Stateful(data->buf, data->len,
errors, &byteorder,
final ? NULL : &consumed);
return codec_tuple(decoded, consumed);
}
/*[clinic input]
_codecs.utf_32_le_decode
data: Py_buffer
errors: str(accept={str, NoneType}) = NULL
final: int(c_default="0") = False
/
[clinic start generated code]*/
static PyObject *
_codecs_utf_32_le_decode_impl(PyObject *module, Py_buffer *data,
const char *errors, int final)
/*[clinic end generated code: output=ec8f46b67a94f3e6 input=d18b650772d188ba]*/
{
int byteorder = -1;
/* This is overwritten unless final is true. */
Py_ssize_t consumed = data->len;
PyObject *decoded = PyUnicode_DecodeUTF32Stateful(data->buf, data->len,
errors, &byteorder,
final ? NULL : &consumed);
return codec_tuple(decoded, consumed);
}
/*[clinic input]
_codecs.utf_32_be_decode
data: Py_buffer
errors: str(accept={str, NoneType}) = NULL
final: int(c_default="0") = False
/
[clinic start generated code]*/
static PyObject *
_codecs_utf_32_be_decode_impl(PyObject *module, Py_buffer *data,
const char *errors, int final)
/*[clinic end generated code: output=ff82bae862c92c4e input=19c271b5d34926d8]*/
{
int byteorder = 1;
/* This is overwritten unless final is true. */
Py_ssize_t consumed = data->len;
PyObject *decoded = PyUnicode_DecodeUTF32Stateful(data->buf, data->len,
errors, &byteorder,
final ? NULL : &consumed);
return codec_tuple(decoded, consumed);
}
/* This non-standard version also provides access to the byteorder
parameter of the builtin UTF-32 codec.
It returns a tuple (unicode, bytesread, byteorder) with byteorder
being the value in effect at the end of data.
*/
/*[clinic input]
_codecs.utf_32_ex_decode
data: Py_buffer
errors: str(accept={str, NoneType}) = NULL
byteorder: int = 0
final: int(c_default="0") = False
/
[clinic start generated code]*/
static PyObject *
_codecs_utf_32_ex_decode_impl(PyObject *module, Py_buffer *data,
const char *errors, int byteorder, int final)
/*[clinic end generated code: output=6bfb177dceaf4848 input=4af3e6ccfe34a076]*/
{
Py_ssize_t consumed = data->len;
PyObject *decoded = PyUnicode_DecodeUTF32Stateful(data->buf, data->len,
errors, &byteorder,
final ? NULL : &consumed);
if (decoded == NULL)
return NULL;
return Py_BuildValue("Nni", decoded, consumed, byteorder);
}
/*[clinic input]
_codecs.unicode_escape_decode
data: Py_buffer(accept={str, buffer})
errors: str(accept={str, NoneType}) = NULL
/
[clinic start generated code]*/
static PyObject *
_codecs_unicode_escape_decode_impl(PyObject *module, Py_buffer *data,
const char *errors)
/*[clinic end generated code: output=3ca3c917176b82ab input=49fd27d06813a7f5]*/
{
PyObject *decoded = PyUnicode_DecodeUnicodeEscape(data->buf, data->len,
errors);
return codec_tuple(decoded, data->len);
}
/*[clinic input]
_codecs.raw_unicode_escape_decode
data: Py_buffer(accept={str, buffer})
errors: str(accept={str, NoneType}) = NULL
/
[clinic start generated code]*/
static PyObject *
_codecs_raw_unicode_escape_decode_impl(PyObject *module, Py_buffer *data,
const char *errors)
/*[clinic end generated code: output=c98eeb56028070a6 input=770903a211434ebc]*/
{
PyObject *decoded = PyUnicode_DecodeRawUnicodeEscape(data->buf, data->len,
errors);
return codec_tuple(decoded, data->len);
}
/*[clinic input]
_codecs.latin_1_decode
data: Py_buffer
errors: str(accept={str, NoneType}) = NULL
/
[clinic start generated code]*/
static PyObject *
_codecs_latin_1_decode_impl(PyObject *module, Py_buffer *data,
const char *errors)
/*[clinic end generated code: output=07f3dfa3f72c7d8f input=5cad0f1759c618ec]*/
{
PyObject *decoded = PyUnicode_DecodeLatin1(data->buf, data->len, errors);
return codec_tuple(decoded, data->len);
}
/*[clinic input]
_codecs.ascii_decode
data: Py_buffer
errors: str(accept={str, NoneType}) = NULL
/
[clinic start generated code]*/
static PyObject *
_codecs_ascii_decode_impl(PyObject *module, Py_buffer *data,
const char *errors)
/*[clinic end generated code: output=2627d72058d42429 input=ad1106f64037bd16]*/
{
PyObject *decoded = PyUnicode_DecodeASCII(data->buf, data->len, errors);
return codec_tuple(decoded, data->len);
}
/*[clinic input]
_codecs.charmap_decode
data: Py_buffer
errors: str(accept={str, NoneType}) = NULL
mapping: object = NULL
/
[clinic start generated code]*/
static PyObject *
_codecs_charmap_decode_impl(PyObject *module, Py_buffer *data,
const char *errors, PyObject *mapping)
/*[clinic end generated code: output=2c335b09778cf895 input=19712ca35c5a80e2]*/
{
PyObject *decoded;
if (mapping == Py_None)
mapping = NULL;
decoded = PyUnicode_DecodeCharmap(data->buf, data->len, mapping, errors);
return codec_tuple(decoded, data->len);
}
#ifdef MS_WINDOWS
/*[clinic input]
_codecs.mbcs_decode
data: Py_buffer
errors: str(accept={str, NoneType}) = NULL
final: int(c_default="0") = False
/
[clinic start generated code]*/
static PyObject *
_codecs_mbcs_decode_impl(PyObject *module, Py_buffer *data,
const char *errors, int final)
/*[clinic end generated code: output=39b65b8598938c4b input=d492c1ca64f4fa8a]*/
{
Py_ssize_t consumed = data->len;
PyObject *decoded = PyUnicode_DecodeMBCSStateful(data->buf, data->len,
errors, final ? NULL : &consumed);
return codec_tuple(decoded, consumed);
}
/*[clinic input]
_codecs.oem_decode
data: Py_buffer
errors: str(accept={str, NoneType}) = NULL
final: int(c_default="0") = False
/
[clinic start generated code]*/
static PyObject *
_codecs_oem_decode_impl(PyObject *module, Py_buffer *data,
const char *errors, int final)
/*[clinic end generated code: output=da1617612f3fcad8 input=95b8a92c446b03cd]*/
{
Py_ssize_t consumed = data->len;
PyObject *decoded = PyUnicode_DecodeCodePageStateful(CP_OEMCP,
data->buf, data->len, errors, final ? NULL : &consumed);
return codec_tuple(decoded, consumed);
}
/*[clinic input]
_codecs.code_page_decode
codepage: int
data: Py_buffer
errors: str(accept={str, NoneType}) = NULL
final: int(c_default="0") = False
/
[clinic start generated code]*/
static PyObject *
_codecs_code_page_decode_impl(PyObject *module, int codepage,
Py_buffer *data, const char *errors, int final)
/*[clinic end generated code: output=53008ea967da3fff input=4f3152a304e21d51]*/
{
Py_ssize_t consumed = data->len;
PyObject *decoded = PyUnicode_DecodeCodePageStateful(codepage,
data->buf, data->len,
errors,
final ? NULL : &consumed);
return codec_tuple(decoded, consumed);
}
#endif /* MS_WINDOWS */
/* --- Encoder ------------------------------------------------------------ */
/*[clinic input]
_codecs.readbuffer_encode
data: Py_buffer(accept={str, buffer})
errors: str(accept={str, NoneType}) = NULL
/
[clinic start generated code]*/
static PyObject *
_codecs_readbuffer_encode_impl(PyObject *module, Py_buffer *data,
const char *errors)
/*[clinic end generated code: output=c645ea7cdb3d6e86 input=b7c322b89d4ab923]*/
{
PyObject *result = PyBytes_FromStringAndSize(data->buf, data->len);
return codec_tuple(result, data->len);
}
/*[clinic input]
_codecs.unicode_internal_encode
obj: object
errors: str(accept={str, NoneType}) = NULL
/
[clinic start generated code]*/
static PyObject *
_codecs_unicode_internal_encode_impl(PyObject *module, PyObject *obj,
const char *errors)
/*[clinic end generated code: output=a72507dde4ea558f input=8628f0280cf5ba61]*/
{
if (PyErr_WarnEx(PyExc_DeprecationWarning,
"unicode_internal codec has been deprecated",
1))
return NULL;
if (PyUnicode_Check(obj)) {
Py_UNICODE *u;
Py_ssize_t len, size;
if (PyUnicode_READY(obj) < 0)
return NULL;
u = PyUnicode_AsUnicodeAndSize(obj, &len);
if (u == NULL)
return NULL;
if ((size_t)len > (size_t)PY_SSIZE_T_MAX / sizeof(Py_UNICODE))
return PyErr_NoMemory();
size = len * sizeof(Py_UNICODE);
return codec_tuple(PyBytes_FromStringAndSize((const char*)u, size),
PyUnicode_GET_LENGTH(obj));
}
else {
Py_buffer view;
PyObject *result;
if (PyObject_GetBuffer(obj, &view, PyBUF_SIMPLE) != 0)
return NULL;
result = codec_tuple(PyBytes_FromStringAndSize(view.buf, view.len),
view.len);
PyBuffer_Release(&view);
return result;
}
}
/*[clinic input]
_codecs.utf_7_encode
str: unicode
errors: str(accept={str, NoneType}) = NULL
/
[clinic start generated code]*/
static PyObject *
_codecs_utf_7_encode_impl(PyObject *module, PyObject *str,
const char *errors)
/*[clinic end generated code: output=0feda21ffc921bc8 input=d1a47579e79cbe15]*/
{
return codec_tuple(_PyUnicode_EncodeUTF7(str, 0, 0, errors),
PyUnicode_GET_LENGTH(str));
}
/*[clinic input]
_codecs.utf_8_encode
str: unicode
errors: str(accept={str, NoneType}) = NULL
/
[clinic start generated code]*/
static PyObject *
_codecs_utf_8_encode_impl(PyObject *module, PyObject *str,
const char *errors)
/*[clinic end generated code: output=02bf47332b9c796c input=42e3ba73c4392eef]*/
{
return codec_tuple(_PyUnicode_AsUTF8String(str, errors),
PyUnicode_GET_LENGTH(str));
}
/* This version provides access to the byteorder parameter of the
builtin UTF-16 codecs as optional third argument. It defaults to 0
which means: use the native byte order and prepend the data with a
BOM mark.
*/
/*[clinic input]
_codecs.utf_16_encode
str: unicode
errors: str(accept={str, NoneType}) = NULL
byteorder: int = 0
/
[clinic start generated code]*/
static PyObject *
_codecs_utf_16_encode_impl(PyObject *module, PyObject *str,
const char *errors, int byteorder)
/*[clinic end generated code: output=c654e13efa2e64e4 input=ff46416b04edb944]*/
{
return codec_tuple(_PyUnicode_EncodeUTF16(str, errors, byteorder),
PyUnicode_GET_LENGTH(str));
}
/*[clinic input]
_codecs.utf_16_le_encode
str: unicode
errors: str(accept={str, NoneType}) = NULL
/
[clinic start generated code]*/
static PyObject *
_codecs_utf_16_le_encode_impl(PyObject *module, PyObject *str,
const char *errors)
/*[clinic end generated code: output=431b01e55f2d4995 input=cb385455ea8f2fe0]*/
{
return codec_tuple(_PyUnicode_EncodeUTF16(str, errors, -1),
PyUnicode_GET_LENGTH(str));
}
/*[clinic input]
_codecs.utf_16_be_encode
str: unicode
errors: str(accept={str, NoneType}) = NULL
/
[clinic start generated code]*/
static PyObject *
_codecs_utf_16_be_encode_impl(PyObject *module, PyObject *str,
const char *errors)
/*[clinic end generated code: output=96886a6fd54dcae3 input=9119997066bdaefd]*/
{
return codec_tuple(_PyUnicode_EncodeUTF16(str, errors, +1),
PyUnicode_GET_LENGTH(str));
}
/* This version provides access to the byteorder parameter of the
builtin UTF-32 codecs as optional third argument. It defaults to 0
which means: use the native byte order and prepend the data with a
BOM mark.
*/
/*[clinic input]
_codecs.utf_32_encode
str: unicode
errors: str(accept={str, NoneType}) = NULL
byteorder: int = 0
/
[clinic start generated code]*/
static PyObject *
_codecs_utf_32_encode_impl(PyObject *module, PyObject *str,
const char *errors, int byteorder)
/*[clinic end generated code: output=5c760da0c09a8b83 input=c5e77da82fbe5c2a]*/
{
return codec_tuple(_PyUnicode_EncodeUTF32(str, errors, byteorder),
PyUnicode_GET_LENGTH(str));
}
/*[clinic input]
_codecs.utf_32_le_encode
str: unicode
errors: str(accept={str, NoneType}) = NULL
/
[clinic start generated code]*/
static PyObject *
_codecs_utf_32_le_encode_impl(PyObject *module, PyObject *str,
const char *errors)
/*[clinic end generated code: output=b65cd176de8e36d6 input=9993b25fe0877848]*/
{
return codec_tuple(_PyUnicode_EncodeUTF32(str, errors, -1),
PyUnicode_GET_LENGTH(str));
}
/*[clinic input]
_codecs.utf_32_be_encode
str: unicode
errors: str(accept={str, NoneType}) = NULL
/
[clinic start generated code]*/
static PyObject *
_codecs_utf_32_be_encode_impl(PyObject *module, PyObject *str,
const char *errors)
/*[clinic end generated code: output=1d9e71a9358709e9 input=d3e0ccaa02920431]*/
{
return codec_tuple(_PyUnicode_EncodeUTF32(str, errors, +1),
PyUnicode_GET_LENGTH(str));
}
/*[clinic input]
_codecs.unicode_escape_encode
str: unicode
errors: str(accept={str, NoneType}) = NULL
/
[clinic start generated code]*/
static PyObject *
_codecs_unicode_escape_encode_impl(PyObject *module, PyObject *str,
const char *errors)
/*[clinic end generated code: output=66271b30bc4f7a3c input=65d9eefca65b455a]*/
{
return codec_tuple(PyUnicode_AsUnicodeEscapeString(str),
PyUnicode_GET_LENGTH(str));
}
/*[clinic input]
_codecs.raw_unicode_escape_encode
str: unicode
errors: str(accept={str, NoneType}) = NULL
/
[clinic start generated code]*/
static PyObject *
_codecs_raw_unicode_escape_encode_impl(PyObject *module, PyObject *str,
const char *errors)
/*[clinic end generated code: output=a66a806ed01c830a input=5aa33e4a133391ab]*/
{
return codec_tuple(PyUnicode_AsRawUnicodeEscapeString(str),
PyUnicode_GET_LENGTH(str));
}
/*[clinic input]
_codecs.latin_1_encode
str: unicode
errors: str(accept={str, NoneType}) = NULL
/
[clinic start generated code]*/
static PyObject *
_codecs_latin_1_encode_impl(PyObject *module, PyObject *str,
const char *errors)
/*[clinic end generated code: output=2c28c83a27884e08 input=30b11c9e49a65150]*/
{
return codec_tuple(_PyUnicode_AsLatin1String(str, errors),
PyUnicode_GET_LENGTH(str));
}
/*[clinic input]
_codecs.ascii_encode
str: unicode
errors: str(accept={str, NoneType}) = NULL
/
[clinic start generated code]*/
static PyObject *
_codecs_ascii_encode_impl(PyObject *module, PyObject *str,
const char *errors)
/*[clinic end generated code: output=b5e035182d33befc input=843a1d268e6dfa8e]*/
{
return codec_tuple(_PyUnicode_AsASCIIString(str, errors),
PyUnicode_GET_LENGTH(str));
}
/*[clinic input]
_codecs.charmap_encode
str: unicode
errors: str(accept={str, NoneType}) = NULL
mapping: object = NULL
/
[clinic start generated code]*/
static PyObject *
_codecs_charmap_encode_impl(PyObject *module, PyObject *str,
const char *errors, PyObject *mapping)
/*[clinic end generated code: output=047476f48495a9e9 input=0752cde07a6d6d00]*/
{
if (mapping == Py_None)
mapping = NULL;
return codec_tuple(_PyUnicode_EncodeCharmap(str, mapping, errors),
PyUnicode_GET_LENGTH(str));
}
/*[clinic input]
_codecs.charmap_build
map: unicode
/
[clinic start generated code]*/
static PyObject *
_codecs_charmap_build_impl(PyObject *module, PyObject *map)
/*[clinic end generated code: output=bb073c27031db9ac input=d91a91d1717dbc6d]*/
{
return PyUnicode_BuildEncodingMap(map);
}
#ifdef MS_WINDOWS
/*[clinic input]
_codecs.mbcs_encode
str: unicode
errors: str(accept={str, NoneType}) = NULL
/
[clinic start generated code]*/
static PyObject *
_codecs_mbcs_encode_impl(PyObject *module, PyObject *str, const char *errors)
/*[clinic end generated code: output=76e2e170c966c080 input=de471e0815947553]*/
{
return codec_tuple(PyUnicode_EncodeCodePage(CP_ACP, str, errors),
PyUnicode_GET_LENGTH(str));
}
/*[clinic input]
_codecs.oem_encode
str: unicode
errors: str(accept={str, NoneType}) = NULL
/
[clinic start generated code]*/
static PyObject *
_codecs_oem_encode_impl(PyObject *module, PyObject *str, const char *errors)
/*[clinic end generated code: output=65d5982c737de649 input=3fc5f0028aad3cda]*/
{
return codec_tuple(PyUnicode_EncodeCodePage(CP_OEMCP, str, errors),
PyUnicode_GET_LENGTH(str));
}
/*[clinic input]
_codecs.code_page_encode
code_page: int
str: unicode
errors: str(accept={str, NoneType}) = NULL
/
[clinic start generated code]*/
static PyObject *
_codecs_code_page_encode_impl(PyObject *module, int code_page, PyObject *str,
const char *errors)
/*[clinic end generated code: output=45673f6085657a9e input=786421ae617d680b]*/
{
return codec_tuple(PyUnicode_EncodeCodePage(code_page, str, errors),
PyUnicode_GET_LENGTH(str));
}
#endif /* MS_WINDOWS */
/* --- Error handler registry --------------------------------------------- */
/*[clinic input]
_codecs.register_error
errors: str
handler: object
/
Register the specified error handler under the name errors.
handler must be a callable object, that will be called with an exception
instance containing information about the location of the encoding/decoding
error and must return a (replacement, new position) tuple.
[clinic start generated code]*/
static PyObject *
_codecs_register_error_impl(PyObject *module, const char *errors,
PyObject *handler)
/*[clinic end generated code: output=fa2f7d1879b3067d input=5e6709203c2e33fe]*/
{
if (PyCodec_RegisterError(errors, handler))
return NULL;
Py_RETURN_NONE;
}
/*[clinic input]
_codecs.lookup_error
name: str
/
lookup_error(errors) -> handler
Return the error handler for the specified error handling name or raise a
LookupError, if no handler exists under this name.
[clinic start generated code]*/
static PyObject *
_codecs_lookup_error_impl(PyObject *module, const char *name)
/*[clinic end generated code: output=087f05dc0c9a98cc input=4775dd65e6235aba]*/
{
return PyCodec_LookupError(name);
}
/* --- Module API --------------------------------------------------------- */
static PyMethodDef _codecs_functions[] = {
_CODECS_REGISTER_METHODDEF
_CODECS_LOOKUP_METHODDEF
_CODECS_ENCODE_METHODDEF
_CODECS_DECODE_METHODDEF
_CODECS_ESCAPE_ENCODE_METHODDEF
_CODECS_ESCAPE_DECODE_METHODDEF
_CODECS_UTF_8_ENCODE_METHODDEF
_CODECS_UTF_8_DECODE_METHODDEF
_CODECS_UTF_7_ENCODE_METHODDEF
_CODECS_UTF_7_DECODE_METHODDEF
_CODECS_UTF_16_ENCODE_METHODDEF
_CODECS_UTF_16_LE_ENCODE_METHODDEF
_CODECS_UTF_16_BE_ENCODE_METHODDEF
_CODECS_UTF_16_DECODE_METHODDEF
_CODECS_UTF_16_LE_DECODE_METHODDEF
_CODECS_UTF_16_BE_DECODE_METHODDEF
_CODECS_UTF_16_EX_DECODE_METHODDEF
_CODECS_UTF_32_ENCODE_METHODDEF
_CODECS_UTF_32_LE_ENCODE_METHODDEF
_CODECS_UTF_32_BE_ENCODE_METHODDEF
_CODECS_UTF_32_DECODE_METHODDEF
_CODECS_UTF_32_LE_DECODE_METHODDEF
_CODECS_UTF_32_BE_DECODE_METHODDEF
_CODECS_UTF_32_EX_DECODE_METHODDEF
_CODECS_UNICODE_ESCAPE_ENCODE_METHODDEF
_CODECS_UNICODE_ESCAPE_DECODE_METHODDEF
_CODECS_UNICODE_INTERNAL_ENCODE_METHODDEF
_CODECS_UNICODE_INTERNAL_DECODE_METHODDEF
_CODECS_RAW_UNICODE_ESCAPE_ENCODE_METHODDEF
_CODECS_RAW_UNICODE_ESCAPE_DECODE_METHODDEF
_CODECS_LATIN_1_ENCODE_METHODDEF
_CODECS_LATIN_1_DECODE_METHODDEF
_CODECS_ASCII_ENCODE_METHODDEF
_CODECS_ASCII_DECODE_METHODDEF
_CODECS_CHARMAP_ENCODE_METHODDEF
_CODECS_CHARMAP_DECODE_METHODDEF
_CODECS_CHARMAP_BUILD_METHODDEF
_CODECS_READBUFFER_ENCODE_METHODDEF
_CODECS_MBCS_ENCODE_METHODDEF
_CODECS_MBCS_DECODE_METHODDEF
_CODECS_OEM_ENCODE_METHODDEF
_CODECS_OEM_DECODE_METHODDEF
_CODECS_CODE_PAGE_ENCODE_METHODDEF
_CODECS_CODE_PAGE_DECODE_METHODDEF
_CODECS_REGISTER_ERROR_METHODDEF
_CODECS_LOOKUP_ERROR_METHODDEF
_CODECS__FORGET_CODEC_METHODDEF
{NULL, NULL} /* sentinel */
};
static struct PyModuleDef codecsmodule = {
PyModuleDef_HEAD_INIT,
"_codecs",
NULL,
-1,
_codecs_functions,
NULL,
NULL,
NULL,
NULL
};
PyMODINIT_FUNC
PyInit__codecs(void)
{
return PyModule_Create(&codecsmodule);
}
| 38,610 | 1,195 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Modules/pyexpat.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:8;coding:utf-8 -*-â
âvi: set net ft=c ts=4 sts=4 sw=4 fenc=utf-8 :viâ
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ¡
â Python 3 â
â https://docs.python.org/3/license.html â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
#include "libc/fmt/fmt.h"
#include "third_party/python/Include/abstract.h"
#include "third_party/python/Include/boolobject.h"
#include "third_party/python/Include/bytearrayobject.h"
#include "third_party/python/Include/ceval.h"
#include "third_party/python/Include/dictobject.h"
#include "third_party/python/Include/frameobject.h"
#include "third_party/python/Include/import.h"
#include "third_party/python/Include/longobject.h"
#include "third_party/python/Include/modsupport.h"
#include "third_party/python/Include/objimpl.h"
#include "third_party/python/Include/pycapsule.h"
#include "third_party/python/Include/pyexpat.h"
#include "third_party/python/Include/pyhash.h"
#include "third_party/python/Include/pymacro.h"
#include "third_party/python/Include/sysmodule.h"
#include "third_party/python/Include/traceback.h"
#include "third_party/python/Include/yoink.h"
#include "third_party/python/Modules/expat/expat.h"
/* clang-format off */
PYTHON_PROVIDE("pyexpat");
PYTHON_PROVIDE("pyexpat.EXPAT_VERSION");
PYTHON_PROVIDE("pyexpat.ErrorString");
PYTHON_PROVIDE("pyexpat.ExpatError");
PYTHON_PROVIDE("pyexpat.ParserCreate");
PYTHON_PROVIDE("pyexpat.XMLParserType");
PYTHON_PROVIDE("pyexpat.XML_PARAM_ENTITY_PARSING_ALWAYS");
PYTHON_PROVIDE("pyexpat.XML_PARAM_ENTITY_PARSING_NEVER");
PYTHON_PROVIDE("pyexpat.XML_PARAM_ENTITY_PARSING_UNLESS_STANDALONE");
PYTHON_PROVIDE("pyexpat.__doc__");
PYTHON_PROVIDE("pyexpat.__loader__");
PYTHON_PROVIDE("pyexpat.__name__");
PYTHON_PROVIDE("pyexpat.__package__");
PYTHON_PROVIDE("pyexpat.__spec__");
PYTHON_PROVIDE("pyexpat.error");
PYTHON_PROVIDE("pyexpat.errors");
PYTHON_PROVIDE("pyexpat.expat_CAPI");
PYTHON_PROVIDE("pyexpat.features");
PYTHON_PROVIDE("pyexpat.model");
PYTHON_PROVIDE("pyexpat.native_encoding");
PYTHON_PROVIDE("pyexpat.version_info");
PYTHON_YOINK("encodings.ascii");
PYTHON_YOINK("encodings.utf_8");
/* Do not emit Clinic output to a file as that wreaks havoc with conditionally
included methods. */
/*[clinic input]
module pyexpat
[clinic start generated code]*/
/*[clinic end generated code: output=da39a3ee5e6b4b0d input=b168d503a4490c15]*/
#define XML_COMBINED_VERSION (10000*XML_MAJOR_VERSION+100*XML_MINOR_VERSION+XML_MICRO_VERSION)
static XML_Memory_Handling_Suite ExpatMemoryHandler = {
PyObject_Malloc, PyObject_Realloc, PyObject_Free};
enum HandlerTypes {
StartElement,
EndElement,
ProcessingInstruction,
CharacterData,
UnparsedEntityDecl,
NotationDecl,
StartNamespaceDecl,
EndNamespaceDecl,
Comment,
StartCdataSection,
EndCdataSection,
Default,
DefaultHandlerExpand,
NotStandalone,
ExternalEntityRef,
StartDoctypeDecl,
EndDoctypeDecl,
EntityDecl,
XmlDecl,
ElementDecl,
AttlistDecl,
#if XML_COMBINED_VERSION >= 19504
SkippedEntity,
#endif
_DummyDecl
};
static PyObject *ErrorObject;
/* ----------------------------------------------------- */
/* Declarations for objects of type xmlparser */
typedef struct {
PyObject_HEAD
XML_Parser itself;
int ordered_attributes; /* Return attributes as a list. */
int specified_attributes; /* Report only specified attributes. */
int in_callback; /* Is a callback active? */
int ns_prefixes; /* Namespace-triplets mode? */
XML_Char *buffer; /* Buffer used when accumulating characters */
/* NULL if not enabled */
int buffer_size; /* Size of buffer, in XML_Char units */
int buffer_used; /* Buffer units in use */
PyObject *intern; /* Dictionary to intern strings */
PyObject **handlers;
} xmlparseobject;
#include "third_party/python/Modules/clinic/pyexpat.inc"
#define CHARACTER_DATA_BUFFER_SIZE 8192
static PyTypeObject Xmlparsetype;
typedef void (*xmlhandlersetter)(XML_Parser self, void *meth);
typedef void* xmlhandler;
struct HandlerInfo {
const char *name;
xmlhandlersetter setter;
xmlhandler handler;
PyCodeObject *tb_code;
PyObject *nameobj;
};
static struct HandlerInfo handler_info[64];
/* Set an integer attribute on the error object; return true on success,
* false on an exception.
*/
static int
set_error_attr(PyObject *err, const char *name, int value)
{
PyObject *v = PyLong_FromLong(value);
if (v == NULL || PyObject_SetAttrString(err, name, v) == -1) {
Py_XDECREF(v);
return 0;
}
Py_DECREF(v);
return 1;
}
/* Build and set an Expat exception, including positioning
* information. Always returns NULL.
*/
static PyObject *
set_error(xmlparseobject *self, enum XML_Error code)
{
PyObject *err;
PyObject *buffer;
XML_Parser parser = self->itself;
int lineno = XML_GetErrorLineNumber(parser);
int column = XML_GetErrorColumnNumber(parser);
buffer = PyUnicode_FromFormat("%s: line %i, column %i",
XML_ErrorString(code), lineno, column);
if (buffer == NULL)
return NULL;
err = PyObject_CallFunction(ErrorObject, "O", buffer);
Py_DECREF(buffer);
if ( err != NULL
&& set_error_attr(err, "code", code)
&& set_error_attr(err, "offset", column)
&& set_error_attr(err, "lineno", lineno)) {
PyErr_SetObject(ErrorObject, err);
}
Py_XDECREF(err);
return NULL;
}
static int
have_handler(xmlparseobject *self, int type)
{
PyObject *handler = self->handlers[type];
return handler != NULL;
}
static PyObject *
get_handler_name(struct HandlerInfo *hinfo)
{
PyObject *name = hinfo->nameobj;
if (name == NULL) {
name = PyUnicode_FromString(hinfo->name);
hinfo->nameobj = name;
}
Py_XINCREF(name);
return name;
}
/* Convert a string of XML_Chars into a Unicode string.
Returns None if str is a null pointer. */
static PyObject *
conv_string_to_unicode(const XML_Char *str)
{
/* XXX currently this code assumes that XML_Char is 8-bit,
and hence in UTF-8. */
/* UTF-8 from Expat, Unicode desired */
if (str == NULL) {
Py_INCREF(Py_None);
return Py_None;
}
return PyUnicode_DecodeUTF8(str, strlen(str), "strict");
}
static PyObject *
conv_string_len_to_unicode(const XML_Char *str, int len)
{
/* XXX currently this code assumes that XML_Char is 8-bit,
and hence in UTF-8. */
/* UTF-8 from Expat, Unicode desired */
if (str == NULL) {
Py_INCREF(Py_None);
return Py_None;
}
return PyUnicode_DecodeUTF8((const char *)str, len, "strict");
}
/* Callback routines */
static void clear_handlers(xmlparseobject *self, int initial);
/* This handler is used when an error has been detected, in the hope
that actual parsing can be terminated early. This will only help
if an external entity reference is encountered. */
static int
error_external_entity_ref_handler(XML_Parser parser,
const XML_Char *context,
const XML_Char *base,
const XML_Char *systemId,
const XML_Char *publicId)
{
return 0;
}
/* Dummy character data handler used when an error (exception) has
been detected, and the actual parsing can be terminated early.
This is needed since character data handler can't be safely removed
from within the character data handler, but can be replaced. It is
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)
{
/* Do nothing. */
}
static void
flag_error(xmlparseobject *self)
{
clear_handlers(self, 0);
XML_SetExternalEntityRefHandler(self->itself,
error_external_entity_ref_handler);
}
static PyObject*
call_with_frame(const char *funcname, int lineno, PyObject* func, PyObject* args,
xmlparseobject *self)
{
PyObject *res;
res = PyEval_CallObject(func, args);
if (res == NULL) {
_PyTraceback_Add(funcname, __FILE__, lineno);
XML_StopParser(self->itself, XML_FALSE);
}
return res;
}
static PyObject*
string_intern(xmlparseobject *self, const char* str)
{
PyObject *result = conv_string_to_unicode(str);
PyObject *value;
/* result can be NULL if the unicode conversion failed. */
if (!result)
return result;
if (!self->intern)
return result;
value = PyDict_GetItem(self->intern, result);
if (!value) {
if (PyDict_SetItem(self->intern, result, result) == 0)
return result;
else {
Py_DECREF(result);
return NULL;
}
}
Py_INCREF(value);
Py_DECREF(result);
return value;
}
/* Return 0 on success, -1 on exception.
* flag_error() will be called before return if needed.
*/
static int
call_character_handler(xmlparseobject *self, const XML_Char *buffer, int len)
{
PyObject *args;
PyObject *temp;
if (!have_handler(self, CharacterData))
return -1;
args = PyTuple_New(1);
if (args == NULL)
return -1;
temp = (conv_string_len_to_unicode(buffer, len));
if (temp == NULL) {
Py_DECREF(args);
flag_error(self);
XML_SetCharacterDataHandler(self->itself,
noop_character_data_handler);
return -1;
}
PyTuple_SET_ITEM(args, 0, temp);
/* temp is now a borrowed reference; consider it unused. */
self->in_callback = 1;
temp = call_with_frame("CharacterData", __LINE__,
self->handlers[CharacterData], args, self);
/* temp is an owned reference again, or NULL */
self->in_callback = 0;
Py_DECREF(args);
if (temp == NULL) {
flag_error(self);
XML_SetCharacterDataHandler(self->itself,
noop_character_data_handler);
return -1;
}
Py_DECREF(temp);
return 0;
}
static int
flush_character_buffer(xmlparseobject *self)
{
int rc;
if (self->buffer == NULL || self->buffer_used == 0)
return 0;
rc = call_character_handler(self, self->buffer, self->buffer_used);
self->buffer_used = 0;
return rc;
}
static void
my_CharacterDataHandler(void *userData, const XML_Char *data, int len)
{
xmlparseobject *self = (xmlparseobject *) userData;
if (PyErr_Occurred())
return;
if (self->buffer == NULL)
call_character_handler(self, data, len);
else {
if ((self->buffer_used + len) > self->buffer_size) {
if (flush_character_buffer(self) < 0)
return;
/* handler might have changed; drop the rest on the floor
* if there isn't a handler anymore
*/
if (!have_handler(self, CharacterData))
return;
}
if (len > self->buffer_size) {
call_character_handler(self, data, len);
self->buffer_used = 0;
}
else {
memcpy(self->buffer + self->buffer_used,
data, len * sizeof(XML_Char));
self->buffer_used += len;
}
}
}
static void
my_StartElementHandler(void *userData,
const XML_Char *name, const XML_Char *atts[])
{
xmlparseobject *self = (xmlparseobject *)userData;
if (have_handler(self, StartElement)) {
PyObject *container, *rv, *args;
int i, max;
if (PyErr_Occurred())
return;
if (flush_character_buffer(self) < 0)
return;
/* Set max to the number of slots filled in atts[]; max/2 is
* the number of attributes we need to process.
*/
if (self->specified_attributes) {
max = XML_GetSpecifiedAttributeCount(self->itself);
}
else {
max = 0;
while (atts[max] != NULL)
max += 2;
}
/* Build the container. */
if (self->ordered_attributes)
container = PyList_New(max);
else
container = PyDict_New();
if (container == NULL) {
flag_error(self);
return;
}
for (i = 0; i < max; i += 2) {
PyObject *n = string_intern(self, (XML_Char *) atts[i]);
PyObject *v;
if (n == NULL) {
flag_error(self);
Py_DECREF(container);
return;
}
v = conv_string_to_unicode((XML_Char *) atts[i+1]);
if (v == NULL) {
flag_error(self);
Py_DECREF(container);
Py_DECREF(n);
return;
}
if (self->ordered_attributes) {
PyList_SET_ITEM(container, i, n);
PyList_SET_ITEM(container, i+1, v);
}
else if (PyDict_SetItem(container, n, v)) {
flag_error(self);
Py_DECREF(n);
Py_DECREF(v);
Py_DECREF(container);
return;
}
else {
Py_DECREF(n);
Py_DECREF(v);
}
}
args = string_intern(self, name);
if (args == NULL) {
Py_DECREF(container);
return;
}
args = Py_BuildValue("(NN)", args, container);
if (args == NULL) {
return;
}
/* Container is now a borrowed reference; ignore it. */
self->in_callback = 1;
rv = call_with_frame("StartElement", __LINE__,
self->handlers[StartElement], args, self);
self->in_callback = 0;
Py_DECREF(args);
if (rv == NULL) {
flag_error(self);
return;
}
Py_DECREF(rv);
}
}
#define RC_HANDLER(RC, NAME, PARAMS, INIT, PARAM_FORMAT, CONVERSION, \
RETURN, GETUSERDATA) \
static RC \
my_##NAME##Handler PARAMS {\
xmlparseobject *self = GETUSERDATA ; \
PyObject *args = NULL; \
PyObject *rv = NULL; \
INIT \
\
if (have_handler(self, NAME)) { \
if (PyErr_Occurred()) \
return RETURN; \
if (flush_character_buffer(self) < 0) \
return RETURN; \
args = Py_BuildValue PARAM_FORMAT ;\
if (!args) { flag_error(self); return RETURN;} \
self->in_callback = 1; \
rv = call_with_frame(#NAME,__LINE__, \
self->handlers[NAME], args, self); \
self->in_callback = 0; \
Py_DECREF(args); \
if (rv == NULL) { \
flag_error(self); \
return RETURN; \
} \
CONVERSION \
Py_DECREF(rv); \
} \
return RETURN; \
}
#define VOID_HANDLER(NAME, PARAMS, PARAM_FORMAT) \
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 = PyLong_AsLong(rv);, rc, \
(xmlparseobject *)userData)
VOID_HANDLER(EndElement,
(void *userData, const XML_Char *name),
("(N)", string_intern(self, name)))
VOID_HANDLER(ProcessingInstruction,
(void *userData,
const XML_Char *target,
const XML_Char *data),
("(NO&)", string_intern(self, target), conv_string_to_unicode ,data))
VOID_HANDLER(UnparsedEntityDecl,
(void *userData,
const XML_Char *entityName,
const XML_Char *base,
const XML_Char *systemId,
const XML_Char *publicId,
const XML_Char *notationName),
("(NNNNN)",
string_intern(self, entityName), string_intern(self, base),
string_intern(self, systemId), string_intern(self, publicId),
string_intern(self, notationName)))
VOID_HANDLER(EntityDecl,
(void *userData,
const XML_Char *entityName,
int is_parameter_entity,
const XML_Char *value,
int value_length,
const XML_Char *base,
const XML_Char *systemId,
const XML_Char *publicId,
const XML_Char *notationName),
("NiNNNNN",
string_intern(self, entityName), is_parameter_entity,
(conv_string_len_to_unicode(value, value_length)),
string_intern(self, base), string_intern(self, systemId),
string_intern(self, publicId),
string_intern(self, notationName)))
VOID_HANDLER(XmlDecl,
(void *userData,
const XML_Char *version,
const XML_Char *encoding,
int standalone),
("(O&O&i)",
conv_string_to_unicode ,version, conv_string_to_unicode ,encoding,
standalone))
static PyObject *
conv_content_model(XML_Content * const model,
PyObject *(*conv_string)(const XML_Char *))
{
PyObject *result = NULL;
PyObject *children = PyTuple_New(model->numchildren);
int i;
if (children != NULL) {
assert(model->numchildren < INT_MAX);
for (i = 0; i < (int)model->numchildren; ++i) {
PyObject *child = conv_content_model(&model->children[i],
conv_string);
if (child == NULL) {
Py_XDECREF(children);
return NULL;
}
PyTuple_SET_ITEM(children, i, child);
}
result = Py_BuildValue("(iiO&N)",
model->type, model->quant,
conv_string,model->name, children);
}
return result;
}
static void
my_ElementDeclHandler(void *userData,
const XML_Char *name,
XML_Content *model)
{
xmlparseobject *self = (xmlparseobject *)userData;
PyObject *args = NULL;
if (have_handler(self, ElementDecl)) {
PyObject *rv = NULL;
PyObject *modelobj, *nameobj;
if (PyErr_Occurred())
return;
if (flush_character_buffer(self) < 0)
goto finally;
modelobj = conv_content_model(model, (conv_string_to_unicode));
if (modelobj == NULL) {
flag_error(self);
goto finally;
}
nameobj = string_intern(self, name);
if (nameobj == NULL) {
Py_DECREF(modelobj);
flag_error(self);
goto finally;
}
args = Py_BuildValue("NN", nameobj, modelobj);
if (args == NULL) {
flag_error(self);
goto finally;
}
self->in_callback = 1;
rv = call_with_frame("ElementDecl", __LINE__,
self->handlers[ElementDecl], args, self);
self->in_callback = 0;
if (rv == NULL) {
flag_error(self);
goto finally;
}
Py_DECREF(rv);
}
finally:
Py_XDECREF(args);
XML_FreeContentModel(self->itself, model);
return;
}
VOID_HANDLER(AttlistDecl,
(void *userData,
const XML_Char *elname,
const XML_Char *attname,
const XML_Char *att_type,
const XML_Char *dflt,
int isrequired),
("(NNO&O&i)",
string_intern(self, elname), string_intern(self, attname),
conv_string_to_unicode ,att_type, conv_string_to_unicode ,dflt,
isrequired))
#if XML_COMBINED_VERSION >= 19504
VOID_HANDLER(SkippedEntity,
(void *userData,
const XML_Char *entityName,
int is_parameter_entity),
("Ni",
string_intern(self, entityName), is_parameter_entity))
#endif
VOID_HANDLER(NotationDecl,
(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)))
VOID_HANDLER(StartNamespaceDecl,
(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),
("(N)", string_intern(self, prefix)))
VOID_HANDLER(Comment,
(void *userData, const XML_Char *data),
("(O&)", conv_string_to_unicode ,data))
VOID_HANDLER(StartCdataSection,
(void *userData),
("()"))
VOID_HANDLER(EndCdataSection,
(void *userData),
("()"))
VOID_HANDLER(Default,
(void *userData, const XML_Char *s, int len),
("(N)", (conv_string_len_to_unicode(s,len))))
VOID_HANDLER(DefaultHandlerExpand,
(void *userData, const XML_Char *s, int len),
("(N)", (conv_string_len_to_unicode(s,len))))
INT_HANDLER(NotStandalone,
(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;,
("(O&NNN)",
conv_string_to_unicode ,context, string_intern(self, base),
string_intern(self, systemId), string_intern(self, publicId)),
rc = PyLong_AsLong(rv);, rc,
XML_GetUserData(parser))
/* XXX UnknownEncodingHandler */
VOID_HANDLER(StartDoctypeDecl,
(void *userData, const XML_Char *doctypeName,
const XML_Char *sysid, const XML_Char *pubid,
int has_internal_subset),
("(NNNi)", string_intern(self, doctypeName),
string_intern(self, sysid), string_intern(self, pubid),
has_internal_subset))
VOID_HANDLER(EndDoctypeDecl, (void *userData), ("()"))
/* ---------------------------------------------------------------- */
/*[clinic input]
class pyexpat.xmlparser "xmlparseobject *" "&Xmlparsetype"
[clinic start generated code]*/
/*[clinic end generated code: output=da39a3ee5e6b4b0d input=2393162385232e1c]*/
static PyObject *
get_parse_result(xmlparseobject *self, int rv)
{
if (PyErr_Occurred()) {
return NULL;
}
if (rv == 0) {
return set_error(self, XML_GetErrorCode(self->itself));
}
if (flush_character_buffer(self) < 0) {
return NULL;
}
return PyLong_FromLong(rv);
}
#define MAX_CHUNK_SIZE (1 << 20)
/*[clinic input]
pyexpat.xmlparser.Parse
data: object
isfinal: int(c_default="0") = False
/
Parse XML data.
`isfinal' should be true at end of input.
[clinic start generated code]*/
static PyObject *
pyexpat_xmlparser_Parse_impl(xmlparseobject *self, PyObject *data,
int isfinal)
/*[clinic end generated code: output=f4db843dd1f4ed4b input=199d9e8e92ebbb4b]*/
{
const char *s;
Py_ssize_t slen;
Py_buffer view;
int rc;
if (PyUnicode_Check(data)) {
view.buf = NULL;
s = PyUnicode_AsUTF8AndSize(data, &slen);
if (s == NULL)
return NULL;
/* Explicitly set UTF-8 encoding. Return code ignored. */
(void)XML_SetEncoding(self->itself, "utf-8");
}
else {
if (PyObject_GetBuffer(data, &view, PyBUF_SIMPLE) < 0)
return NULL;
s = view.buf;
slen = view.len;
}
while (slen > MAX_CHUNK_SIZE) {
rc = XML_Parse(self->itself, s, MAX_CHUNK_SIZE, 0);
if (!rc)
goto done;
s += MAX_CHUNK_SIZE;
slen -= MAX_CHUNK_SIZE;
}
Py_BUILD_ASSERT(MAX_CHUNK_SIZE <= INT_MAX);
assert(slen <= INT_MAX);
rc = XML_Parse(self->itself, s, (int)slen, isfinal);
done:
if (view.buf != NULL)
PyBuffer_Release(&view);
return get_parse_result(self, rc);
}
/* File reading copied from cPickle */
#define BUF_SIZE 2048
static int
readinst(char *buf, int buf_size, PyObject *meth)
{
PyObject *str;
Py_ssize_t len;
const char *ptr;
str = PyObject_CallFunction(meth, "n", buf_size);
if (str == NULL)
goto error;
if (PyBytes_Check(str))
ptr = PyBytes_AS_STRING(str);
else if (PyByteArray_Check(str))
ptr = PyByteArray_AS_STRING(str);
else {
PyErr_Format(PyExc_TypeError,
"read() did not return a bytes object (type=%.400s)",
Py_TYPE(str)->tp_name);
goto error;
}
len = Py_SIZE(str);
if (len > buf_size) {
PyErr_Format(PyExc_ValueError,
"read() returned too much data: "
"%i bytes requested, %zd returned",
buf_size, len);
goto error;
}
memcpy(buf, ptr, len);
Py_DECREF(str);
/* len <= buf_size <= INT_MAX */
return (int)len;
error:
Py_XDECREF(str);
return -1;
}
/*[clinic input]
pyexpat.xmlparser.ParseFile
file: object
/
Parse XML data from file-like object.
[clinic start generated code]*/
static PyObject *
pyexpat_xmlparser_ParseFile(xmlparseobject *self, PyObject *file)
/*[clinic end generated code: output=2adc6a13100cc42b input=fbb5a12b6038d735]*/
{
int rv = 1;
PyObject *readmethod = NULL;
_Py_IDENTIFIER(read);
readmethod = _PyObject_GetAttrId(file, &PyId_read);
if (readmethod == NULL) {
PyErr_SetString(PyExc_TypeError,
"argument must have 'read' attribute");
return NULL;
}
for (;;) {
int bytes_read;
void *buf = XML_GetBuffer(self->itself, BUF_SIZE);
if (buf == NULL) {
Py_XDECREF(readmethod);
return get_parse_result(self, 0);
}
bytes_read = readinst(buf, BUF_SIZE, readmethod);
if (bytes_read < 0) {
Py_DECREF(readmethod);
return NULL;
}
rv = XML_ParseBuffer(self->itself, bytes_read, bytes_read == 0);
if (PyErr_Occurred()) {
Py_XDECREF(readmethod);
return NULL;
}
if (!rv || bytes_read == 0)
break;
}
Py_XDECREF(readmethod);
return get_parse_result(self, rv);
}
/*[clinic input]
pyexpat.xmlparser.SetBase
base: str
/
Set the base URL for the parser.
[clinic start generated code]*/
static PyObject *
pyexpat_xmlparser_SetBase_impl(xmlparseobject *self, const char *base)
/*[clinic end generated code: output=c212ddceb607b539 input=c684e5de895ee1a8]*/
{
if (!XML_SetBase(self->itself, base)) {
return PyErr_NoMemory();
}
Py_RETURN_NONE;
}
/*[clinic input]
pyexpat.xmlparser.GetBase
Return base URL string for the parser.
[clinic start generated code]*/
static PyObject *
pyexpat_xmlparser_GetBase_impl(xmlparseobject *self)
/*[clinic end generated code: output=2886cb21f9a8739a input=918d71c38009620e]*/
{
return Py_BuildValue("z", XML_GetBase(self->itself));
}
/*[clinic input]
pyexpat.xmlparser.GetInputContext
Return the untranslated text of the input that caused the current event.
If the event was generated by a large amount of text (such as a start tag
for an element with many attributes), not all of the text may be available.
[clinic start generated code]*/
static PyObject *
pyexpat_xmlparser_GetInputContext_impl(xmlparseobject *self)
/*[clinic end generated code: output=a88026d683fc22cc input=034df8712db68379]*/
{
if (self->in_callback) {
int offset, size;
const char *buffer
= XML_GetInputContext(self->itself, &offset, &size);
if (buffer != NULL)
return PyBytes_FromStringAndSize(buffer + offset,
size - offset);
else
Py_RETURN_NONE;
}
else
Py_RETURN_NONE;
}
/*[clinic input]
pyexpat.xmlparser.ExternalEntityParserCreate
context: str(accept={str, NoneType})
encoding: str = NULL
/
Create a parser for parsing an external entity based on the information passed to the ExternalEntityRefHandler.
[clinic start generated code]*/
static PyObject *
pyexpat_xmlparser_ExternalEntityParserCreate_impl(xmlparseobject *self,
const char *context,
const char *encoding)
/*[clinic end generated code: output=535cda9d7a0fbcd6 input=b906714cc122c322]*/
{
xmlparseobject *new_parser;
int i;
new_parser = PyObject_GC_New(xmlparseobject, &Xmlparsetype);
if (new_parser == NULL)
return NULL;
new_parser->buffer_size = self->buffer_size;
new_parser->buffer_used = 0;
new_parser->buffer = NULL;
new_parser->ordered_attributes = self->ordered_attributes;
new_parser->specified_attributes = self->specified_attributes;
new_parser->in_callback = 0;
new_parser->ns_prefixes = self->ns_prefixes;
new_parser->itself = XML_ExternalEntityParserCreate(self->itself, context,
encoding);
new_parser->handlers = 0;
new_parser->intern = self->intern;
Py_XINCREF(new_parser->intern);
PyObject_GC_Track(new_parser);
if (self->buffer != NULL) {
new_parser->buffer = PyMem_Malloc(new_parser->buffer_size);
if (new_parser->buffer == NULL) {
Py_DECREF(new_parser);
return PyErr_NoMemory();
}
}
if (!new_parser->itself) {
Py_DECREF(new_parser);
return PyErr_NoMemory();
}
XML_SetUserData(new_parser->itself, (void *)new_parser);
/* allocate and clear handlers first */
for (i = 0; handler_info[i].name != NULL; i++)
/* do nothing */;
new_parser->handlers = PyMem_New(PyObject *, i);
if (!new_parser->handlers) {
Py_DECREF(new_parser);
return PyErr_NoMemory();
}
clear_handlers(new_parser, 1);
/* then copy handlers from self */
for (i = 0; handler_info[i].name != NULL; i++) {
PyObject *handler = self->handlers[i];
if (handler != NULL) {
Py_INCREF(handler);
new_parser->handlers[i] = handler;
handler_info[i].setter(new_parser->itself,
handler_info[i].handler);
}
}
return (PyObject *)new_parser;
}
/*[clinic input]
pyexpat.xmlparser.SetParamEntityParsing
flag: int
/
Controls parsing of parameter entities (including the external DTD subset).
Possible flag values are XML_PARAM_ENTITY_PARSING_NEVER,
XML_PARAM_ENTITY_PARSING_UNLESS_STANDALONE and
XML_PARAM_ENTITY_PARSING_ALWAYS. Returns true if setting the flag
was successful.
[clinic start generated code]*/
static PyObject *
pyexpat_xmlparser_SetParamEntityParsing_impl(xmlparseobject *self, int flag)
/*[clinic end generated code: output=18668ee8e760d64c input=8aea19b4b15e9af1]*/
{
flag = XML_SetParamEntityParsing(self->itself, flag);
return PyLong_FromLong(flag);
}
#if XML_COMBINED_VERSION >= 19505
/*[clinic input]
pyexpat.xmlparser.UseForeignDTD
flag: bool = True
/
Allows the application to provide an artificial external subset if one is not specified as part of the document instance.
This readily allows the use of a 'default' document type controlled by the
application, while still getting the advantage of providing document type
information to the parser. 'flag' defaults to True if not provided.
[clinic start generated code]*/
static PyObject *
pyexpat_xmlparser_UseForeignDTD_impl(xmlparseobject *self, int flag)
/*[clinic end generated code: output=cfaa9aa50bb0f65c input=78144c519d116a6e]*/
{
enum XML_Error rc;
rc = XML_UseForeignDTD(self->itself, flag ? XML_TRUE : XML_FALSE);
if (rc != XML_ERROR_NONE) {
return set_error(self, rc);
}
Py_INCREF(Py_None);
return Py_None;
}
#endif
/*[clinic input]
pyexpat.xmlparser.__dir__
[clinic start generated code]*/
static PyObject *
pyexpat_xmlparser___dir___impl(xmlparseobject *self)
/*[clinic end generated code: output=bc22451efb9e4d17 input=76aa455f2a661384]*/
{
#define APPEND(list, str) \
do { \
PyObject *o = PyUnicode_FromString(str); \
if (o != NULL) \
PyList_Append(list, o); \
Py_XDECREF(o); \
} while (0)
int i;
PyObject *rc = PyList_New(0);
if (!rc)
return NULL;
for (i = 0; handler_info[i].name != NULL; i++) {
PyObject *o = get_handler_name(&handler_info[i]);
if (o != NULL)
PyList_Append(rc, o);
Py_XDECREF(o);
}
APPEND(rc, "ErrorCode");
APPEND(rc, "ErrorLineNumber");
APPEND(rc, "ErrorColumnNumber");
APPEND(rc, "ErrorByteIndex");
APPEND(rc, "CurrentLineNumber");
APPEND(rc, "CurrentColumnNumber");
APPEND(rc, "CurrentByteIndex");
APPEND(rc, "buffer_size");
APPEND(rc, "buffer_text");
APPEND(rc, "buffer_used");
APPEND(rc, "namespace_prefixes");
APPEND(rc, "ordered_attributes");
APPEND(rc, "specified_attributes");
APPEND(rc, "intern");
#undef APPEND
if (PyErr_Occurred()) {
Py_DECREF(rc);
rc = NULL;
}
return rc;
}
static struct PyMethodDef xmlparse_methods[] = {
PYEXPAT_XMLPARSER_PARSE_METHODDEF
PYEXPAT_XMLPARSER_PARSEFILE_METHODDEF
PYEXPAT_XMLPARSER_SETBASE_METHODDEF
PYEXPAT_XMLPARSER_GETBASE_METHODDEF
PYEXPAT_XMLPARSER_GETINPUTCONTEXT_METHODDEF
PYEXPAT_XMLPARSER_EXTERNALENTITYPARSERCREATE_METHODDEF
PYEXPAT_XMLPARSER_SETPARAMENTITYPARSING_METHODDEF
#if XML_COMBINED_VERSION >= 19505
PYEXPAT_XMLPARSER_USEFOREIGNDTD_METHODDEF
#endif
PYEXPAT_XMLPARSER___DIR___METHODDEF
{NULL, NULL} /* sentinel */
};
/* ---------- */
/* pyexpat international encoding support.
Make it as simple as possible.
*/
static int
PyUnknownEncodingHandler(void *encodingHandlerData,
const XML_Char *name,
XML_Encoding *info)
{
static unsigned char template_buffer[256] = {0};
PyObject* u;
int i;
void *data;
unsigned int kind;
if (PyErr_Occurred())
return XML_STATUS_ERROR;
if (template_buffer[1] == 0) {
for (i = 0; i < 256; i++)
template_buffer[i] = i;
}
u = PyUnicode_Decode((char*) template_buffer, 256, name, "replace");
if (u == NULL || PyUnicode_READY(u)) {
Py_XDECREF(u);
return XML_STATUS_ERROR;
}
if (PyUnicode_GET_LENGTH(u) != 256) {
Py_DECREF(u);
PyErr_SetString(PyExc_ValueError,
"multi-byte encodings are not supported");
return XML_STATUS_ERROR;
}
kind = PyUnicode_KIND(u);
data = PyUnicode_DATA(u);
for (i = 0; i < 256; i++) {
Py_UCS4 ch = PyUnicode_READ(kind, data, i);
if (ch != Py_UNICODE_REPLACEMENT_CHARACTER)
info->map[i] = ch;
else
info->map[i] = -1;
}
info->data = NULL;
info->convert = NULL;
info->release = NULL;
Py_DECREF(u);
return XML_STATUS_OK;
}
static PyObject *
newxmlparseobject(const char *encoding, const char *namespace_separator, PyObject *intern)
{
int i;
xmlparseobject *self;
self = PyObject_GC_New(xmlparseobject, &Xmlparsetype);
if (self == NULL)
return NULL;
self->buffer = NULL;
self->buffer_size = CHARACTER_DATA_BUFFER_SIZE;
self->buffer_used = 0;
self->ordered_attributes = 0;
self->specified_attributes = 0;
self->in_callback = 0;
self->ns_prefixes = 0;
self->handlers = NULL;
self->intern = intern;
Py_XINCREF(self->intern);
PyObject_GC_Track(self);
/* namespace_separator is either NULL or contains one char + \0 */
self->itself = XML_ParserCreate_MM(encoding, &ExpatMemoryHandler,
namespace_separator);
if (self->itself == NULL) {
PyErr_SetString(PyExc_RuntimeError,
"XML_ParserCreate failed");
Py_DECREF(self);
return NULL;
}
#if XML_COMBINED_VERSION >= 20100
/* This feature was added upstream in libexpat 2.1.0. */
XML_SetHashSalt(self->itself,
(unsigned long)_Py_HashSecret.expat.hashsalt);
#endif
XML_SetUserData(self->itself, (void *)self);
XML_SetUnknownEncodingHandler(self->itself,
(XML_UnknownEncodingHandler) PyUnknownEncodingHandler, NULL);
for (i = 0; handler_info[i].name != NULL; i++)
/* do nothing */;
self->handlers = PyMem_New(PyObject *, i);
if (!self->handlers) {
Py_DECREF(self);
return PyErr_NoMemory();
}
clear_handlers(self, 1);
return (PyObject*)self;
}
static void
xmlparse_dealloc(xmlparseobject *self)
{
int i;
PyObject_GC_UnTrack(self);
if (self->itself != NULL)
XML_ParserFree(self->itself);
self->itself = NULL;
if (self->handlers != NULL) {
for (i = 0; handler_info[i].name != NULL; i++)
Py_CLEAR(self->handlers[i]);
PyMem_Free(self->handlers);
self->handlers = NULL;
}
if (self->buffer != NULL) {
PyMem_Free(self->buffer);
self->buffer = NULL;
}
Py_XDECREF(self->intern);
PyObject_GC_Del(self);
}
static int
handlername2int(PyObject *name)
{
int i;
for (i = 0; handler_info[i].name != NULL; i++) {
if (_PyUnicode_EqualToASCIIString(name, handler_info[i].name)) {
return i;
}
}
return -1;
}
static PyObject *
get_pybool(int istrue)
{
PyObject *result = istrue ? Py_True : Py_False;
Py_INCREF(result);
return result;
}
static PyObject *
xmlparse_getattro(xmlparseobject *self, PyObject *nameobj)
{
Py_UCS4 first_char;
int handlernum = -1;
if (!PyUnicode_Check(nameobj))
goto generic;
if (PyUnicode_READY(nameobj))
return NULL;
handlernum = handlername2int(nameobj);
if (handlernum != -1) {
PyObject *result = self->handlers[handlernum];
if (result == NULL)
result = Py_None;
Py_INCREF(result);
return result;
}
first_char = PyUnicode_READ_CHAR(nameobj, 0);
if (first_char == 'E') {
if (_PyUnicode_EqualToASCIIString(nameobj, "ErrorCode"))
return PyLong_FromLong((long)
XML_GetErrorCode(self->itself));
if (_PyUnicode_EqualToASCIIString(nameobj, "ErrorLineNumber"))
return PyLong_FromLong((long)
XML_GetErrorLineNumber(self->itself));
if (_PyUnicode_EqualToASCIIString(nameobj, "ErrorColumnNumber"))
return PyLong_FromLong((long)
XML_GetErrorColumnNumber(self->itself));
if (_PyUnicode_EqualToASCIIString(nameobj, "ErrorByteIndex"))
return PyLong_FromLong((long)
XML_GetErrorByteIndex(self->itself));
}
if (first_char == 'C') {
if (_PyUnicode_EqualToASCIIString(nameobj, "CurrentLineNumber"))
return PyLong_FromLong((long)
XML_GetCurrentLineNumber(self->itself));
if (_PyUnicode_EqualToASCIIString(nameobj, "CurrentColumnNumber"))
return PyLong_FromLong((long)
XML_GetCurrentColumnNumber(self->itself));
if (_PyUnicode_EqualToASCIIString(nameobj, "CurrentByteIndex"))
return PyLong_FromLong((long)
XML_GetCurrentByteIndex(self->itself));
}
if (first_char == 'b') {
if (_PyUnicode_EqualToASCIIString(nameobj, "buffer_size"))
return PyLong_FromLong((long) self->buffer_size);
if (_PyUnicode_EqualToASCIIString(nameobj, "buffer_text"))
return get_pybool(self->buffer != NULL);
if (_PyUnicode_EqualToASCIIString(nameobj, "buffer_used"))
return PyLong_FromLong((long) self->buffer_used);
}
if (_PyUnicode_EqualToASCIIString(nameobj, "namespace_prefixes"))
return get_pybool(self->ns_prefixes);
if (_PyUnicode_EqualToASCIIString(nameobj, "ordered_attributes"))
return get_pybool(self->ordered_attributes);
if (_PyUnicode_EqualToASCIIString(nameobj, "specified_attributes"))
return get_pybool((long) self->specified_attributes);
if (_PyUnicode_EqualToASCIIString(nameobj, "intern")) {
if (self->intern == NULL) {
Py_INCREF(Py_None);
return Py_None;
}
else {
Py_INCREF(self->intern);
return self->intern;
}
}
generic:
return PyObject_GenericGetAttr((PyObject*)self, nameobj);
}
static int
sethandler(xmlparseobject *self, PyObject *name, PyObject* v)
{
int handlernum = handlername2int(name);
if (handlernum >= 0) {
xmlhandler c_handler = NULL;
if (v == Py_None) {
/* If this is the character data handler, and a character
data handler is already active, we need to be more
careful. What we can safely do is replace the existing
character data handler callback function with a no-op
function that will refuse to call Python. The downside
is that this doesn't completely remove the character
data handler from the C layer if there's any callback
active, so Expat does a little more work than it
otherwise would, but that's really an odd case. A more
elaborate system of handlers and state could remove the
C handler more effectively. */
if (handlernum == CharacterData && self->in_callback)
c_handler = noop_character_data_handler;
v = NULL;
}
else if (v != NULL) {
Py_INCREF(v);
c_handler = handler_info[handlernum].handler;
}
Py_XSETREF(self->handlers[handlernum], v);
handler_info[handlernum].setter(self->itself, c_handler);
return 1;
}
return 0;
}
static int
xmlparse_setattro(xmlparseobject *self, PyObject *name, PyObject *v)
{
/* Set attribute 'name' to value 'v'. v==NULL means delete */
if (!PyUnicode_Check(name)) {
PyErr_Format(PyExc_TypeError,
"attribute name must be string, not '%.200s'",
name->ob_type->tp_name);
return -1;
}
if (v == NULL) {
PyErr_SetString(PyExc_RuntimeError, "Cannot delete attribute");
return -1;
}
if (_PyUnicode_EqualToASCIIString(name, "buffer_text")) {
int b = PyObject_IsTrue(v);
if (b < 0)
return -1;
if (b) {
if (self->buffer == NULL) {
self->buffer = PyMem_Malloc(self->buffer_size);
if (self->buffer == NULL) {
PyErr_NoMemory();
return -1;
}
self->buffer_used = 0;
}
}
else if (self->buffer != NULL) {
if (flush_character_buffer(self) < 0)
return -1;
PyMem_Free(self->buffer);
self->buffer = NULL;
}
return 0;
}
if (_PyUnicode_EqualToASCIIString(name, "namespace_prefixes")) {
int b = PyObject_IsTrue(v);
if (b < 0)
return -1;
self->ns_prefixes = b;
XML_SetReturnNSTriplet(self->itself, self->ns_prefixes);
return 0;
}
if (_PyUnicode_EqualToASCIIString(name, "ordered_attributes")) {
int b = PyObject_IsTrue(v);
if (b < 0)
return -1;
self->ordered_attributes = b;
return 0;
}
if (_PyUnicode_EqualToASCIIString(name, "specified_attributes")) {
int b = PyObject_IsTrue(v);
if (b < 0)
return -1;
self->specified_attributes = b;
return 0;
}
if (_PyUnicode_EqualToASCIIString(name, "buffer_size")) {
long new_buffer_size;
if (!PyLong_Check(v)) {
PyErr_SetString(PyExc_TypeError, "buffer_size must be an integer");
return -1;
}
new_buffer_size = PyLong_AsLong(v);
if (new_buffer_size <= 0) {
if (!PyErr_Occurred())
PyErr_SetString(PyExc_ValueError, "buffer_size must be greater than zero");
return -1;
}
/* trivial case -- no change */
if (new_buffer_size == self->buffer_size) {
return 0;
}
/* 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;
}
if (self->buffer != NULL) {
/* there is already a buffer */
if (self->buffer_used != 0) {
if (flush_character_buffer(self) < 0) {
return -1;
}
}
/* free existing buffer */
PyMem_Free(self->buffer);
}
self->buffer = PyMem_Malloc(new_buffer_size);
if (self->buffer == NULL) {
PyErr_NoMemory();
return -1;
}
self->buffer_size = new_buffer_size;
return 0;
}
if (_PyUnicode_EqualToASCIIString(name, "CharacterDataHandler")) {
/* If we're changing the character data handler, flush all
* cached data with the old handler. Not sure there's a
* "right" thing to do, though, but this probably won't
* happen.
*/
if (flush_character_buffer(self) < 0)
return -1;
}
if (sethandler(self, name, v)) {
return 0;
}
PyErr_SetObject(PyExc_AttributeError, name);
return -1;
}
static int
xmlparse_traverse(xmlparseobject *op, visitproc visit, void *arg)
{
int i;
for (i = 0; handler_info[i].name != NULL; i++)
Py_VISIT(op->handlers[i]);
return 0;
}
static int
xmlparse_clear(xmlparseobject *op)
{
clear_handlers(op, 0);
Py_CLEAR(op->intern);
return 0;
}
PyDoc_STRVAR(Xmlparsetype__doc__, "XML parser");
static PyTypeObject Xmlparsetype = {
PyVarObject_HEAD_INIT(NULL, 0)
"pyexpat.xmlparser", /*tp_name*/
sizeof(xmlparseobject), /*tp_basicsize*/
0, /*tp_itemsize*/
/* methods */
(destructor)xmlparse_dealloc, /*tp_dealloc*/
(printfunc)0, /*tp_print*/
0, /*tp_getattr*/
0, /*tp_setattr*/
0, /*tp_reserved*/
(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*/
(getattrofunc)xmlparse_getattro, /* tp_getattro */
(setattrofunc)xmlparse_setattro, /* tp_setattro */
0, /* tp_as_buffer */
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /*tp_flags*/
Xmlparsetype__doc__, /* tp_doc - Documentation string */
(traverseproc)xmlparse_traverse, /* tp_traverse */
(inquiry)xmlparse_clear, /* tp_clear */
0, /* tp_richcompare */
0, /* tp_weaklistoffset */
0, /* tp_iter */
0, /* tp_iternext */
xmlparse_methods, /* tp_methods */
};
/* End of code for xmlparser objects */
/* -------------------------------------------------------- */
/*[clinic input]
pyexpat.ParserCreate
encoding: str(accept={str, NoneType}) = NULL
namespace_separator: str(accept={str, NoneType}) = NULL
intern: object = NULL
Return a new XML parser object.
[clinic start generated code]*/
static PyObject *
pyexpat_ParserCreate_impl(PyObject *module, const char *encoding,
const char *namespace_separator, PyObject *intern)
/*[clinic end generated code: output=295c0cf01ab1146c input=23d29704acad385d]*/
{
PyObject *result;
int intern_decref = 0;
if (namespace_separator != NULL
&& strlen(namespace_separator) > 1) {
PyErr_SetString(PyExc_ValueError,
"namespace_separator must be at most one"
" character, omitted, or None");
return NULL;
}
/* Explicitly passing None means no interning is desired.
Not passing anything means that a new dictionary is used. */
if (intern == Py_None)
intern = NULL;
else if (intern == NULL) {
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;
}
result = newxmlparseobject(encoding, namespace_separator, intern);
if (intern_decref) {
Py_DECREF(intern);
}
return result;
}
/*[clinic input]
pyexpat.ErrorString
code: long
/
Returns string error for given number.
[clinic start generated code]*/
static PyObject *
pyexpat_ErrorString_impl(PyObject *module, long code)
/*[clinic end generated code: output=2feae50d166f2174 input=cc67de010d9e62b3]*/
{
return Py_BuildValue("z", XML_ErrorString((int)code));
}
/* List of methods defined in the module */
static struct PyMethodDef pyexpat_methods[] = {
PYEXPAT_PARSERCREATE_METHODDEF
PYEXPAT_ERRORSTRING_METHODDEF
{NULL, NULL} /* sentinel */
};
/* Module docstring */
PyDoc_STRVAR(pyexpat_module_documentation,
"Python wrapper for Expat parser.");
/* Initialization function for the module */
#ifndef MODULE_NAME
#define MODULE_NAME "pyexpat"
#endif
#ifndef MODULE_INITFUNC
#define MODULE_INITFUNC PyInit_pyexpat
#endif
static struct PyModuleDef pyexpatmodule = {
PyModuleDef_HEAD_INIT,
MODULE_NAME,
pyexpat_module_documentation,
-1,
pyexpat_methods,
NULL,
NULL,
NULL,
NULL
};
PyMODINIT_FUNC
MODULE_INITFUNC(void)
{
PyObject *m, *d;
PyObject *errmod_name = PyUnicode_FromString(MODULE_NAME ".errors");
PyObject *errors_module;
PyObject *modelmod_name;
PyObject *model_module;
PyObject *sys_modules;
PyObject *tmpnum, *tmpstr;
PyObject *codes_dict;
PyObject *rev_codes_dict;
int res;
static struct PyExpat_CAPI capi;
PyObject *capi_object;
if (errmod_name == NULL)
return NULL;
modelmod_name = PyUnicode_FromString(MODULE_NAME ".model");
if (modelmod_name == NULL)
return NULL;
if (PyType_Ready(&Xmlparsetype) < 0)
return NULL;
/* Create the module and add the functions */
m = PyModule_Create(&pyexpatmodule);
if (m == NULL)
return NULL;
/* Add some symbolic constants to the module */
if (ErrorObject == NULL) {
ErrorObject = PyErr_NewException("xml.parsers.expat.ExpatError",
NULL, NULL);
if (ErrorObject == NULL)
return NULL;
}
Py_INCREF(ErrorObject);
PyModule_AddObject(m, "error", ErrorObject);
Py_INCREF(ErrorObject);
PyModule_AddObject(m, "ExpatError", ErrorObject);
Py_INCREF(&Xmlparsetype);
PyModule_AddObject(m, "XMLParserType", (PyObject *) &Xmlparsetype);
PyModule_AddStringConstant(m, "EXPAT_VERSION",
XML_ExpatVersion());
{
XML_Expat_Version info = XML_ExpatVersionInfo();
PyModule_AddObject(m, "version_info",
Py_BuildValue("(iii)", info.major,
info.minor, info.micro));
}
/* XXX When Expat supports some way of figuring out how it was
compiled, this should check and set native_encoding
appropriately.
*/
PyModule_AddStringConstant(m, "native_encoding", "UTF-8");
sys_modules = PySys_GetObject("modules");
if (sys_modules == NULL) {
Py_DECREF(m);
return NULL;
}
d = PyModule_GetDict(m);
if (d == NULL) {
Py_DECREF(m);
return NULL;
}
errors_module = PyDict_GetItem(d, errmod_name);
if (errors_module == NULL) {
errors_module = PyModule_New(MODULE_NAME ".errors");
if (errors_module != NULL) {
PyDict_SetItem(sys_modules, errmod_name, errors_module);
/* gives away the reference to errors_module */
PyModule_AddObject(m, "errors", errors_module);
}
}
Py_DECREF(errmod_name);
model_module = PyDict_GetItem(d, modelmod_name);
if (model_module == NULL) {
model_module = PyModule_New(MODULE_NAME ".model");
if (model_module != NULL) {
PyDict_SetItem(sys_modules, modelmod_name, model_module);
/* gives away the reference to model_module */
PyModule_AddObject(m, "model", model_module);
}
}
Py_DECREF(modelmod_name);
if (errors_module == NULL || model_module == NULL) {
/* Don't core dump later! */
Py_DECREF(m);
return NULL;
}
#if XML_COMBINED_VERSION > 19505
{
const XML_Feature *features = XML_GetFeatureList();
PyObject *list = PyList_New(0);
if (list == NULL)
/* just ignore it */
PyErr_Clear();
else {
int i = 0;
for (; features[i].feature != XML_FEATURE_END; ++i) {
int ok;
PyObject *item = Py_BuildValue("si", features[i].name,
features[i].value);
if (item == NULL) {
Py_DECREF(list);
list = NULL;
break;
}
ok = PyList_Append(list, item);
Py_DECREF(item);
if (ok < 0) {
PyErr_Clear();
break;
}
}
if (list != NULL)
PyModule_AddObject(m, "features", list);
}
}
#endif
codes_dict = PyDict_New();
rev_codes_dict = PyDict_New();
if (codes_dict == NULL || rev_codes_dict == NULL) {
Py_XDECREF(codes_dict);
Py_XDECREF(rev_codes_dict);
return NULL;
}
#define MYCONST(name) \
if (PyModule_AddStringConstant(errors_module, #name, \
XML_ErrorString(name)) < 0) \
return NULL; \
tmpnum = PyLong_FromLong(name); \
if (tmpnum == NULL) return NULL; \
res = PyDict_SetItemString(codes_dict, \
XML_ErrorString(name), tmpnum); \
if (res < 0) return NULL; \
tmpstr = PyUnicode_FromString(XML_ErrorString(name)); \
if (tmpstr == NULL) return NULL; \
res = PyDict_SetItem(rev_codes_dict, tmpnum, tmpstr); \
Py_DECREF(tmpstr); \
Py_DECREF(tmpnum); \
if (res < 0) return NULL; \
MYCONST(XML_ERROR_NO_MEMORY);
MYCONST(XML_ERROR_SYNTAX);
MYCONST(XML_ERROR_NO_ELEMENTS);
MYCONST(XML_ERROR_INVALID_TOKEN);
MYCONST(XML_ERROR_UNCLOSED_TOKEN);
MYCONST(XML_ERROR_PARTIAL_CHAR);
MYCONST(XML_ERROR_TAG_MISMATCH);
MYCONST(XML_ERROR_DUPLICATE_ATTRIBUTE);
MYCONST(XML_ERROR_JUNK_AFTER_DOC_ELEMENT);
MYCONST(XML_ERROR_PARAM_ENTITY_REF);
MYCONST(XML_ERROR_UNDEFINED_ENTITY);
MYCONST(XML_ERROR_RECURSIVE_ENTITY_REF);
MYCONST(XML_ERROR_ASYNC_ENTITY);
MYCONST(XML_ERROR_BAD_CHAR_REF);
MYCONST(XML_ERROR_BINARY_ENTITY_REF);
MYCONST(XML_ERROR_ATTRIBUTE_EXTERNAL_ENTITY_REF);
MYCONST(XML_ERROR_MISPLACED_XML_PI);
MYCONST(XML_ERROR_UNKNOWN_ENCODING);
MYCONST(XML_ERROR_INCORRECT_ENCODING);
MYCONST(XML_ERROR_UNCLOSED_CDATA_SECTION);
MYCONST(XML_ERROR_EXTERNAL_ENTITY_HANDLING);
MYCONST(XML_ERROR_NOT_STANDALONE);
MYCONST(XML_ERROR_UNEXPECTED_STATE);
MYCONST(XML_ERROR_ENTITY_DECLARED_IN_PE);
MYCONST(XML_ERROR_FEATURE_REQUIRES_XML_DTD);
MYCONST(XML_ERROR_CANT_CHANGE_FEATURE_ONCE_PARSING);
/* Added in Expat 1.95.7. */
MYCONST(XML_ERROR_UNBOUND_PREFIX);
/* Added in Expat 1.95.8. */
MYCONST(XML_ERROR_UNDECLARING_PREFIX);
MYCONST(XML_ERROR_INCOMPLETE_PE);
MYCONST(XML_ERROR_XML_DECL);
MYCONST(XML_ERROR_TEXT_DECL);
MYCONST(XML_ERROR_PUBLICID);
MYCONST(XML_ERROR_SUSPENDED);
MYCONST(XML_ERROR_NOT_SUSPENDED);
MYCONST(XML_ERROR_ABORTED);
MYCONST(XML_ERROR_FINISHED);
MYCONST(XML_ERROR_SUSPEND_PE);
if (PyModule_AddStringConstant(errors_module, "__doc__",
"Constants used to describe "
"error conditions.") < 0)
return NULL;
if (PyModule_AddObject(errors_module, "codes", codes_dict) < 0)
return NULL;
if (PyModule_AddObject(errors_module, "messages", rev_codes_dict) < 0)
return NULL;
#undef MYCONST
#define MYCONST(c) PyModule_AddIntConstant(m, #c, c)
MYCONST(XML_PARAM_ENTITY_PARSING_NEVER);
MYCONST(XML_PARAM_ENTITY_PARSING_UNLESS_STANDALONE);
MYCONST(XML_PARAM_ENTITY_PARSING_ALWAYS);
#undef MYCONST
#define MYCONST(c) PyModule_AddIntConstant(model_module, #c, c)
PyModule_AddStringConstant(model_module, "__doc__",
"Constants used to interpret content model information.");
MYCONST(XML_CTYPE_EMPTY);
MYCONST(XML_CTYPE_ANY);
MYCONST(XML_CTYPE_MIXED);
MYCONST(XML_CTYPE_NAME);
MYCONST(XML_CTYPE_CHOICE);
MYCONST(XML_CTYPE_SEQ);
MYCONST(XML_CQUANT_NONE);
MYCONST(XML_CQUANT_OPT);
MYCONST(XML_CQUANT_REP);
MYCONST(XML_CQUANT_PLUS);
#undef MYCONST
/* initialize pyexpat dispatch table */
capi.size = sizeof(capi);
capi.magic = PyExpat_CAPI_MAGIC;
capi.MAJOR_VERSION = XML_MAJOR_VERSION;
capi.MINOR_VERSION = XML_MINOR_VERSION;
capi.MICRO_VERSION = XML_MICRO_VERSION;
capi.ErrorString = XML_ErrorString;
capi.GetErrorCode = XML_GetErrorCode;
capi.GetErrorColumnNumber = XML_GetErrorColumnNumber;
capi.GetErrorLineNumber = XML_GetErrorLineNumber;
capi.Parse = XML_Parse;
capi.ParserCreate_MM = XML_ParserCreate_MM;
capi.ParserFree = XML_ParserFree;
capi.SetCharacterDataHandler = XML_SetCharacterDataHandler;
capi.SetCommentHandler = XML_SetCommentHandler;
capi.SetDefaultHandlerExpand = XML_SetDefaultHandlerExpand;
capi.SetElementHandler = XML_SetElementHandler;
capi.SetNamespaceDeclHandler = XML_SetNamespaceDeclHandler;
capi.SetProcessingInstructionHandler = XML_SetProcessingInstructionHandler;
capi.SetUnknownEncodingHandler = XML_SetUnknownEncodingHandler;
capi.SetUserData = XML_SetUserData;
capi.SetStartDoctypeDeclHandler = XML_SetStartDoctypeDeclHandler;
capi.SetEncoding = XML_SetEncoding;
capi.DefaultUnknownEncodingHandler = PyUnknownEncodingHandler;
#if XML_COMBINED_VERSION >= 20100
capi.SetHashSalt = XML_SetHashSalt;
#else
capi.SetHashSalt = NULL;
#endif
/* export using capsule */
capi_object = PyCapsule_New(&capi, PyExpat_CAPSULE_NAME, NULL);
if (capi_object)
PyModule_AddObject(m, "expat_CAPI", capi_object);
return m;
}
static void
clear_handlers(xmlparseobject *self, int initial)
{
int i = 0;
for (; handler_info[i].name != NULL; i++) {
if (initial)
self->handlers[i] = NULL;
else {
Py_CLEAR(self->handlers[i]);
handler_info[i].setter(self->itself, NULL);
}
}
}
static struct HandlerInfo handler_info[] = {
{"StartElementHandler",
(xmlhandlersetter)XML_SetStartElementHandler,
(xmlhandler)my_StartElementHandler},
{"EndElementHandler",
(xmlhandlersetter)XML_SetEndElementHandler,
(xmlhandler)my_EndElementHandler},
{"ProcessingInstructionHandler",
(xmlhandlersetter)XML_SetProcessingInstructionHandler,
(xmlhandler)my_ProcessingInstructionHandler},
{"CharacterDataHandler",
(xmlhandlersetter)XML_SetCharacterDataHandler,
(xmlhandler)my_CharacterDataHandler},
{"UnparsedEntityDeclHandler",
(xmlhandlersetter)XML_SetUnparsedEntityDeclHandler,
(xmlhandler)my_UnparsedEntityDeclHandler},
{"NotationDeclHandler",
(xmlhandlersetter)XML_SetNotationDeclHandler,
(xmlhandler)my_NotationDeclHandler},
{"StartNamespaceDeclHandler",
(xmlhandlersetter)XML_SetStartNamespaceDeclHandler,
(xmlhandler)my_StartNamespaceDeclHandler},
{"EndNamespaceDeclHandler",
(xmlhandlersetter)XML_SetEndNamespaceDeclHandler,
(xmlhandler)my_EndNamespaceDeclHandler},
{"CommentHandler",
(xmlhandlersetter)XML_SetCommentHandler,
(xmlhandler)my_CommentHandler},
{"StartCdataSectionHandler",
(xmlhandlersetter)XML_SetStartCdataSectionHandler,
(xmlhandler)my_StartCdataSectionHandler},
{"EndCdataSectionHandler",
(xmlhandlersetter)XML_SetEndCdataSectionHandler,
(xmlhandler)my_EndCdataSectionHandler},
{"DefaultHandler",
(xmlhandlersetter)XML_SetDefaultHandler,
(xmlhandler)my_DefaultHandler},
{"DefaultHandlerExpand",
(xmlhandlersetter)XML_SetDefaultHandlerExpand,
(xmlhandler)my_DefaultHandlerExpandHandler},
{"NotStandaloneHandler",
(xmlhandlersetter)XML_SetNotStandaloneHandler,
(xmlhandler)my_NotStandaloneHandler},
{"ExternalEntityRefHandler",
(xmlhandlersetter)XML_SetExternalEntityRefHandler,
(xmlhandler)my_ExternalEntityRefHandler},
{"StartDoctypeDeclHandler",
(xmlhandlersetter)XML_SetStartDoctypeDeclHandler,
(xmlhandler)my_StartDoctypeDeclHandler},
{"EndDoctypeDeclHandler",
(xmlhandlersetter)XML_SetEndDoctypeDeclHandler,
(xmlhandler)my_EndDoctypeDeclHandler},
{"EntityDeclHandler",
(xmlhandlersetter)XML_SetEntityDeclHandler,
(xmlhandler)my_EntityDeclHandler},
{"XmlDeclHandler",
(xmlhandlersetter)XML_SetXmlDeclHandler,
(xmlhandler)my_XmlDeclHandler},
{"ElementDeclHandler",
(xmlhandlersetter)XML_SetElementDeclHandler,
(xmlhandler)my_ElementDeclHandler},
{"AttlistDeclHandler",
(xmlhandlersetter)XML_SetAttlistDeclHandler,
(xmlhandler)my_AttlistDeclHandler},
#if XML_COMBINED_VERSION >= 19504
{"SkippedEntityHandler",
(xmlhandlersetter)XML_SetSkippedEntityHandler,
(xmlhandler)my_SkippedEntityHandler},
#endif
{NULL, NULL, NULL} /* sentinel */
};
/*[clinic input]
dump buffer
[clinic start generated code]*/
/*[clinic end generated code: output=da39a3ee5e6b4b0d input=524ce2e021e4eba6]*/
_Section(".rodata.pytab.1") const struct _inittab _PyImport_Inittab_pyexpat = {
"pyexpat",
PyInit_pyexpat,
};
| 64,634 | 2,048 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Modules/getpath.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:8;coding:utf-8 -*-â
âvi: set net ft=c ts=4 sts=4 sw=4 fenc=utf-8 :viâ
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ¡
â Python 3 â
â https://docs.python.org/3/license.html â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
#include "libc/calls/calls.h"
#include "libc/calls/struct/stat.h"
#include "libc/errno.h"
#include "libc/intrin/cmpxchg.h"
#include "libc/log/log.h"
#include "libc/mem/alloca.h"
#include "libc/mem/mem.h"
#include "libc/mem/gc.internal.h"
#include "libc/runtime/runtime.h"
#include "libc/str/str.h"
#include "libc/sysv/consts/auxv.h"
#include "libc/sysv/consts/s.h"
#include "libc/x/x.h"
#include "third_party/python/Include/fileutils.h"
#include "third_party/python/Include/osdefs.h"
#include "third_party/python/Include/pyerrors.h"
#include "third_party/python/Include/pymem.h"
/* clang-format off */
/* Return the initial module search path. */
#pragma GCC diagnostic ignored "-Wunused-function" // search_for_exec_prefix
#pragma GCC diagnostic ignored "-Wunused-but-set-variable" // separator
/* Search in some common locations for the associated Python libraries.
*
* Two directories must be found, the platform independent directory
* (prefix), containing the common .py and .pyc files, and the platform
* dependent directory (exec_prefix), containing the shared library
* modules. Note that prefix and exec_prefix can be the same directory,
* but for some installations, they are different.
*
* Py_GetPath() carries out separate searches for prefix and exec_prefix.
* Each search tries a number of different locations until a ``landmark''
* file or directory is found. If no prefix or exec_prefix is found, a
* warning message is issued and the preprocessor defined PREFIX and
* EXEC_PREFIX are used (even though they will not work); python carries on
* as best as is possible, but most imports will fail.
*
* Before any searches are done, the location of the executable is
* determined. If argv[0] has one or more slashes in it, it is used
* unchanged. Otherwise, it must have been invoked from the shell's path,
* so we search $PATH for the named executable and use that. If the
* executable was not found on $PATH (or there was no $PATH environment
* variable), the original argv[0] string is used.
*
* Next, the executable location is examined to see if it is a symbolic
* link. If so, the link is chased (correctly interpreting a relative
* pathname if one is found) and the directory of the link target is used.
*
* Finally, argv0_path is set to the directory containing the executable
* (i.e. the last component is stripped).
*
* With argv0_path in hand, we perform a number of steps. The same steps
* are performed for prefix and for exec_prefix, but with a different
* landmark.
*
* Step 1. Are we running python out of the build directory? This is
* checked by looking for a different kind of landmark relative to
* argv0_path. For prefix, the landmark's path is derived from the VPATH
* preprocessor variable (taking into account that its value is almost, but
* not quite, what we need). For exec_prefix, the landmark is
* pybuilddir.txt. If the landmark is found, we're done.
*
* For the remaining steps, the prefix landmark will always be
* lib/python$VERSION/os.py and the exec_prefix will always be
* lib/python$VERSION/lib-dynload, where $VERSION is Python's version
* number as supplied by the Makefile. Note that this means that no more
* build directory checking is performed; if the first step did not find
* the landmarks, the assumption is that python is running from an
* installed setup.
*
* Step 2. See if the $PYTHONHOME environment variable points to the
* installed location of the Python libraries. If $PYTHONHOME is set, then
* it points to prefix and exec_prefix. $PYTHONHOME can be a single
* directory, which is used for both, or the prefix and exec_prefix
* directories separated by a colon.
*
* Step 3. Try to find prefix and exec_prefix relative to argv0_path,
* backtracking up the path until it is exhausted. This is the most common
* step to succeed. Note that if prefix and exec_prefix are different,
* exec_prefix is more likely to be found; however if exec_prefix is a
* subdirectory of prefix, both will be found.
*
* Step 4. Search the directories pointed to by the preprocessor variables
* PREFIX and EXEC_PREFIX. These are supplied by the Makefile but can be
* passed in as options to the configure script.
*
* That's it!
*
* Well, almost. Once we have determined prefix and exec_prefix, the
* preprocessor variable PYTHONPATH is used to construct a path. Each
* relative path on PYTHONPATH is prefixed with prefix. Then the directory
* containing the shared library modules is appended. The environment
* variable $PYTHONPATH is inserted in front of it all. Finally, the
* prefix and exec_prefix globals are tweaked so they reflect the values
* expected by other code, by stripping the "lib/python$VERSION/..." stuff
* off. If either points to the build directory, the globals are reset to
* the corresponding preprocessor variables (so sys.prefix will reflect the
* installation location, even though sys.path points into the build
* directory). This seems to make more sense given that currently the only
* known use of sys.prefix and sys.exec_prefix is for the ILU installation
* process to find the installed Python tree.
*
* An embedding application can use Py_SetPath() to override all of
* these authomatic path computations.
*
* NOTE: Windows MSVC builds use PC/getpathp.c instead!
*/
wchar_t *Py_GetProgramName(void);
#if !defined(PREFIX) || !defined(EXEC_PREFIX) || !defined(VERSION) || !defined(VPATH)
#define PREFIX L"Lib"
#define EXEC_PREFIX L"build"
#define VERSION L"3.6"
#define VPATH ""
// #error "PREFIX, EXEC_PREFIX, VERSION, and VPATH must be constant defined"
#endif
#ifndef LANDMARK
#define LANDMARK L"os.py"
#endif
#define LIMITED_SEARCH_PATH L"/zip/.python"
static wchar_t *progpath;
static wchar_t *prefix = LIMITED_SEARCH_PATH;
static wchar_t *exec_prefix = LIMITED_SEARCH_PATH;
static wchar_t *module_search_path = LIMITED_SEARCH_PATH;
/* Get file status. Encode the path to the locale encoding. */
static int
_Py_wstat(const wchar_t* path, struct stat *buf)
{
int err;
char *fname;
fname = Py_EncodeLocale(path, NULL);
if (fname == NULL) {
errno = EINVAL;
return -1;
}
err = stat(fname, buf);
PyMem_Free(fname);
return err;
}
static void
reduce(wchar_t *dir)
{
size_t i = wcslen(dir);
while (i > 0 && dir[i] != SEP)
--i;
dir[i] = '\0';
}
static int
isfile(wchar_t *filename) /* Is file, not directory */
{
struct stat buf;
if (_Py_wstat(filename, &buf) != 0)
return 0;
if (!S_ISREG(buf.st_mode))
return 0;
return 1;
}
static int
ismodule(wchar_t *filename) /* Is module -- check for .pyc too */
{
if (isfile(filename))
return 1;
/* Check for the compiled version of prefix. */
if (wcslen(filename) < MAXPATHLEN) {
wcscat(filename, L"c");
if (isfile(filename))
return 1;
}
return 0;
}
static int
isxfile(wchar_t *filename) /* Is executable file */
{
struct stat buf;
if (_Py_wstat(filename, &buf) != 0)
return 0;
if (!S_ISREG(buf.st_mode))
return 0;
if ((buf.st_mode & 0111) == 0)
return 0;
return 1;
}
static int
isdir(wchar_t *filename) /* Is directory */
{
struct stat buf;
if (_Py_wstat(filename, &buf) != 0)
return 0;
if (!S_ISDIR(buf.st_mode))
return 0;
return 1;
}
/* Add a path component, by appending stuff to buffer.
buffer must have at least MAXPATHLEN + 1 bytes allocated, and contain a
NUL-terminated string with no more than MAXPATHLEN characters (not counting
the trailing NUL). It's a fatal error if it contains a string longer than
that (callers must be careful!). If these requirements are met, it's
guaranteed that buffer will still be a NUL-terminated string with no more
than MAXPATHLEN characters at exit. If stuff is too long, only as much of
stuff as fits will be appended.
*/
static void
joinpath(wchar_t *buffer, wchar_t *stuff)
{
size_t n, k;
if (stuff[0] == SEP)
n = 0;
else {
n = wcslen(buffer);
if (n > 0 && buffer[n-1] != SEP && n < MAXPATHLEN)
buffer[n++] = SEP;
}
if (n > MAXPATHLEN)
Py_FatalError("buffer overflow in getpath.c's joinpath()");
k = wcslen(stuff);
if (n + k > MAXPATHLEN)
k = MAXPATHLEN - n;
wcsncpy(buffer+n, stuff, k);
buffer[n+k] = '\0';
}
/* copy_absolute requires that path be allocated at least
MAXPATHLEN + 1 bytes and that p be no more than MAXPATHLEN bytes. */
static void
copy_absolute(wchar_t *path, wchar_t *p, size_t pathlen)
{
if (p[0] == SEP)
wcscpy(path, p);
else {
if (!_Py_wgetcwd(path, pathlen)) {
/* unable to get the current directory */
wcscpy(path, p);
return;
}
if (p[0] == '.' && p[1] == SEP)
p += 2;
joinpath(path, p);
}
}
/* absolutize() requires that path be allocated at least MAXPATHLEN+1 bytes. */
static void
absolutize(wchar_t *path)
{
wchar_t *buffer = gc(calloc(MAXPATHLEN+1, sizeof(wchar_t)));
if (path[0] == SEP) return;
copy_absolute(buffer, path, MAXPATHLEN+1);
wcscpy(path, buffer);
}
/* search for a prefix value in an environment file. If found, copy it
to the provided buffer, which is expected to be no more than MAXPATHLEN
bytes long.
*/
static int
find_env_config_value(FILE * env_file, const wchar_t * key, wchar_t * value)
{
int result = 0; /* meaning not found */
char buffer[MAXPATHLEN*2+1]; /* allow extra for key, '=', etc. */
fseek(env_file, 0, SEEK_SET);
while (!feof(env_file)) {
char * p = fgets(buffer, MAXPATHLEN*2, env_file);
wchar_t tmpbuffer[MAXPATHLEN*2+1];
PyObject * decoded;
int n;
if (p == NULL)
break;
n = strlen(p);
if (p[n - 1] != '\n') {
/* line has overflowed - bail */
break;
}
if (p[0] == '#') /* Comment - skip */
continue;
decoded = PyUnicode_DecodeUTF8(buffer, n, "surrogateescape");
if (decoded != NULL) {
Py_ssize_t k;
wchar_t * state;
k = PyUnicode_AsWideChar(decoded,
tmpbuffer, MAXPATHLEN * 2);
Py_DECREF(decoded);
if (k >= 0) {
wchar_t * tok = wcstok(tmpbuffer, L" \t\r\n", &state);
if ((tok != NULL) && !wcscmp(tok, key)) {
tok = wcstok(NULL, L" \t", &state);
if ((tok != NULL) && !wcscmp(tok, L"=")) {
tok = wcstok(NULL, L"\r\n", &state);
if (tok != NULL) {
wcsncpy(value, tok, MAXPATHLEN);
result = 1;
break;
}
}
}
}
}
}
return result;
}
/* search_for_prefix requires that argv0_path be no more than MAXPATHLEN
bytes long.
*/
static int
search_for_prefix(wchar_t *argv0_path, wchar_t *home, wchar_t *_prefix,
wchar_t *lib_python)
{
size_t n;
wchar_t *vpath;
/* If PYTHONHOME is set, we believe it unconditionally */
if (home) {
wchar_t *delim;
wcsncpy(prefix, home, MAXPATHLEN);
prefix[MAXPATHLEN] = L'\0';
delim = wcschr(prefix, DELIM);
if (delim)
*delim = L'\0';
joinpath(prefix, lib_python);
joinpath(prefix, LANDMARK);
return 1;
}
/* Check to see if argv[0] is in the build directory */
wcsncpy(prefix, argv0_path, MAXPATHLEN);
prefix[MAXPATHLEN] = L'\0';
joinpath(prefix, L"Modules/Setup");
if (isfile(prefix)) {
/* Check VPATH to see if argv0_path is in the build directory. */
vpath = Py_DecodeLocale(VPATH, NULL);
if (vpath != NULL) {
wcsncpy(prefix, argv0_path, MAXPATHLEN);
prefix[MAXPATHLEN] = L'\0';
joinpath(prefix, vpath);
PyMem_RawFree(vpath);
joinpath(prefix, L"Lib");
joinpath(prefix, LANDMARK);
if (ismodule(prefix))
return -1;
}
}
/* Search from argv0_path, until root is found */
copy_absolute(prefix, argv0_path, MAXPATHLEN+1);
do {
n = wcslen(prefix);
joinpath(prefix, lib_python);
joinpath(prefix, LANDMARK);
if (ismodule(prefix))
return 1;
prefix[n] = L'\0';
reduce(prefix);
} while (prefix[0]);
/* Look at configure's PREFIX */
wcsncpy(prefix, _prefix, MAXPATHLEN);
prefix[MAXPATHLEN] = L'\0';
joinpath(prefix, lib_python);
joinpath(prefix, LANDMARK);
if (ismodule(prefix))
return 1;
/* Fail */
return 0;
}
/* search_for_exec_prefix requires that argv0_path be no more than
MAXPATHLEN bytes long.
*/
static int
search_for_exec_prefix(wchar_t *argv0_path, wchar_t *home,
wchar_t *_exec_prefix, wchar_t *lib_python)
{
size_t n;
/* If PYTHONHOME is set, we believe it unconditionally */
if (home) {
wchar_t *delim;
delim = wcschr(home, DELIM);
if (delim)
wcsncpy(exec_prefix, delim+1, MAXPATHLEN);
else
wcsncpy(exec_prefix, home, MAXPATHLEN);
exec_prefix[MAXPATHLEN] = L'\0';
joinpath(exec_prefix, lib_python);
joinpath(exec_prefix, L"lib-dynload");
return 1;
}
/* Check to see if argv[0] is in the build directory. "pybuilddir.txt"
is written by setup.py and contains the relative path to the location
of shared library modules. */
wcsncpy(exec_prefix, argv0_path, MAXPATHLEN);
exec_prefix[MAXPATHLEN] = L'\0';
joinpath(exec_prefix, L"pybuilddir.txt");
if (isfile(exec_prefix)) {
FILE *f = _Py_wfopen(exec_prefix, L"rb");
if (f == NULL)
errno = 0;
else {
char buf[MAXPATHLEN+1];
PyObject *decoded;
wchar_t rel_builddir_path[MAXPATHLEN+1];
n = fread(buf, 1, MAXPATHLEN, f);
buf[n] = '\0';
fclose(f);
decoded = PyUnicode_DecodeUTF8(buf, n, "surrogateescape");
if (decoded != NULL) {
Py_ssize_t k;
k = PyUnicode_AsWideChar(decoded,
rel_builddir_path, MAXPATHLEN);
Py_DECREF(decoded);
if (k >= 0) {
rel_builddir_path[k] = L'\0';
wcsncpy(exec_prefix, argv0_path, MAXPATHLEN);
exec_prefix[MAXPATHLEN] = L'\0';
joinpath(exec_prefix, rel_builddir_path);
return -1;
}
}
}
}
/* Search from argv0_path, until root is found */
copy_absolute(exec_prefix, argv0_path, MAXPATHLEN+1);
do {
n = wcslen(exec_prefix);
joinpath(exec_prefix, lib_python);
joinpath(exec_prefix, L"lib-dynload");
if (isdir(exec_prefix))
return 1;
exec_prefix[n] = L'\0';
reduce(exec_prefix);
} while (exec_prefix[0]);
/* Look at configure's EXEC_PREFIX */
wcsncpy(exec_prefix, _exec_prefix, MAXPATHLEN);
exec_prefix[MAXPATHLEN] = L'\0';
joinpath(exec_prefix, lib_python);
joinpath(exec_prefix, L"lib-dynload");
if (isdir(exec_prefix))
return 1;
/* Fail */
return 0;
}
static void
calculate_path(void)
{
static wchar_t delimiter[2] = {DELIM, '\0'};
static wchar_t separator[2] = {SEP, '\0'};
/* ignore PYTHONPATH/PYTHONHOME for now */
// char *_rtpypath = Py_GETENV("PYTHONPATH");
/* XXX use wide version on Windows */
// wchar_t *rtpypath = NULL;
// wchar_t *home = Py_GetPythonHome();
char *_path = getenv("PATH");
wchar_t *path_buffer = NULL;
wchar_t *path = NULL;
wchar_t *prog = Py_GetProgramName();
/* wont need zip_path because embedded stdlib inside executable */
/* wchar_t zip_path[MAXPATHLEN+1]; */
wchar_t *buf;
size_t bufsz;
size_t ape_length;
wchar_t *ape_path = gc(calloc(MAXPATHLEN+1, sizeof(wchar_t)));
wchar_t *argv0_path = gc(calloc(MAXPATHLEN+1, sizeof(wchar_t)));
wchar_t *ape_lib_path = gc(calloc(MAXPATHLEN+1, sizeof(wchar_t)));
wchar_t *ape_exec_path = gc(calloc(MAXPATHLEN+1, sizeof(wchar_t)));
wchar_t *package_path = gc(calloc(MAXPATHLEN+1, sizeof(wchar_t)));
wchar_t *ape_package_path = gc(calloc(MAXPATHLEN+1, sizeof(wchar_t)));
if (IsWindows()) {
delimiter[0] = L';';
separator[0] = L'\\';
}
if (_path) {
path_buffer = Py_DecodeLocale(_path, NULL);
path = path_buffer;
}
/* 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 (wcschr(prog, SEP)) {
wcsncpy(progpath, prog, MAXPATHLEN);
} else if (path) {
while (1) {
wchar_t *delim = wcschr(path, DELIM);
if (delim) {
size_t len = delim - path;
if (len > MAXPATHLEN)
len = MAXPATHLEN;
wcsncpy(progpath, path, len);
*(progpath + len) = '\0';
}
else
wcsncpy(progpath, path, MAXPATHLEN);
joinpath(progpath, prog);
if (isxfile(progpath))
break;
if (!delim) {
progpath[0] = L'\0';
break;
}
path = delim + 1;
}
} else {
progpath[0] = '\0';
}
PyMem_RawFree(path_buffer);
if (progpath[0] != SEP && progpath[0] != '\0')
absolutize(progpath);
wcsncpy(argv0_path, progpath, MAXPATHLEN);
argv0_path[MAXPATHLEN] = '\0';
reduce(argv0_path);
/* At this point, argv0_path is guaranteed to be less than
MAXPATHLEN bytes long.
*/
/* not searching for pyvenv.cfg */
/* Avoid absolute path for prefix */
wcsncpy(prefix,
L"third_party/python/Lib",
MAXPATHLEN);
/* wcsncpy(prefix, */
/* L"/zip/.python", */
/* MAXPATHLEN); */
/* Avoid absolute path for exec_prefix */
wcsncpy(exec_prefix, L"build/lib.linux-x86_64-3.6", MAXPATHLEN);
wcsncpy(package_path, L"Lib/site-packages", MAXPATHLEN);
/* add paths for the internal store of the APE */
if (wcslen(progpath) > 0 && wcslen(progpath) + 1 < MAXPATHLEN)
wcsncpy(ape_path, progpath, MAXPATHLEN);
else
wcsncpy(ape_path, prog, MAXPATHLEN);
ape_length = wcslen(ape_path);
wcsncpy(ape_lib_path, ape_path, MAXPATHLEN);
// extra 1 at the start for the slash
if(ape_length + 1 + wcslen(prefix) + 1 < MAXPATHLEN)
{
ape_lib_path[ape_length] = L'/';
wcscat(ape_lib_path + ape_length + 1, prefix);
}
wcsncpy(ape_exec_path, ape_path, MAXPATHLEN);
if(ape_length + 1 + wcslen(exec_prefix) + 1 < MAXPATHLEN)
{
ape_exec_path[ape_length] = L'/';
wcscat(ape_exec_path + ape_length + 1, exec_prefix);
}
wcsncpy(ape_package_path, ape_path, MAXPATHLEN);
if(ape_length + 1 + wcslen(package_path) + 1 < MAXPATHLEN)
{
ape_package_path[ape_length] = L'/';
wcscat(ape_package_path + ape_length + 1, package_path);
}
/* Calculate size of return buffer */
bufsz = 0;
bufsz += wcslen(ape_lib_path) + 1;
bufsz += wcslen(ape_exec_path) + 1;
bufsz += wcslen(ape_package_path) + 1;
bufsz += wcslen(ape_path) + 1;
bufsz += wcslen(prefix) + 1;
bufsz += wcslen(exec_prefix) + 1;
bufsz += wcslen(package_path) + 1;
/* This is the only malloc call in this file */
buf = PyMem_RawMalloc(bufsz * sizeof(wchar_t));
if (buf == NULL) {
Py_FatalError(
"Not enough memory for dynamic PYTHONPATH");
}
buf[0] = L'\0';
wcscat(buf, prefix);
wcscat(buf, delimiter);
wcscat(buf, package_path);
wcscat(buf, delimiter);
wcscat(buf, ape_lib_path);
wcscat(buf, delimiter);
wcscat(buf, ape_package_path);
wcscat(buf, delimiter);
wcscat(buf, ape_exec_path);
wcscat(buf, delimiter);
wcscat(buf, ape_path);
wcscat(buf, delimiter);
/* Finally, on goes the directory for dynamic-load modules */
wcscat(buf, exec_prefix);
/* And publish the results */
module_search_path = buf;
// printf("%ls\n", buf);
}
/* External interface */
void
Py_SetPath(const wchar_t *path)
{
if (module_search_path != NULL) {
PyMem_RawFree(module_search_path);
module_search_path = NULL;
}
if (path != NULL) {
wchar_t *prog = Py_GetProgramName();
wcsncpy(progpath, prog, MAXPATHLEN);
exec_prefix[0] = prefix[0] = L'\0';
module_search_path = PyMem_RawMalloc((wcslen(path) + 1) * sizeof(wchar_t));
if (module_search_path != NULL)
wcscpy(module_search_path, path);
}
}
wchar_t *
Py_GetPath(void)
{
if (!module_search_path)
calculate_path();
return module_search_path;
}
wchar_t *
Py_GetPrefix(void)
{
if (!module_search_path)
calculate_path();
return prefix;
}
wchar_t *
Py_GetExecPrefix(void)
{
if (!module_search_path)
calculate_path();
return exec_prefix;
}
wchar_t *
Py_GetProgramFullPath(void)
{
static bool once;
if (_cmpxchg(&once, false, true)) {
progpath = utf8to32(GetProgramExecutableName(), -1, 0);
__cxa_atexit(free, progpath, 0);
}
return progpath;
}
void
Py_LimitedPath(void)
{
prefix = wcscpy(PyMem_RawMalloc((wcslen(LIMITED_SEARCH_PATH) + 1) * 4), LIMITED_SEARCH_PATH);
exec_prefix = wcscpy(PyMem_RawMalloc((wcslen(LIMITED_SEARCH_PATH) + 1) * 4), LIMITED_SEARCH_PATH);
module_search_path = wcscpy(PyMem_RawMalloc((wcslen(LIMITED_SEARCH_PATH) + 1) * 4), LIMITED_SEARCH_PATH);
}
| 22,978 | 680 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Modules/arraymodule.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:8;coding:utf-8 -*-â
âvi: set net ft=c ts=4 sts=4 sw=4 fenc=utf-8 :viâ
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ¡
â Python 3 â
â https://docs.python.org/3/license.html â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
#define PY_SSIZE_T_CLEAN
#include "third_party/python/Include/abstract.h"
#include "third_party/python/Include/boolobject.h"
#include "third_party/python/Include/bytearrayobject.h"
#include "third_party/python/Include/descrobject.h"
#include "third_party/python/Include/floatobject.h"
#include "third_party/python/Include/import.h"
#include "third_party/python/Include/longobject.h"
#include "third_party/python/Include/modsupport.h"
#include "third_party/python/Include/objimpl.h"
#include "third_party/python/Include/pyerrors.h"
#include "third_party/python/Include/pymacro.h"
#include "third_party/python/Include/pymem.h"
#include "third_party/python/Include/sliceobject.h"
#include "third_party/python/Include/structmember.h"
#include "third_party/python/Include/unicodeobject.h"
#include "third_party/python/Include/warnings.h"
#include "third_party/python/Include/yoink.h"
/* clang-format off */
PYTHON_PROVIDE("array");
PYTHON_PROVIDE("array.ArrayType");
PYTHON_PROVIDE("array._array_reconstructor");
PYTHON_PROVIDE("array.array");
PYTHON_PROVIDE("array.typecodes");
/* Array object implementation */
/* An array is a uniform list -- all items have the same type.
The item type is restricted to simple C types like int or float */
/*[clinic input]
module array
[clinic start generated code]*/
/*[clinic end generated code: output=da39a3ee5e6b4b0d input=7d1b8d7f5958fd83]*/
struct arrayobject; /* Forward */
/* All possible arraydescr values are defined in the vector "descriptors"
* below. That's defined later because the appropriate get and set
* functions aren't visible yet.
*/
struct arraydescr {
char typecode;
int itemsize;
PyObject * (*getitem)(struct arrayobject *, Py_ssize_t);
int (*setitem)(struct arrayobject *, Py_ssize_t, PyObject *);
const char *formats;
int is_integer_type;
int is_signed;
};
typedef struct arrayobject {
PyObject_VAR_HEAD
char *ob_item;
Py_ssize_t allocated;
const struct arraydescr *ob_descr;
PyObject *weakreflist; /* List of weak references */
int ob_exports; /* Number of exported buffers */
} arrayobject;
static PyTypeObject Arraytype;
typedef struct {
PyObject_HEAD
Py_ssize_t index;
arrayobject *ao;
PyObject* (*getitem)(struct arrayobject *, Py_ssize_t);
} arrayiterobject;
static PyTypeObject PyArrayIter_Type;
#define PyArrayIter_Check(op) PyObject_TypeCheck(op, &PyArrayIter_Type)
enum machine_format_code {
UNKNOWN_FORMAT = -1,
/* UNKNOWN_FORMAT is used to indicate that the machine format for an
* array type code cannot be interpreted. When this occurs, a list of
* Python objects is used to represent the content of the array
* instead of using the memory content of the array directly. In that
* case, the array_reconstructor mechanism is bypassed completely, and
* the standard array constructor is used instead.
*
* This is will most likely occur when the machine doesn't use IEEE
* floating-point numbers.
*/
UNSIGNED_INT8 = 0,
SIGNED_INT8 = 1,
UNSIGNED_INT16_LE = 2,
UNSIGNED_INT16_BE = 3,
SIGNED_INT16_LE = 4,
SIGNED_INT16_BE = 5,
UNSIGNED_INT32_LE = 6,
UNSIGNED_INT32_BE = 7,
SIGNED_INT32_LE = 8,
SIGNED_INT32_BE = 9,
UNSIGNED_INT64_LE = 10,
UNSIGNED_INT64_BE = 11,
SIGNED_INT64_LE = 12,
SIGNED_INT64_BE = 13,
IEEE_754_FLOAT_LE = 14,
IEEE_754_FLOAT_BE = 15,
IEEE_754_DOUBLE_LE = 16,
IEEE_754_DOUBLE_BE = 17,
UTF16_LE = 18,
UTF16_BE = 19,
UTF32_LE = 20,
UTF32_BE = 21
};
#define MACHINE_FORMAT_CODE_MIN 0
#define MACHINE_FORMAT_CODE_MAX 21
/*
* Must come after arrayobject, arrayiterobject,
* and enum machine_code_type definitions.
*/
#include "third_party/python/Modules/clinic/arraymodule.inc"
#define array_Check(op) PyObject_TypeCheck(op, &Arraytype)
#define array_CheckExact(op) (Py_TYPE(op) == &Arraytype)
static int
array_resize(arrayobject *self, Py_ssize_t newsize)
{
char *items;
size_t _new_size;
if (self->ob_exports > 0 && newsize != Py_SIZE(self)) {
PyErr_SetString(PyExc_BufferError,
"cannot resize an array that is exporting buffers");
return -1;
}
/* 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 array.
*/
if (self->allocated >= newsize &&
Py_SIZE(self) < newsize + 16 &&
self->ob_item != NULL) {
Py_SIZE(self) = newsize;
return 0;
}
if (newsize == 0) {
PyMem_FREE(self->ob_item);
self->ob_item = NULL;
Py_SIZE(self) = 0;
self->allocated = 0;
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;
}
/****************************************************************************
Get and Set functions for each type.
A Get function takes an arrayobject* and an integer index, returning the
array value at that index wrapped in an appropriate PyObject*.
A Set function takes an arrayobject, integer index, and PyObject*; sets
the array value at that index to the raw C data extracted from the PyObject*,
and returns 0 if successful, else nonzero on failure (PyObject* not of an
appropriate type or value).
Note that the basic Get and Set functions do NOT check that the index is
in bounds; that's the responsibility of the caller.
****************************************************************************/
static PyObject *
b_getitem(arrayobject *ap, Py_ssize_t i)
{
long x = ((char *)ap->ob_item)[i];
if (x >= 128)
x -= 256;
return PyLong_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;
}
static PyObject *
BB_getitem(arrayobject *ap, Py_ssize_t i)
{
long x = ((unsigned char *)ap->ob_item)[i];
return PyLong_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;
}
static PyObject *
u_getitem(arrayobject *ap, Py_ssize_t i)
{
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;
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;
}
static PyObject *
h_getitem(arrayobject *ap, Py_ssize_t i)
{
return PyLong_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;
}
static PyObject *
HH_getitem(arrayobject *ap, Py_ssize_t i)
{
return PyLong_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;
}
static PyObject *
i_getitem(arrayobject *ap, Py_ssize_t i)
{
return PyLong_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;
}
static PyObject *
II_getitem(arrayobject *ap, Py_ssize_t i)
{
return PyLong_FromUnsignedLong(
(unsigned long) ((unsigned int *)ap->ob_item)[i]);
}
static PyObject *
get_int_unless_float(PyObject *v)
{
if (PyFloat_Check(v)) {
PyErr_SetString(PyExc_TypeError,
"array item must be integer");
return NULL;
}
return (PyObject *)_PyLong_FromNbInt(v);
}
static int
II_setitem(arrayobject *ap, Py_ssize_t i, PyObject *v)
{
unsigned long x;
int do_decref = 0; /* if nb_int was called */
if (!PyLong_Check(v)) {
v = get_int_unless_float(v);
if (NULL == v) {
return -1;
}
do_decref = 1;
}
x = PyLong_AsUnsignedLong(v);
if (x == (unsigned long)-1 && PyErr_Occurred()) {
if (do_decref) {
Py_DECREF(v);
}
return -1;
}
if (x > UINT_MAX) {
PyErr_SetString(PyExc_OverflowError,
"unsigned int is greater than maximum");
if (do_decref) {
Py_DECREF(v);
}
return -1;
}
if (i >= 0)
((unsigned int *)ap->ob_item)[i] = (unsigned int)x;
if (do_decref) {
Py_DECREF(v);
}
return 0;
}
static PyObject *
l_getitem(arrayobject *ap, Py_ssize_t i)
{
return PyLong_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;
}
static PyObject *
LL_getitem(arrayobject *ap, Py_ssize_t 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;
int do_decref = 0; /* if nb_int was called */
if (!PyLong_Check(v)) {
v = get_int_unless_float(v);
if (NULL == v) {
return -1;
}
do_decref = 1;
}
x = PyLong_AsUnsignedLong(v);
if (x == (unsigned long)-1 && PyErr_Occurred()) {
if (do_decref) {
Py_DECREF(v);
}
return -1;
}
if (i >= 0)
((unsigned long *)ap->ob_item)[i] = x;
if (do_decref) {
Py_DECREF(v);
}
return 0;
}
static PyObject *
q_getitem(arrayobject *ap, Py_ssize_t i)
{
return PyLong_FromLongLong(((long long *)ap->ob_item)[i]);
}
static int
q_setitem(arrayobject *ap, Py_ssize_t i, PyObject *v)
{
long long x;
if (!PyArg_Parse(v, "L;array item must be integer", &x))
return -1;
if (i >= 0)
((long long *)ap->ob_item)[i] = x;
return 0;
}
static PyObject *
QQ_getitem(arrayobject *ap, Py_ssize_t i)
{
return PyLong_FromUnsignedLongLong(
((unsigned long long *)ap->ob_item)[i]);
}
static int
QQ_setitem(arrayobject *ap, Py_ssize_t i, PyObject *v)
{
unsigned long long x;
int do_decref = 0; /* if nb_int was called */
if (!PyLong_Check(v)) {
v = get_int_unless_float(v);
if (NULL == v) {
return -1;
}
do_decref = 1;
}
x = PyLong_AsUnsignedLongLong(v);
if (x == (unsigned long long)-1 && PyErr_Occurred()) {
if (do_decref) {
Py_DECREF(v);
}
return -1;
}
if (i >= 0)
((unsigned long long *)ap->ob_item)[i] = x;
if (do_decref) {
Py_DECREF(v);
}
return 0;
}
static PyObject *
f_getitem(arrayobject *ap, Py_ssize_t 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;
}
static PyObject *
d_getitem(arrayobject *ap, Py_ssize_t 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;
}
/* Description of types.
*
* Don't forget to update typecode_to_mformat_code() if you add a new
* typecode.
*/
static const struct arraydescr descriptors[] = {
{'b', 1, b_getitem, b_setitem, "b", 1, 1},
{'B', 1, BB_getitem, BB_setitem, "B", 1, 0},
{'u', sizeof(Py_UNICODE), u_getitem, u_setitem, "u", 0, 0},
{'h', sizeof(short), h_getitem, h_setitem, "h", 1, 1},
{'H', sizeof(short), HH_getitem, HH_setitem, "H", 1, 0},
{'i', sizeof(int), i_getitem, i_setitem, "i", 1, 1},
{'I', sizeof(int), II_getitem, II_setitem, "I", 1, 0},
{'l', sizeof(long), l_getitem, l_setitem, "l", 1, 1},
{'L', sizeof(long), LL_getitem, LL_setitem, "L", 1, 0},
{'q', sizeof(long long), q_getitem, q_setitem, "q", 1, 1},
{'Q', sizeof(long long), QQ_getitem, QQ_setitem, "Q", 1, 0},
{'f', sizeof(float), f_getitem, f_setitem, "f", 0, 0},
{'d', sizeof(double), d_getitem, d_setitem, "d", 0, 0},
{'\0', 0, 0, 0, 0, 0, 0} /* Sentinel */
};
/****************************************************************************
Implementations of array object methods.
****************************************************************************/
/*[clinic input]
class array.array "arrayobject *" "&Arraytype"
[clinic start generated code]*/
/*[clinic end generated code: output=da39a3ee5e6b4b0d input=ad43d37e942a8854]*/
static PyObject *
newarrayobject(PyTypeObject *type, Py_ssize_t size, const struct arraydescr *descr)
{
arrayobject *op;
size_t nbytes;
if (size < 0) {
PyErr_BadInternalCall();
return NULL;
}
/* Check for overflow */
if (size > PY_SSIZE_T_MAX / descr->itemsize) {
return PyErr_NoMemory();
}
nbytes = size * descr->itemsize;
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();
}
}
op->ob_exports = 0;
return (PyObject *) op;
}
static PyObject *
getarrayitem(PyObject *op, Py_ssize_t i)
{
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);
}
/* Methods */
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);
}
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_RETURN_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);
}
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);
}
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;
if (ihigh > ilow) {
memcpy(np->ob_item, a->ob_item + ilow * a->ob_descr->itemsize,
(ihigh-ilow) * a->ob_descr->itemsize);
}
return (PyObject *)np;
}
/*[clinic input]
array.array.__copy__
Return a copy of the array.
[clinic start generated code]*/
static PyObject *
array_array___copy___impl(arrayobject *self)
/*[clinic end generated code: output=dec7c3f925d9619e input=ad1ee5b086965f09]*/
{
return array_slice(self, 0, Py_SIZE(self));
}
/*[clinic input]
array.array.__deepcopy__
unused: object
/
Return a copy of the array.
[clinic start generated code]*/
static PyObject *
array_array___deepcopy__(arrayobject *self, PyObject *unused)
/*[clinic end generated code: output=1ec748d8e14a9faa input=2405ecb4933748c4]*/
{
return array_array___copy___impl(self);
}
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;
}
#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;
}
if (Py_SIZE(a) > 0) {
memcpy(np->ob_item, a->ob_item, Py_SIZE(a)*a->ob_descr->itemsize);
}
if (Py_SIZE(b) > 0) {
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 size;
arrayobject *np;
Py_ssize_t oldbytes, newbytes;
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;
if (size == 0)
return (PyObject *)np;
oldbytes = Py_SIZE(a) * a->ob_descr->itemsize;
newbytes = oldbytes * n;
/* this follows the code in unicode_repeat */
if (oldbytes == 1) {
memset(np->ob_item, a->ob_item[0], newbytes);
} else {
Py_ssize_t done = oldbytes;
memcpy(np->ob_item, a->ob_item, oldbytes);
while (done < newbytes) {
Py_ssize_t ncopy = (done <= newbytes-done) ? done : newbytes-done;
memcpy(np->ob_item+done, np->ob_item, ncopy);
done += ncopy;
}
}
return (PyObject *)np;
}
static int
array_del_slice(arrayobject *a, Py_ssize_t ilow, Py_ssize_t ihigh)
{
char *item;
Py_ssize_t d; /* Change in size */
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 = ihigh-ilow;
/* Issue #4509: If the array has exported buffers and the slice
assignment would change the size of the array, fail early to make
sure we don't modify it. */
if (d != 0 && a->ob_exports > 0) {
PyErr_SetString(PyExc_BufferError,
"cannot resize an array that is exporting buffers");
return -1;
}
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);
if (array_resize(a, Py_SIZE(a) - d) == -1)
return -1;
}
return 0;
}
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_del_slice(a, i, i+1);
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);
}
static int
array_iter_extend(arrayobject *self, PyObject *bb)
{
PyObject *it, *v;
it = PyObject_GetIter(bb);
if (it == NULL)
return -1;
while ((v = PyIter_Next(it)) != NULL) {
if (ins1(self, 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, oldsize, bbsize;
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;
}
oldsize = Py_SIZE(self);
/* Get the size of bb before resizing the array since bb could be self. */
bbsize = Py_SIZE(bb);
size = oldsize + Py_SIZE(b);
if (array_resize(self, size) == -1)
return -1;
if (bbsize > 0) {
memcpy(self->ob_item + oldsize * self->ob_descr->itemsize,
b->ob_item, bbsize * b->ob_descr->itemsize);
}
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;
}
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;
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 && size > PY_SSIZE_T_MAX / n) {
return PyErr_NoMemory();
}
if (array_resize(self, n * Py_SIZE(self)) == -1)
return NULL;
items = p = self->ob_item;
for (i = 1; i < n; i++) {
p += size;
memcpy(p, items, size);
}
}
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;
}
/*[clinic input]
array.array.count
v: object
/
Return number of occurrences of v in the array.
[clinic start generated code]*/
static PyObject *
array_array_count(arrayobject *self, PyObject *v)
/*[clinic end generated code: output=3dd3624bf7135a3a input=d9bce9d65e39d1f5]*/
{
Py_ssize_t count = 0;
Py_ssize_t i;
for (i = 0; i < Py_SIZE(self); i++) {
PyObject *selfi;
int cmp;
selfi = getarrayitem((PyObject *)self, i);
if (selfi == NULL)
return NULL;
cmp = PyObject_RichCompareBool(selfi, v, Py_EQ);
Py_DECREF(selfi);
if (cmp > 0)
count++;
else if (cmp < 0)
return NULL;
}
return PyLong_FromSsize_t(count);
}
/*[clinic input]
array.array.index
v: object
/
Return index of first occurrence of v in the array.
[clinic start generated code]*/
static PyObject *
array_array_index(arrayobject *self, PyObject *v)
/*[clinic end generated code: output=d48498d325602167 input=cf619898c6649d08]*/
{
Py_ssize_t i;
for (i = 0; i < Py_SIZE(self); i++) {
PyObject *selfi;
int cmp;
selfi = getarrayitem((PyObject *)self, i);
if (selfi == NULL)
return NULL;
cmp = PyObject_RichCompareBool(selfi, v, Py_EQ);
Py_DECREF(selfi);
if (cmp > 0) {
return PyLong_FromLong((long)i);
}
else if (cmp < 0)
return NULL;
}
PyErr_SetString(PyExc_ValueError, "array.index(x): x not in list");
return NULL;
}
static int
array_contains(arrayobject *self, PyObject *v)
{
Py_ssize_t i;
int cmp;
for (i = 0, cmp = 0 ; cmp == 0 && i < Py_SIZE(self); i++) {
PyObject *selfi = getarrayitem((PyObject *)self, i);
if (selfi == NULL)
return -1;
cmp = PyObject_RichCompareBool(selfi, v, Py_EQ);
Py_DECREF(selfi);
}
return cmp;
}
/*[clinic input]
array.array.remove
v: object
/
Remove the first occurrence of v in the array.
[clinic start generated code]*/
static PyObject *
array_array_remove(arrayobject *self, PyObject *v)
/*[clinic end generated code: output=bef06be9fdf9dceb input=0b1e5aed25590027]*/
{
int i;
for (i = 0; i < Py_SIZE(self); i++) {
PyObject *selfi;
int cmp;
selfi = getarrayitem((PyObject *)self,i);
if (selfi == NULL)
return NULL;
cmp = PyObject_RichCompareBool(selfi, v, Py_EQ);
Py_DECREF(selfi);
if (cmp > 0) {
if (array_del_slice(self, i, i+1) != 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;
}
/*[clinic input]
array.array.pop
i: Py_ssize_t = -1
/
Return the i-th element and delete it from the array.
i defaults to -1.
[clinic start generated code]*/
static PyObject *
array_array_pop_impl(arrayobject *self, Py_ssize_t i)
/*[clinic end generated code: output=bc1f0c54fe5308e4 input=8e5feb4c1a11cd44]*/
{
PyObject *v;
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 (v == NULL)
return NULL;
if (array_del_slice(self, i, i+1) != 0) {
Py_DECREF(v);
return NULL;
}
return v;
}
/*[clinic input]
array.array.extend
bb: object
/
Append items to the end of the array.
[clinic start generated code]*/
static PyObject *
array_array_extend(arrayobject *self, PyObject *bb)
/*[clinic end generated code: output=bbddbc8e8bef871d input=43be86aba5c31e44]*/
{
if (array_do_extend(self, bb) == -1)
return NULL;
Py_INCREF(Py_None);
return Py_None;
}
/*[clinic input]
array.array.insert
i: Py_ssize_t
v: object
/
Insert a new item v into the array before position i.
[clinic start generated code]*/
static PyObject *
array_array_insert_impl(arrayobject *self, Py_ssize_t i, PyObject *v)
/*[clinic end generated code: output=5a3648e278348564 input=5577d1b4383e9313]*/
{
return ins(self, i, v);
}
/*[clinic input]
array.array.buffer_info
Return a tuple (address, length) giving the current memory address and the length in items of the buffer used to hold array's contents.
The length should be multiplied by the itemsize attribute to calculate
the buffer length in bytes.
[clinic start generated code]*/
static PyObject *
array_array_buffer_info_impl(arrayobject *self)
/*[clinic end generated code: output=9b2a4ec3ae7e98e7 input=a58bae5c6e1ac6a6]*/
{
PyObject *retval = NULL, *v;
retval = PyTuple_New(2);
if (!retval)
return NULL;
v = PyLong_FromVoidPtr(self->ob_item);
if (v == NULL) {
Py_DECREF(retval);
return NULL;
}
PyTuple_SET_ITEM(retval, 0, v);
v = PyLong_FromSsize_t(Py_SIZE(self));
if (v == NULL) {
Py_DECREF(retval);
return NULL;
}
PyTuple_SET_ITEM(retval, 1, v);
return retval;
}
/*[clinic input]
array.array.append
v: object
/
Append new value v to the end of the array.
[clinic start generated code]*/
static PyObject *
array_array_append(arrayobject *self, PyObject *v)
/*[clinic end generated code: output=745a0669bf8db0e2 input=0b98d9d78e78f0fa]*/
{
return ins(self, Py_SIZE(self), v);
}
/*[clinic input]
array.array.byteswap
Byteswap all items of the array.
If the items in the array are not 1, 2, 4, or 8 bytes in size, RuntimeError is
raised.
[clinic start generated code]*/
static PyObject *
array_array_byteswap_impl(arrayobject *self)
/*[clinic end generated code: output=5f8236cbdf0d90b5 input=6a85591b950a0186]*/
{
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;
}
/*[clinic input]
array.array.reverse
Reverse the order of the items in the array.
[clinic start generated code]*/
static PyObject *
array_array_reverse_impl(arrayobject *self)
/*[clinic end generated code: output=c04868b36f6f4089 input=cd904f01b27d966a]*/
{
Py_ssize_t itemsize = self->ob_descr->itemsize;
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;
}
/*[clinic input]
array.array.fromfile
f: object
n: Py_ssize_t
/
Read n objects from the file object f and append them to the end of the array.
[clinic start generated code]*/
static PyObject *
array_array_fromfile_impl(arrayobject *self, PyObject *f, Py_ssize_t n)
/*[clinic end generated code: output=ec9f600e10f53510 input=e188afe8e58adf40]*/
{
PyObject *b, *res;
Py_ssize_t itemsize = self->ob_descr->itemsize;
Py_ssize_t nbytes;
_Py_IDENTIFIER(read);
int not_enough_bytes;
if (n < 0) {
PyErr_SetString(PyExc_ValueError, "negative count");
return NULL;
}
if (n > PY_SSIZE_T_MAX / itemsize) {
PyErr_NoMemory();
return NULL;
}
nbytes = n * itemsize;
b = _PyObject_CallMethodId(f, &PyId_read, "n", nbytes);
if (b == NULL)
return NULL;
if (!PyBytes_Check(b)) {
PyErr_SetString(PyExc_TypeError,
"read() didn't return bytes");
Py_DECREF(b);
return NULL;
}
not_enough_bytes = (PyBytes_GET_SIZE(b) != nbytes);
res = array_array_frombytes(self, b);
Py_DECREF(b);
if (res == NULL)
return NULL;
if (not_enough_bytes) {
PyErr_SetString(PyExc_EOFError,
"read() didn't return enough bytes");
Py_DECREF(res);
return NULL;
}
return res;
}
/*[clinic input]
array.array.tofile
f: object
/
Write all items (as machine values) to the file object f.
[clinic start generated code]*/
static PyObject *
array_array_tofile(arrayobject *self, PyObject *f)
/*[clinic end generated code: output=3a2cfa8128df0777 input=b0669a484aab0831]*/
{
Py_ssize_t nbytes = Py_SIZE(self) * self->ob_descr->itemsize;
/* Write 64K blocks at a time */
/* XXX Make the block size settable */
int BLOCKSIZE = 64*1024;
Py_ssize_t nblocks = (nbytes + BLOCKSIZE - 1) / BLOCKSIZE;
Py_ssize_t i;
if (Py_SIZE(self) == 0)
goto done;
for (i = 0; i < nblocks; i++) {
char* ptr = self->ob_item + i*BLOCKSIZE;
Py_ssize_t size = BLOCKSIZE;
PyObject *bytes, *res;
_Py_IDENTIFIER(write);
if (i*BLOCKSIZE + size > nbytes)
size = nbytes - i*BLOCKSIZE;
bytes = PyBytes_FromStringAndSize(ptr, size);
if (bytes == NULL)
return NULL;
res = _PyObject_CallMethodId(f, &PyId_write, "O", bytes);
Py_DECREF(bytes);
if (res == NULL)
return NULL;
Py_DECREF(res); /* drop write result */
}
done:
Py_INCREF(Py_None);
return Py_None;
}
/*[clinic input]
array.array.fromlist
list: object
/
Append items to array from list.
[clinic start generated code]*/
static PyObject *
array_array_fromlist(arrayobject *self, PyObject *list)
/*[clinic end generated code: output=26411c2d228a3e3f input=be2605a96c49680f]*/
{
Py_ssize_t n;
if (!PyList_Check(list)) {
PyErr_SetString(PyExc_TypeError, "arg must be list");
return NULL;
}
n = PyList_Size(list);
if (n > 0) {
Py_ssize_t i, old_size;
old_size = Py_SIZE(self);
if (array_resize(self, old_size + n) == -1)
return NULL;
for (i = 0; i < n; i++) {
PyObject *v = PyList_GET_ITEM(list, i);
if ((*self->ob_descr->setitem)(self,
Py_SIZE(self) - n + i, v) != 0) {
array_resize(self, old_size);
return NULL;
}
if (n != PyList_GET_SIZE(list)) {
PyErr_SetString(PyExc_RuntimeError,
"list changed size during iteration");
array_resize(self, old_size);
return NULL;
}
}
}
Py_INCREF(Py_None);
return Py_None;
}
/*[clinic input]
array.array.tolist
Convert array to an ordinary list with the same items.
[clinic start generated code]*/
static PyObject *
array_array_tolist_impl(arrayobject *self)
/*[clinic end generated code: output=00b60cc9eab8ef89 input=a8d7784a94f86b53]*/
{
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)
goto error;
PyList_SET_ITEM(list, i, v);
}
return list;
error:
Py_DECREF(list);
return NULL;
}
static PyObject *
frombytes(arrayobject *self, Py_buffer *buffer)
{
int itemsize = self->ob_descr->itemsize;
Py_ssize_t n;
if (buffer->itemsize != 1) {
PyBuffer_Release(buffer);
PyErr_SetString(PyExc_TypeError, "a bytes-like object is required");
return NULL;
}
n = buffer->len;
if (n % itemsize != 0) {
PyBuffer_Release(buffer);
PyErr_SetString(PyExc_ValueError,
"bytes length not a multiple of item size");
return NULL;
}
n = n / itemsize;
if (n > 0) {
Py_ssize_t old_size = Py_SIZE(self);
if ((n > PY_SSIZE_T_MAX - old_size) ||
((old_size + n) > PY_SSIZE_T_MAX / itemsize)) {
PyBuffer_Release(buffer);
return PyErr_NoMemory();
}
if (array_resize(self, old_size + n) == -1) {
PyBuffer_Release(buffer);
return NULL;
}
memcpy(self->ob_item + old_size * itemsize,
buffer->buf, n * itemsize);
}
PyBuffer_Release(buffer);
Py_INCREF(Py_None);
return Py_None;
}
/*[clinic input]
array.array.fromstring
buffer: Py_buffer(accept={str, buffer})
/
Appends items from the string, interpreting it as an array of machine values, as if it had been read from a file using the fromfile() method).
This method is deprecated. Use frombytes instead.
[clinic start generated code]*/
static PyObject *
array_array_fromstring_impl(arrayobject *self, Py_buffer *buffer)
/*[clinic end generated code: output=31c4baa779df84ce input=a3341a512e11d773]*/
{
if (PyErr_WarnEx(PyExc_DeprecationWarning,
"fromstring() is deprecated. Use frombytes() instead.", 2) != 0)
return NULL;
return frombytes(self, buffer);
}
/*[clinic input]
array.array.frombytes
buffer: Py_buffer
/
Appends items from the string, interpreting it as an array of machine values, as if it had been read from a file using the fromfile() method).
[clinic start generated code]*/
static PyObject *
array_array_frombytes_impl(arrayobject *self, Py_buffer *buffer)
/*[clinic end generated code: output=d9842c8f7510a516 input=2bbf2b53ebfcc988]*/
{
return frombytes(self, buffer);
}
/*[clinic input]
array.array.tobytes
Convert the array to an array of machine values and return the bytes representation.
[clinic start generated code]*/
static PyObject *
array_array_tobytes_impl(arrayobject *self)
/*[clinic end generated code: output=87318e4edcdc2bb6 input=90ee495f96de34f5]*/
{
if (Py_SIZE(self) <= PY_SSIZE_T_MAX / self->ob_descr->itemsize) {
return PyBytes_FromStringAndSize(self->ob_item,
Py_SIZE(self) * self->ob_descr->itemsize);
} else {
return PyErr_NoMemory();
}
}
/*[clinic input]
array.array.tostring
Convert the array to an array of machine values and return the bytes representation.
This method is deprecated. Use tobytes instead.
[clinic start generated code]*/
static PyObject *
array_array_tostring_impl(arrayobject *self)
/*[clinic end generated code: output=7d6bd92745a2c8f3 input=b6c0ddee7b30457e]*/
{
if (PyErr_WarnEx(PyExc_DeprecationWarning,
"tostring() is deprecated. Use tobytes() instead.", 2) != 0)
return NULL;
return array_array_tobytes_impl(self);
}
/*[clinic input]
array.array.fromunicode
ustr: Py_UNICODE(zeroes=True)
/
Extends this array with data from the unicode string ustr.
The array must be a unicode type array; otherwise a ValueError is raised.
Use array.frombytes(ustr.encode(...)) to append Unicode data to an array of
some other type.
[clinic start generated code]*/
static PyObject *
array_array_fromunicode_impl(arrayobject *self, Py_UNICODE *ustr,
Py_ssize_clean_t ustr_length)
/*[clinic end generated code: output=ebb72fc16975e06d input=150f00566ffbca6e]*/
{
char typecode;
typecode = self->ob_descr->typecode;
if (typecode != 'u') {
PyErr_SetString(PyExc_ValueError,
"fromunicode() may only be called on "
"unicode type arrays");
return NULL;
}
if (ustr_length > 0) {
Py_ssize_t old_size = Py_SIZE(self);
if (array_resize(self, old_size + ustr_length) == -1)
return NULL;
memcpy(self->ob_item + old_size * sizeof(Py_UNICODE),
ustr, ustr_length * sizeof(Py_UNICODE));
}
Py_RETURN_NONE;
}
/*[clinic input]
array.array.tounicode
Extends this array with data from the unicode string ustr.
Convert the array to a unicode string. The array must be a unicode type array;
otherwise a ValueError is raised. Use array.tobytes().decode() to obtain a
unicode string from an array of some other type.
[clinic start generated code]*/
static PyObject *
array_array_tounicode_impl(arrayobject *self)
/*[clinic end generated code: output=08e442378336e1ef input=127242eebe70b66d]*/
{
char typecode;
typecode = self->ob_descr->typecode;
if (typecode != 'u') {
PyErr_SetString(PyExc_ValueError,
"tounicode() may only be called on unicode type arrays");
return NULL;
}
return PyUnicode_FromUnicode((Py_UNICODE *) self->ob_item, Py_SIZE(self));
}
/*[clinic input]
array.array.__sizeof__
Size of the array in memory, in bytes.
[clinic start generated code]*/
static PyObject *
array_array___sizeof___impl(arrayobject *self)
/*[clinic end generated code: output=d8e1c61ebbe3eaed input=805586565bf2b3c6]*/
{
Py_ssize_t res;
res = _PyObject_SIZE(Py_TYPE(self)) + self->allocated * self->ob_descr->itemsize;
return PyLong_FromSsize_t(res);
}
/*********************** Pickling support ************************/
static const struct mformatdescr {
size_t size;
int is_signed;
int is_big_endian;
} mformat_descriptors[] = {
{1, 0, 0}, /* 0: UNSIGNED_INT8 */
{1, 1, 0}, /* 1: SIGNED_INT8 */
{2, 0, 0}, /* 2: UNSIGNED_INT16_LE */
{2, 0, 1}, /* 3: UNSIGNED_INT16_BE */
{2, 1, 0}, /* 4: SIGNED_INT16_LE */
{2, 1, 1}, /* 5: SIGNED_INT16_BE */
{4, 0, 0}, /* 6: UNSIGNED_INT32_LE */
{4, 0, 1}, /* 7: UNSIGNED_INT32_BE */
{4, 1, 0}, /* 8: SIGNED_INT32_LE */
{4, 1, 1}, /* 9: SIGNED_INT32_BE */
{8, 0, 0}, /* 10: UNSIGNED_INT64_LE */
{8, 0, 1}, /* 11: UNSIGNED_INT64_BE */
{8, 1, 0}, /* 12: SIGNED_INT64_LE */
{8, 1, 1}, /* 13: SIGNED_INT64_BE */
{4, 0, 0}, /* 14: IEEE_754_FLOAT_LE */
{4, 0, 1}, /* 15: IEEE_754_FLOAT_BE */
{8, 0, 0}, /* 16: IEEE_754_DOUBLE_LE */
{8, 0, 1}, /* 17: IEEE_754_DOUBLE_BE */
{4, 0, 0}, /* 18: UTF16_LE */
{4, 0, 1}, /* 19: UTF16_BE */
{8, 0, 0}, /* 20: UTF32_LE */
{8, 0, 1} /* 21: UTF32_BE */
};
/*
* Internal: This function is used to find the machine format of a given
* array type code. This returns UNKNOWN_FORMAT when the machine format cannot
* be found.
*/
static enum machine_format_code
typecode_to_mformat_code(char typecode)
{
const int is_big_endian = PY_BIG_ENDIAN;
size_t intsize;
int is_signed;
switch (typecode) {
case 'b':
return SIGNED_INT8;
case 'B':
return UNSIGNED_INT8;
case 'u':
if (sizeof(Py_UNICODE) == 2) {
return UTF16_LE + is_big_endian;
}
if (sizeof(Py_UNICODE) == 4) {
return UTF32_LE + is_big_endian;
}
return UNKNOWN_FORMAT;
case 'f':
if (sizeof(float) == 4) {
const float y = 16711938.0;
if (!bcmp(&y, "\x4b\x7f\x01\x02", 4))
return IEEE_754_FLOAT_BE;
if (!bcmp(&y, "\x02\x01\x7f\x4b", 4))
return IEEE_754_FLOAT_LE;
}
return UNKNOWN_FORMAT;
case 'd':
if (sizeof(double) == 8) {
const double x = 9006104071832581.0;
if (!bcmp(&x, "\x43\x3f\xff\x01\x02\x03\x04\x05", 8))
return IEEE_754_DOUBLE_BE;
if (!bcmp(&x, "\x05\x04\x03\x02\x01\xff\x3f\x43", 8))
return IEEE_754_DOUBLE_LE;
}
return UNKNOWN_FORMAT;
/* Integers */
case 'h':
intsize = sizeof(short);
is_signed = 1;
break;
case 'H':
intsize = sizeof(short);
is_signed = 0;
break;
case 'i':
intsize = sizeof(int);
is_signed = 1;
break;
case 'I':
intsize = sizeof(int);
is_signed = 0;
break;
case 'l':
intsize = sizeof(long);
is_signed = 1;
break;
case 'L':
intsize = sizeof(long);
is_signed = 0;
break;
case 'q':
intsize = sizeof(long long);
is_signed = 1;
break;
case 'Q':
intsize = sizeof(long long);
is_signed = 0;
break;
default:
return UNKNOWN_FORMAT;
}
switch (intsize) {
case 2:
return UNSIGNED_INT16_LE + is_big_endian + (2 * is_signed);
case 4:
return UNSIGNED_INT32_LE + is_big_endian + (2 * is_signed);
case 8:
return UNSIGNED_INT64_LE + is_big_endian + (2 * is_signed);
default:
return UNKNOWN_FORMAT;
}
}
/* Forward declaration. */
static PyObject *array_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
/*
* Internal: This function wraps the array constructor--i.e., array_new()--to
* allow the creation of array objects from C code without having to deal
* directly the tuple argument of array_new(). The typecode argument is a
* Unicode character value, like 'i' or 'f' for example, representing an array
* type code. The items argument is a bytes or a list object from which
* contains the initial value of the array.
*
* On success, this functions returns the array object created. Otherwise,
* NULL is returned to indicate a failure.
*/
static PyObject *
make_array(PyTypeObject *arraytype, char typecode, PyObject *items)
{
PyObject *new_args;
PyObject *array_obj;
PyObject *typecode_obj;
assert(arraytype != NULL);
assert(items != NULL);
typecode_obj = PyUnicode_FromOrdinal(typecode);
if (typecode_obj == NULL)
return NULL;
new_args = PyTuple_New(2);
if (new_args == NULL) {
Py_DECREF(typecode_obj);
return NULL;
}
Py_INCREF(items);
PyTuple_SET_ITEM(new_args, 0, typecode_obj);
PyTuple_SET_ITEM(new_args, 1, items);
array_obj = array_new(arraytype, new_args, NULL);
Py_DECREF(new_args);
if (array_obj == NULL)
return NULL;
return array_obj;
}
/*
* This functions is a special constructor used when unpickling an array. It
* provides a portable way to rebuild an array from its memory representation.
*/
/*[clinic input]
array._array_reconstructor
arraytype: object(type="PyTypeObject *")
typecode: int(accept={str})
mformat_code: int(type="enum machine_format_code")
items: object
/
Internal. Used for pickling support.
[clinic start generated code]*/
static PyObject *
array__array_reconstructor_impl(PyObject *module, PyTypeObject *arraytype,
int typecode,
enum machine_format_code mformat_code,
PyObject *items)
/*[clinic end generated code: output=e05263141ba28365 input=2464dc8f4c7736b5]*/
{
PyObject *converted_items;
PyObject *result;
const struct arraydescr *descr;
if (!PyType_Check(arraytype)) {
PyErr_Format(PyExc_TypeError,
"first argument must a type object, not %.200s",
Py_TYPE(arraytype)->tp_name);
return NULL;
}
if (!PyType_IsSubtype(arraytype, &Arraytype)) {
PyErr_Format(PyExc_TypeError,
"%.200s is not a subtype of %.200s",
arraytype->tp_name, Arraytype.tp_name);
return NULL;
}
for (descr = descriptors; descr->typecode != '\0'; descr++) {
if ((int)descr->typecode == typecode)
break;
}
if (descr->typecode == '\0') {
PyErr_SetString(PyExc_ValueError,
"second argument must be a valid type code");
return NULL;
}
if (mformat_code < MACHINE_FORMAT_CODE_MIN ||
mformat_code > MACHINE_FORMAT_CODE_MAX) {
PyErr_SetString(PyExc_ValueError,
"third argument must be a valid machine format code.");
return NULL;
}
if (!PyBytes_Check(items)) {
PyErr_Format(PyExc_TypeError,
"fourth argument should be bytes, not %.200s",
Py_TYPE(items)->tp_name);
return NULL;
}
/* Fast path: No decoding has to be done. */
if (mformat_code == typecode_to_mformat_code((char)typecode) ||
mformat_code == UNKNOWN_FORMAT) {
return make_array(arraytype, (char)typecode, items);
}
/* Slow path: Decode the byte string according to the given machine
* format code. This occurs when the computer unpickling the array
* object is architecturally different from the one that pickled the
* array.
*/
if (Py_SIZE(items) % mformat_descriptors[mformat_code].size != 0) {
PyErr_SetString(PyExc_ValueError,
"string length not a multiple of item size");
return NULL;
}
switch (mformat_code) {
case IEEE_754_FLOAT_LE:
case IEEE_754_FLOAT_BE: {
int i;
int le = (mformat_code == IEEE_754_FLOAT_LE) ? 1 : 0;
Py_ssize_t itemcount = Py_SIZE(items) / 4;
const unsigned char *memstr =
(unsigned char *)PyBytes_AS_STRING(items);
converted_items = PyList_New(itemcount);
if (converted_items == NULL)
return NULL;
for (i = 0; i < itemcount; i++) {
PyObject *pyfloat = PyFloat_FromDouble(
_PyFloat_Unpack4(&memstr[i * 4], le));
if (pyfloat == NULL) {
Py_DECREF(converted_items);
return NULL;
}
PyList_SET_ITEM(converted_items, i, pyfloat);
}
break;
}
case IEEE_754_DOUBLE_LE:
case IEEE_754_DOUBLE_BE: {
int i;
int le = (mformat_code == IEEE_754_DOUBLE_LE) ? 1 : 0;
Py_ssize_t itemcount = Py_SIZE(items) / 8;
const unsigned char *memstr =
(unsigned char *)PyBytes_AS_STRING(items);
converted_items = PyList_New(itemcount);
if (converted_items == NULL)
return NULL;
for (i = 0; i < itemcount; i++) {
PyObject *pyfloat = PyFloat_FromDouble(
_PyFloat_Unpack8(&memstr[i * 8], le));
if (pyfloat == NULL) {
Py_DECREF(converted_items);
return NULL;
}
PyList_SET_ITEM(converted_items, i, pyfloat);
}
break;
}
case UTF16_LE:
case UTF16_BE: {
int byteorder = (mformat_code == UTF16_LE) ? -1 : 1;
converted_items = PyUnicode_DecodeUTF16(
PyBytes_AS_STRING(items), Py_SIZE(items),
"strict", &byteorder);
if (converted_items == NULL)
return NULL;
break;
}
case UTF32_LE:
case UTF32_BE: {
int byteorder = (mformat_code == UTF32_LE) ? -1 : 1;
converted_items = PyUnicode_DecodeUTF32(
PyBytes_AS_STRING(items), Py_SIZE(items),
"strict", &byteorder);
if (converted_items == NULL)
return NULL;
break;
}
case UNSIGNED_INT8:
case SIGNED_INT8:
case UNSIGNED_INT16_LE:
case UNSIGNED_INT16_BE:
case SIGNED_INT16_LE:
case SIGNED_INT16_BE:
case UNSIGNED_INT32_LE:
case UNSIGNED_INT32_BE:
case SIGNED_INT32_LE:
case SIGNED_INT32_BE:
case UNSIGNED_INT64_LE:
case UNSIGNED_INT64_BE:
case SIGNED_INT64_LE:
case SIGNED_INT64_BE: {
int i;
const struct mformatdescr mf_descr =
mformat_descriptors[mformat_code];
Py_ssize_t itemcount = Py_SIZE(items) / mf_descr.size;
const unsigned char *memstr =
(unsigned char *)PyBytes_AS_STRING(items);
const struct arraydescr *descr;
/* If possible, try to pack array's items using a data type
* that fits better. This may result in an array with narrower
* or wider elements.
*
* For example, if a 32-bit machine pickles an L-code array of
* unsigned longs, then the array will be unpickled by 64-bit
* machine as an I-code array of unsigned ints.
*
* XXX: Is it possible to write a unit test for this?
*/
for (descr = descriptors; descr->typecode != '\0'; descr++) {
if (descr->is_integer_type &&
(size_t)descr->itemsize == mf_descr.size &&
descr->is_signed == mf_descr.is_signed)
typecode = descr->typecode;
}
converted_items = PyList_New(itemcount);
if (converted_items == NULL)
return NULL;
for (i = 0; i < itemcount; i++) {
PyObject *pylong;
pylong = _PyLong_FromByteArray(
&memstr[i * mf_descr.size],
mf_descr.size,
!mf_descr.is_big_endian,
mf_descr.is_signed);
if (pylong == NULL) {
Py_DECREF(converted_items);
return NULL;
}
PyList_SET_ITEM(converted_items, i, pylong);
}
break;
}
case UNKNOWN_FORMAT:
/* Impossible, but needed to shut up GCC about the unhandled
* enumeration value.
*/
default:
PyErr_BadArgument();
return NULL;
}
result = make_array(arraytype, (char)typecode, converted_items);
Py_DECREF(converted_items);
return result;
}
/*[clinic input]
array.array.__reduce_ex__
value: object
/
Return state information for pickling.
[clinic start generated code]*/
static PyObject *
array_array___reduce_ex__(arrayobject *self, PyObject *value)
/*[clinic end generated code: output=051e0a6175d0eddb input=c36c3f85de7df6cd]*/
{
PyObject *dict;
PyObject *result;
PyObject *array_str;
int typecode = self->ob_descr->typecode;
int mformat_code;
static PyObject *array_reconstructor = NULL;
long protocol;
_Py_IDENTIFIER(_array_reconstructor);
_Py_IDENTIFIER(__dict__);
if (array_reconstructor == NULL) {
PyObject *array_module = PyImport_ImportModule("array");
if (array_module == NULL)
return NULL;
array_reconstructor = _PyObject_GetAttrId(
array_module,
&PyId__array_reconstructor);
Py_DECREF(array_module);
if (array_reconstructor == NULL)
return NULL;
}
if (!PyLong_Check(value)) {
PyErr_SetString(PyExc_TypeError,
"__reduce_ex__ argument should an integer");
return NULL;
}
protocol = PyLong_AsLong(value);
if (protocol == -1 && PyErr_Occurred())
return NULL;
dict = _PyObject_GetAttrId((PyObject *)self, &PyId___dict__);
if (dict == NULL) {
if (!PyErr_ExceptionMatches(PyExc_AttributeError))
return NULL;
PyErr_Clear();
dict = Py_None;
Py_INCREF(dict);
}
mformat_code = typecode_to_mformat_code(typecode);
if (mformat_code == UNKNOWN_FORMAT || protocol < 3) {
/* Convert the array to a list if we got something weird
* (e.g., non-IEEE floats), or we are pickling the array using
* a Python 2.x compatible protocol.
*
* It is necessary to use a list representation for Python 2.x
* compatible pickle protocol, since Python 2's str objects
* are unpickled as unicode by Python 3. Thus it is impossible
* to make arrays unpicklable by Python 3 by using their memory
* representation, unless we resort to ugly hacks such as
* coercing unicode objects to bytes in array_reconstructor.
*/
PyObject *list;
list = array_array_tolist_impl(self);
if (list == NULL) {
Py_DECREF(dict);
return NULL;
}
result = Py_BuildValue(
"O(CO)O", Py_TYPE(self), typecode, list, dict);
Py_DECREF(list);
Py_DECREF(dict);
return result;
}
array_str = array_array_tobytes_impl(self);
if (array_str == NULL) {
Py_DECREF(dict);
return NULL;
}
result = Py_BuildValue(
"O(OCiN)O", array_reconstructor, Py_TYPE(self), typecode,
mformat_code, array_str, dict);
Py_DECREF(dict);
return result;
}
static PyObject *
array_get_typecode(arrayobject *a, void *closure)
{
char typecode = a->ob_descr->typecode;
return PyUnicode_FromOrdinal(typecode);
}
static PyObject *
array_get_itemsize(arrayobject *a, void *closure)
{
return PyLong_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}
};
static PyMethodDef array_methods[] = {
ARRAY_ARRAY_APPEND_METHODDEF
ARRAY_ARRAY_BUFFER_INFO_METHODDEF
ARRAY_ARRAY_BYTESWAP_METHODDEF
ARRAY_ARRAY___COPY___METHODDEF
ARRAY_ARRAY_COUNT_METHODDEF
ARRAY_ARRAY___DEEPCOPY___METHODDEF
ARRAY_ARRAY_EXTEND_METHODDEF
ARRAY_ARRAY_FROMFILE_METHODDEF
ARRAY_ARRAY_FROMLIST_METHODDEF
ARRAY_ARRAY_FROMSTRING_METHODDEF
ARRAY_ARRAY_FROMBYTES_METHODDEF
ARRAY_ARRAY_FROMUNICODE_METHODDEF
ARRAY_ARRAY_INDEX_METHODDEF
ARRAY_ARRAY_INSERT_METHODDEF
ARRAY_ARRAY_POP_METHODDEF
ARRAY_ARRAY___REDUCE_EX___METHODDEF
ARRAY_ARRAY_REMOVE_METHODDEF
ARRAY_ARRAY_REVERSE_METHODDEF
ARRAY_ARRAY_TOFILE_METHODDEF
ARRAY_ARRAY_TOLIST_METHODDEF
ARRAY_ARRAY_TOSTRING_METHODDEF
ARRAY_ARRAY_TOBYTES_METHODDEF
ARRAY_ARRAY_TOUNICODE_METHODDEF
ARRAY_ARRAY___SIZEOF___METHODDEF
{NULL, NULL} /* sentinel */
};
static PyObject *
array_repr(arrayobject *a)
{
char typecode;
PyObject *s, *v = NULL;
Py_ssize_t len;
len = Py_SIZE(a);
typecode = a->ob_descr->typecode;
if (len == 0) {
return PyUnicode_FromFormat("array('%c')", (int)typecode);
}
if (typecode == 'u') {
v = array_array_tounicode_impl(a);
} else {
v = array_array_tolist_impl(a);
}
if (v == NULL)
return NULL;
s = PyUnicode_FromFormat("array('%c', %R)", (int)typecode, v);
Py_DECREF(v);
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_Unpack(item, &start, &stop, &step) < 0) {
return NULL;
}
slicelength = PySlice_AdjustIndices(Py_SIZE(self), &start, &stop,
step);
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_Unpack(item, &start, &stop, &step) < 0) {
return -1;
}
slicelength = PySlice_AdjustIndices(Py_SIZE(self), &start, &stop,
step);
}
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;
/* Issue #4509: If the array has exported buffers and the slice
assignment would change the size of the array, fail early to make
sure we don't modify it. */
if ((needed == 0 || slicelength != needed) && self->ob_exports > 0) {
PyErr_SetString(PyExc_BufferError,
"cannot resize an array that is exporting buffers");
return -1;
}
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 + (size_t)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
};
static const void *emptybuf = "";
static int
array_buffer_getbuf(arrayobject *self, Py_buffer *view, int flags)
{
if (view == NULL) {
PyErr_SetString(PyExc_BufferError,
"array_buffer_getbuf: view==NULL argument is obsolete");
return -1;
}
view->buf = (void *)self->ob_item;
view->obj = (PyObject*)self;
Py_INCREF(self);
if (view->buf == NULL)
view->buf = (void *)emptybuf;
view->len = (Py_SIZE(self)) * self->ob_descr->itemsize;
view->readonly = 0;
view->ndim = 1;
view->itemsize = self->ob_descr->itemsize;
view->suboffsets = NULL;
view->shape = NULL;
if ((flags & PyBUF_ND)==PyBUF_ND) {
view->shape = &((Py_SIZE(self)));
}
view->strides = NULL;
if ((flags & PyBUF_STRIDES)==PyBUF_STRIDES)
view->strides = &(view->itemsize);
view->format = NULL;
view->internal = NULL;
if ((flags & PyBUF_FORMAT) == PyBUF_FORMAT) {
view->format = (char *)self->ob_descr->formats;
#ifdef Py_UNICODE_WIDE
if (self->ob_descr->typecode == 'u') {
view->format = "w";
}
#endif
}
self->ob_exports++;
return 0;
}
static void
array_buffer_relbuf(arrayobject *self, Py_buffer *view)
{
self->ob_exports--;
}
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*/
0, /*sq_slice*/
(ssizeobjargproc)array_ass_item, /*sq_ass_item*/
0, /*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 = {
(getbufferproc)array_buffer_getbuf,
(releasebufferproc)array_buffer_relbuf
};
static PyObject *
array_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
int c;
PyObject *initial = NULL, *it = NULL;
const 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 && c != 'u') {
if (PyUnicode_Check(initial)) {
PyErr_Format(PyExc_TypeError, "cannot use a str to initialize "
"an array with typecode '%c'", c);
return NULL;
}
else if (array_Check(initial) &&
((arrayobject*)initial)->ob_descr->typecode == 'u') {
PyErr_Format(PyExc_TypeError, "cannot use a unicode array to "
"initialize an array with typecode '%c'", c);
return NULL;
}
}
if (!(initial == NULL || PyList_Check(initial)
|| PyByteArray_Check(initial)
|| PyBytes_Check(initial)
|| PyTuple_Check(initial)
|| ((c=='u') && PyUnicode_Check(initial))
|| (array_Check(initial)
&& c == ((arrayobject*)initial)->ob_descr->typecode))) {
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)
len = 0;
else if (PyList_Check(initial))
len = PyList_GET_SIZE(initial);
else if (PyTuple_Check(initial) || array_Check(initial))
len = Py_SIZE(initial);
else
len = 0;
a = newarrayobject(type, len, descr);
if (a == NULL)
return NULL;
if (len > 0 && !array_Check(initial)) {
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 && (PyByteArray_Check(initial) ||
PyBytes_Check(initial))) {
PyObject *v;
v = array_array_frombytes((arrayobject *)a,
initial);
if (v == NULL) {
Py_DECREF(a);
return NULL;
}
Py_DECREF(v);
}
else if (initial != NULL && PyUnicode_Check(initial)) {
Py_UNICODE *ustr;
Py_ssize_t n;
ustr = PyUnicode_AsUnicode(initial);
if (ustr == NULL) {
PyErr_NoMemory();
Py_DECREF(a);
return NULL;
}
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, ustr, n);
self->allocated = Py_SIZE(self);
}
}
else if (initial != NULL && array_Check(initial) && len > 0) {
arrayobject *self = (arrayobject *)a;
arrayobject *other = (arrayobject *)initial;
memcpy(self->ob_item, other->ob_item, len * other->ob_descr->itemsize);
}
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 b, B, u, h, H, i, I, l, L, q, Q, f or d)");
return NULL;
}
PyDoc_STRVAR(module_doc,
"This module defines an object type which can efficiently represent\n\
an array of basic values: characters, integers, floating point\n\
numbers. Arrays are sequence types and behave very much like lists,\n\
except that the type of objects stored in them is constrained.\n");
PyDoc_STRVAR(arraytype_doc,
"array(typecode [, initializer]) -> array\n\
\n\
Return a new array whose items are restricted by typecode, and\n\
initialized from the optional initializer value, which must be a list,\n\
string or iterable over elements of the appropriate type.\n\
\n\
Arrays represent basic values and behave very much like lists, except\n\
the type of objects stored in them is constrained. The type is specified\n\
at object creation time by using a type code, which is a single character.\n\
The following type codes are defined:\n\
\n\
Type code C Type Minimum size in bytes \n\
'b' signed integer 1 \n\
'B' unsigned integer 1 \n\
'u' Unicode character 2 (see note) \n\
'h' signed integer 2 \n\
'H' unsigned integer 2 \n\
'i' signed integer 2 \n\
'I' unsigned integer 2 \n\
'l' signed integer 4 \n\
'L' unsigned integer 4 \n\
'q' signed integer 8 (see note) \n\
'Q' unsigned integer 8 (see note) \n\
'f' floating point 4 \n\
'd' floating point 8 \n\
\n\
NOTE: The 'u' typecode corresponds to Python's unicode character. On \n\
narrow builds this is 2-bytes on wide builds this is 4-bytes.\n\
\n\
NOTE: The 'q' and 'Q' type codes are only available if the platform \n\
C compiler used to build Python supports 'long long', or, on Windows, \n\
'__int64'.\n\
\n\
Methods:\n\
\n\
append() -- append a new item to the end of the array\n\
buffer_info() -- return information giving the current memory info\n\
byteswap() -- byteswap all the items of the array\n\
count() -- return number of occurrences of an object\n\
extend() -- extend array by appending multiple elements from an iterable\n\
fromfile() -- read items from a file object\n\
fromlist() -- append items from the list\n\
frombytes() -- append items from the string\n\
index() -- return index of first occurrence of an object\n\
insert() -- insert a new item into the array at a provided position\n\
pop() -- remove and return item (default last)\n\
remove() -- remove first occurrence of an object\n\
reverse() -- reverse the order of the items in the array\n\
tofile() -- write all items to a file object\n\
tolist() -- return the array converted to an ordinary list\n\
tobytes() -- return the array converted to a string\n\
\n\
Attributes:\n\
\n\
typecode -- the typecode character used to create the array\n\
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_reserved */
(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, /* 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 **************************/
/*[clinic input]
class array.arrayiterator "arrayiterobject *" "&PyArrayIter_Type"
[clinic start generated code]*/
/*[clinic end generated code: output=da39a3ee5e6b4b0d input=5aefd2d74d8c8e30]*/
static PyObject *
array_iter(arrayobject *ao)
{
arrayiterobject *it;
if (!array_Check(ao)) {
PyErr_BadInternalCall();
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;
}
static PyObject *
arrayiter_next(arrayiterobject *it)
{
arrayobject *ao;
assert(it != NULL);
assert(PyArrayIter_Check(it));
ao = it->ao;
if (ao == NULL) {
return NULL;
}
assert(array_Check(ao));
if (it->index < Py_SIZE(ao)) {
return (*it->getitem)(ao, it->index++);
}
it->ao = NULL;
Py_DECREF(ao);
return NULL;
}
static void
arrayiter_dealloc(arrayiterobject *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;
}
/*[clinic input]
array.arrayiterator.__reduce__
Return state information for pickling.
[clinic start generated code]*/
static PyObject *
array_arrayiterator___reduce___impl(arrayiterobject *self)
/*[clinic end generated code: output=7898a52e8e66e016 input=a062ea1e9951417a]*/
{
PyObject *func = _PyObject_GetBuiltin("iter");
if (self->ao == NULL) {
return Py_BuildValue("N(())", func);
}
return Py_BuildValue("N(O)n", func, self->ao, self->index);
}
/*[clinic input]
array.arrayiterator.__setstate__
state: object
/
Set state information for unpickling.
[clinic start generated code]*/
static PyObject *
array_arrayiterator___setstate__(arrayiterobject *self, PyObject *state)
/*[clinic end generated code: output=397da9904e443cbe input=f47d5ceda19e787b]*/
{
Py_ssize_t index = PyLong_AsSsize_t(state);
if (index == -1 && PyErr_Occurred())
return NULL;
if (index < 0)
index = 0;
else if (index > Py_SIZE(self->ao))
index = Py_SIZE(self->ao); /* iterator exhausted */
self->index = index;
Py_RETURN_NONE;
}
static PyMethodDef arrayiter_methods[] = {
ARRAY_ARRAYITERATOR___REDUCE___METHODDEF
ARRAY_ARRAYITERATOR___SETSTATE___METHODDEF
{NULL, NULL} /* sentinel */
};
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_reserved */
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 */
arrayiter_methods, /* tp_methods */
};
/*********************** Install Module **************************/
/* No functions in array module. */
static PyMethodDef a_methods[] = {
ARRAY__ARRAY_RECONSTRUCTOR_METHODDEF
{NULL, NULL, 0, NULL} /* Sentinel */
};
static int
array_modexec(PyObject *m)
{
char buffer[Py_ARRAY_LENGTH(descriptors)], *p;
PyObject *typecodes;
Py_ssize_t size = 0;
const struct arraydescr *descr;
if (PyType_Ready(&Arraytype) < 0)
return -1;
Py_TYPE(&PyArrayIter_Type) = &PyType_Type;
Py_INCREF((PyObject *)&Arraytype);
PyModule_AddObject(m, "ArrayType", (PyObject *)&Arraytype);
Py_INCREF((PyObject *)&Arraytype);
PyModule_AddObject(m, "array", (PyObject *)&Arraytype);
for (descr=descriptors; descr->typecode != '\0'; descr++) {
size++;
}
p = buffer;
for (descr = descriptors; descr->typecode != '\0'; descr++) {
*p++ = (char)descr->typecode;
}
typecodes = PyUnicode_DecodeASCII(buffer, p - buffer, NULL);
PyModule_AddObject(m, "typecodes", typecodes);
if (PyErr_Occurred()) {
Py_DECREF(m);
m = NULL;
}
return 0;
}
static PyModuleDef_Slot arrayslots[] = {
{Py_mod_exec, array_modexec},
{0, NULL}
};
static struct PyModuleDef arraymodule = {
PyModuleDef_HEAD_INIT,
"array",
module_doc,
0,
a_methods,
arrayslots,
NULL,
NULL,
NULL
};
PyMODINIT_FUNC
PyInit_array(void)
{
return PyModuleDef_Init(&arraymodule);
}
_Section(".rodata.pytab.1") const struct _inittab _PyImport_Inittab_array = {
"array",
PyInit_array,
};
| 89,782 | 3,065 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Modules/termios.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:8;coding:utf-8 -*-â
âvi: set net ft=c ts=4 sts=4 sw=4 fenc=utf-8 :viâ
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ¡
â Python 3 â
â https://docs.python.org/3/license.html â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
#include "libc/calls/struct/termios.h"
#include "libc/calls/termios.h"
#include "libc/calls/ttydefaults.h"
#include "libc/calls/weirdtypes.h"
#include "libc/dce.h"
#include "libc/sysv/consts/baud.internal.h"
#include "libc/sysv/consts/fio.h"
#include "libc/sysv/consts/modem.h"
#include "libc/sysv/consts/pty.h"
#include "libc/sysv/consts/termios.h"
#include "third_party/python/Include/bytesobject.h"
#include "third_party/python/Include/fileobject.h"
#include "third_party/python/Include/import.h"
#include "third_party/python/Include/listobject.h"
#include "third_party/python/Include/longobject.h"
#include "third_party/python/Include/modsupport.h"
#include "third_party/python/Include/object.h"
#include "third_party/python/Include/pyerrors.h"
#include "third_party/python/Include/pymacro.h"
#include "third_party/python/Include/yoink.h"
/* clang-format off */
PYTHON_PROVIDE("termios");
PYTHON_PROVIDE("termios.B1000000");
PYTHON_PROVIDE("termios.B110");
PYTHON_PROVIDE("termios.B115200");
PYTHON_PROVIDE("termios.B1152000");
PYTHON_PROVIDE("termios.B1200");
PYTHON_PROVIDE("termios.B134");
PYTHON_PROVIDE("termios.B150");
PYTHON_PROVIDE("termios.B1500000");
PYTHON_PROVIDE("termios.B1800");
PYTHON_PROVIDE("termios.B19200");
PYTHON_PROVIDE("termios.B200");
PYTHON_PROVIDE("termios.B2000000");
PYTHON_PROVIDE("termios.B230400");
PYTHON_PROVIDE("termios.B2400");
PYTHON_PROVIDE("termios.B2500000");
PYTHON_PROVIDE("termios.B300");
PYTHON_PROVIDE("termios.B3000000");
PYTHON_PROVIDE("termios.B3500000");
PYTHON_PROVIDE("termios.B38400");
PYTHON_PROVIDE("termios.B4000000");
PYTHON_PROVIDE("termios.B4800");
PYTHON_PROVIDE("termios.B50");
PYTHON_PROVIDE("termios.B500000");
PYTHON_PROVIDE("termios.B57600");
PYTHON_PROVIDE("termios.B576000");
PYTHON_PROVIDE("termios.B600");
PYTHON_PROVIDE("termios.B75");
PYTHON_PROVIDE("termios.B9600");
PYTHON_PROVIDE("termios.BRKINT");
PYTHON_PROVIDE("termios.BS0");
PYTHON_PROVIDE("termios.BS1");
PYTHON_PROVIDE("termios.BSDLY");
PYTHON_PROVIDE("termios.CBAUD");
PYTHON_PROVIDE("termios.CBAUDEX");
PYTHON_PROVIDE("termios.CDSUSP");
PYTHON_PROVIDE("termios.CEOF");
PYTHON_PROVIDE("termios.CEOL");
PYTHON_PROVIDE("termios.CEOT");
PYTHON_PROVIDE("termios.CERASE");
PYTHON_PROVIDE("termios.CFLUSH");
PYTHON_PROVIDE("termios.CIBAUD");
PYTHON_PROVIDE("termios.CINTR");
PYTHON_PROVIDE("termios.CKILL");
PYTHON_PROVIDE("termios.CLNEXT");
PYTHON_PROVIDE("termios.CLOCAL");
PYTHON_PROVIDE("termios.CQUIT");
PYTHON_PROVIDE("termios.CR0");
PYTHON_PROVIDE("termios.CR1");
PYTHON_PROVIDE("termios.CR2");
PYTHON_PROVIDE("termios.CR3");
PYTHON_PROVIDE("termios.CRDLY");
PYTHON_PROVIDE("termios.CREAD");
PYTHON_PROVIDE("termios.CRPRNT");
PYTHON_PROVIDE("termios.CS5");
PYTHON_PROVIDE("termios.CS6");
PYTHON_PROVIDE("termios.CS7");
PYTHON_PROVIDE("termios.CS8");
PYTHON_PROVIDE("termios.CSIZE");
PYTHON_PROVIDE("termios.CSTART");
PYTHON_PROVIDE("termios.CSTOP");
PYTHON_PROVIDE("termios.CSTOPB");
PYTHON_PROVIDE("termios.CSUSP");
PYTHON_PROVIDE("termios.CWERASE");
PYTHON_PROVIDE("termios.ECHO");
PYTHON_PROVIDE("termios.ECHOCTL");
PYTHON_PROVIDE("termios.ECHOE");
PYTHON_PROVIDE("termios.ECHOK");
PYTHON_PROVIDE("termios.ECHOKE");
PYTHON_PROVIDE("termios.ECHONL");
PYTHON_PROVIDE("termios.ECHOPRT");
PYTHON_PROVIDE("termios.EXTA");
PYTHON_PROVIDE("termios.EXTB");
PYTHON_PROVIDE("termios.FF0");
PYTHON_PROVIDE("termios.FF1");
PYTHON_PROVIDE("termios.FFDLY");
PYTHON_PROVIDE("termios.FIOASYNC");
PYTHON_PROVIDE("termios.FIOCLEX");
PYTHON_PROVIDE("termios.FIONBIO");
PYTHON_PROVIDE("termios.FIONCLEX");
PYTHON_PROVIDE("termios.FIONREAD");
PYTHON_PROVIDE("termios.FLUSHO");
PYTHON_PROVIDE("termios.HUPCL");
PYTHON_PROVIDE("termios.ICANON");
PYTHON_PROVIDE("termios.ICRNL");
PYTHON_PROVIDE("termios.IEXTEN");
PYTHON_PROVIDE("termios.IGNBRK");
PYTHON_PROVIDE("termios.IGNCR");
PYTHON_PROVIDE("termios.IGNPAR");
PYTHON_PROVIDE("termios.IMAXBEL");
PYTHON_PROVIDE("termios.INLCR");
PYTHON_PROVIDE("termios.INPCK");
PYTHON_PROVIDE("termios.ISIG");
PYTHON_PROVIDE("termios.ISTRIP");
PYTHON_PROVIDE("termios.IUCLC");
PYTHON_PROVIDE("termios.IXANY");
PYTHON_PROVIDE("termios.IXOFF");
PYTHON_PROVIDE("termios.IXON");
PYTHON_PROVIDE("termios.NCCS");
PYTHON_PROVIDE("termios.NL0");
PYTHON_PROVIDE("termios.NL1");
PYTHON_PROVIDE("termios.NLDLY");
PYTHON_PROVIDE("termios.NOFLSH");
PYTHON_PROVIDE("termios.OCRNL");
PYTHON_PROVIDE("termios.OFDEL");
PYTHON_PROVIDE("termios.OFILL");
PYTHON_PROVIDE("termios.OLCUC");
PYTHON_PROVIDE("termios.ONLCR");
PYTHON_PROVIDE("termios.ONLRET");
PYTHON_PROVIDE("termios.ONOCR");
PYTHON_PROVIDE("termios.OPOST");
PYTHON_PROVIDE("termios.PARENB");
PYTHON_PROVIDE("termios.PARMRK");
PYTHON_PROVIDE("termios.PARODD");
PYTHON_PROVIDE("termios.PENDIN");
PYTHON_PROVIDE("termios.TAB0");
PYTHON_PROVIDE("termios.TAB1");
PYTHON_PROVIDE("termios.TAB2");
PYTHON_PROVIDE("termios.TAB3");
PYTHON_PROVIDE("termios.TABDLY");
PYTHON_PROVIDE("termios.TCFLSH");
PYTHON_PROVIDE("termios.TCGETS");
PYTHON_PROVIDE("termios.TCIFLUSH");
PYTHON_PROVIDE("termios.TCIOFF");
PYTHON_PROVIDE("termios.TCIOFLUSH");
PYTHON_PROVIDE("termios.TCION");
PYTHON_PROVIDE("termios.TCOFLUSH");
PYTHON_PROVIDE("termios.TCOOFF");
PYTHON_PROVIDE("termios.TCOON");
PYTHON_PROVIDE("termios.TCSADRAIN");
PYTHON_PROVIDE("termios.TCSAFLUSH");
PYTHON_PROVIDE("termios.TCSANOW");
PYTHON_PROVIDE("termios.TCSBRK");
PYTHON_PROVIDE("termios.TCSETS");
PYTHON_PROVIDE("termios.TCSETSF");
PYTHON_PROVIDE("termios.TCSETSW");
PYTHON_PROVIDE("termios.TCXONC");
PYTHON_PROVIDE("termios.TIOCCONS");
PYTHON_PROVIDE("termios.TIOCGETD");
PYTHON_PROVIDE("termios.TIOCGPGRP");
PYTHON_PROVIDE("termios.TIOCGWINSZ");
PYTHON_PROVIDE("termios.TIOCMBIC");
PYTHON_PROVIDE("termios.TIOCMBIS");
PYTHON_PROVIDE("termios.TIOCMGET");
PYTHON_PROVIDE("termios.TIOCMSET");
PYTHON_PROVIDE("termios.TIOCM_CAR");
PYTHON_PROVIDE("termios.TIOCM_CD");
PYTHON_PROVIDE("termios.TIOCM_CTS");
PYTHON_PROVIDE("termios.TIOCM_DSR");
PYTHON_PROVIDE("termios.TIOCM_DTR");
PYTHON_PROVIDE("termios.TIOCM_LE");
PYTHON_PROVIDE("termios.TIOCM_RI");
PYTHON_PROVIDE("termios.TIOCM_RNG");
PYTHON_PROVIDE("termios.TIOCM_RTS");
PYTHON_PROVIDE("termios.TIOCM_SR");
PYTHON_PROVIDE("termios.TIOCM_ST");
PYTHON_PROVIDE("termios.TIOCNOTTY");
PYTHON_PROVIDE("termios.TIOCNXCL");
PYTHON_PROVIDE("termios.TIOCOUTQ");
PYTHON_PROVIDE("termios.TIOCPKT");
PYTHON_PROVIDE("termios.TIOCSCTTY");
PYTHON_PROVIDE("termios.TIOCSERGETLSR");
PYTHON_PROVIDE("termios.TIOCSERGETMULTI");
PYTHON_PROVIDE("termios.TIOCSERSETMULTI");
PYTHON_PROVIDE("termios.TIOCSER_TEMT");
PYTHON_PROVIDE("termios.TIOCSETD");
PYTHON_PROVIDE("termios.TIOCSPGRP");
PYTHON_PROVIDE("termios.TIOCSTI");
PYTHON_PROVIDE("termios.TIOCSWINSZ");
PYTHON_PROVIDE("termios.TOSTOP");
PYTHON_PROVIDE("termios.VDISCARD");
PYTHON_PROVIDE("termios.VEOF");
PYTHON_PROVIDE("termios.VEOL");
PYTHON_PROVIDE("termios.VEOL2");
PYTHON_PROVIDE("termios.VERASE");
PYTHON_PROVIDE("termios.VINTR");
PYTHON_PROVIDE("termios.VKILL");
PYTHON_PROVIDE("termios.VLNEXT");
PYTHON_PROVIDE("termios.VMIN");
PYTHON_PROVIDE("termios.VQUIT");
PYTHON_PROVIDE("termios.VREPRINT");
PYTHON_PROVIDE("termios.VSTART");
PYTHON_PROVIDE("termios.VSTOP");
PYTHON_PROVIDE("termios.VSUSP");
PYTHON_PROVIDE("termios.VSWTC");
PYTHON_PROVIDE("termios.VT0");
PYTHON_PROVIDE("termios.VT1");
PYTHON_PROVIDE("termios.VTDLY");
PYTHON_PROVIDE("termios.VTIME");
PYTHON_PROVIDE("termios.VWERASE");
PYTHON_PROVIDE("termios.XCASE");
PYTHON_PROVIDE("termios.XTABS");
PYTHON_PROVIDE("termios.error");
PYTHON_PROVIDE("termios.tcdrain");
PYTHON_PROVIDE("termios.tcflow");
PYTHON_PROVIDE("termios.tcflush");
PYTHON_PROVIDE("termios.tcgetattr");
PYTHON_PROVIDE("termios.tcsendbreak");
PYTHON_PROVIDE("termios.tcsetattr");
/* termiosmodule.c -- POSIX terminal I/O module implementation. */
PyDoc_STRVAR(termios__doc__,
"This module provides an interface to the Posix calls for tty I/O control.\n\
For a complete description of these calls, see the Posix or Unix manual\n\
pages. It is only available for those Unix versions that support Posix\n\
termios style tty I/O control.\n\
\n\
All functions in this module take a file descriptor fd as their first\n\
argument. This can be an integer file descriptor, such as returned by\n\
sys.stdin.fileno(), or a file object, such as sys.stdin itself.");
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;
}
PyDoc_STRVAR(termios_tcgetattr__doc__,
"tcgetattr(fd) -> list_of_attrs\n\
\n\
Get the tty attributes for file descriptor fd, as follows:\n\
[iflag, oflag, cflag, lflag, ispeed, ospeed, cc] where cc is a list\n\
of the tty special characters (each a string of length 1, except the items\n\
with indices VMIN and VTIME, which are integers when these fields are\n\
defined). The interpretation of the flags and the speeds as well as the\n\
indexing in the cc array must be done using the symbolic constants defined\n\
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 = PyBytes_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 = PyLong_FromLong((long)mode.c_cc[VMIN]);
if (v == NULL)
goto err;
PyList_SetItem(cc, VMIN, v);
v = PyLong_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, PyLong_FromLong((long)mode.c_iflag));
PyList_SetItem(v, 1, PyLong_FromLong((long)mode.c_oflag));
PyList_SetItem(v, 2, PyLong_FromLong((long)mode.c_cflag));
PyList_SetItem(v, 3, PyLong_FromLong((long)mode.c_lflag));
PyList_SetItem(v, 4, PyLong_FromLong((long)ispeed));
PyList_SetItem(v, 5, PyLong_FromLong((long)ospeed));
if (PyErr_Occurred()) {
Py_DECREF(v);
goto err;
}
PyList_SetItem(v, 6, cc);
return v;
err:
Py_DECREF(cc);
return NULL;
}
PyDoc_STRVAR(termios_tcsetattr__doc__,
"tcsetattr(fd, when, attributes) -> None\n\
\n\
Set the tty attributes for file descriptor fd.\n\
The attributes to be set are taken from the attributes argument, which\n\
is a list like the one returned by tcgetattr(). The when argument\n\
determines when the attributes are changed: termios.TCSANOW to\n\
change immediately, termios.TCSADRAIN to change after transmitting all\n\
queued output, or termios.TCSAFLUSH to change after transmitting all\n\
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) PyLong_AsLong(PyList_GetItem(term, 0));
mode.c_oflag = (tcflag_t) PyLong_AsLong(PyList_GetItem(term, 1));
mode.c_cflag = (tcflag_t) PyLong_AsLong(PyList_GetItem(term, 2));
mode.c_lflag = (tcflag_t) PyLong_AsLong(PyList_GetItem(term, 3));
ispeed = (speed_t) PyLong_AsLong(PyList_GetItem(term, 4));
ospeed = (speed_t) PyLong_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 (PyBytes_Check(v) && PyBytes_Size(v) == 1)
mode.c_cc[i] = (cc_t) * PyBytes_AsString(v);
else if (PyLong_Check(v))
mode.c_cc[i] = (cc_t) PyLong_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;
}
PyDoc_STRVAR(termios_tcsendbreak__doc__,
"tcsendbreak(fd, duration) -> None\n\
\n\
Send a break on file descriptor fd.\n\
A zero duration sends a break for 0.25-0.5 seconds; a nonzero duration\n\
has a system dependent meaning.");
static PyObject *
termios_tcsendbreak(PyObject *self, PyObject *args)
{
int fd, duration;
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;
}
PyDoc_STRVAR(termios_tcdrain__doc__,
"tcdrain(fd) -> None\n\
\n\
Wait until all output written to file descriptor fd has been transmitted.");
static PyObject *
termios_tcdrain(PyObject *self, PyObject *args)
{
int fd;
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;
}
PyDoc_STRVAR(termios_tcflush__doc__,
"tcflush(fd, queue) -> None\n\
\n\
Discard queued data on file descriptor fd.\n\
The queue selector specifies which queue: termios.TCIFLUSH for the input\n\
queue, termios.TCOFLUSH for the output queue, or termios.TCIOFLUSH for\n\
both queues. ");
static PyObject *
termios_tcflush(PyObject *self, PyObject *args)
{
int fd, queue;
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;
}
PyDoc_STRVAR(termios_tcflow__doc__,
"tcflow(fd, action) -> None\n\
\n\
Suspend or resume input or output on file descriptor fd.\n\
The action argument can be termios.TCOOFF to suspend output,\n\
termios.TCOON to restart output, termios.TCIOFF to suspend input,\n\
or termios.TCION to restart input.");
static PyObject *
termios_tcflow(PyObject *self, PyObject *args)
{
int fd, action;
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;
}
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}
};
#if defined(VSWTCH) && !defined(VSWTC)
#define VSWTC VSWTCH
#endif
#if defined(VSWTC) && !defined(VSWTCH)
#define VSWTCH VSWTC
#endif
static struct PyModuleDef termiosmodule = {
PyModuleDef_HEAD_INIT,
"termios",
termios__doc__,
-1,
termios_methods,
NULL,
NULL,
NULL,
NULL
};
PyMODINIT_FUNC
PyInit_termios(void)
{
PyObject *m;
m = PyModule_Create(&termiosmodule);
if (m == NULL)
return NULL;
if (TermiosError == NULL) {
TermiosError = PyErr_NewException("termios.error", NULL, NULL);
}
Py_INCREF(TermiosError);
PyModule_AddObject(m, "error", TermiosError);
if (B50) PyModule_AddIntConstant(m, "B50", B50);
if (B75) PyModule_AddIntConstant(m, "B75", B75);
if (B110) PyModule_AddIntConstant(m, "B110", B110);
if (B134) PyModule_AddIntConstant(m, "B134", B134);
if (B150) PyModule_AddIntConstant(m, "B150", B150);
if (B200) PyModule_AddIntConstant(m, "B200", B200);
if (B300) PyModule_AddIntConstant(m, "B300", B300);
if (B600) PyModule_AddIntConstant(m, "B600", B600);
if (B1200) PyModule_AddIntConstant(m, "B1200", B1200);
if (B1800) PyModule_AddIntConstant(m, "B1800", B1800);
if (B2400) PyModule_AddIntConstant(m, "B2400", B2400);
if (B4800) PyModule_AddIntConstant(m, "B4800", B4800);
if (B9600) PyModule_AddIntConstant(m, "B9600", B9600);
if (B19200) PyModule_AddIntConstant(m, "B19200", B19200);
if (B38400) PyModule_AddIntConstant(m, "B38400", B38400);
if (B57600) PyModule_AddIntConstant(m, "B57600", B57600);
if (B115200) PyModule_AddIntConstant(m, "B115200", B115200);
if (B230400) PyModule_AddIntConstant(m, "B230400", B230400);
if (B500000) PyModule_AddIntConstant(m, "B500000", B500000);
if (B576000) PyModule_AddIntConstant(m, "B576000", B576000);
if (B1000000) PyModule_AddIntConstant(m, "B1000000", B1000000);
if (B1152000) PyModule_AddIntConstant(m, "B1152000", B1152000);
if (B1500000) PyModule_AddIntConstant(m, "B1500000", B1500000);
if (B2000000) PyModule_AddIntConstant(m, "B2000000", B2000000);
if (B2500000) PyModule_AddIntConstant(m, "B2500000", B2500000);
if (B3000000) PyModule_AddIntConstant(m, "B3000000", B3000000);
if (B3500000) PyModule_AddIntConstant(m, "B3500000", B3500000);
if (B4000000) PyModule_AddIntConstant(m, "B4000000", B4000000);
if (CBAUDEX) PyModule_AddIntConstant(m, "CBAUDEX", CBAUDEX);
/* TODO(jart): B460800 */
/* TODO(jart): B921600 */
/* TODO(jart): B460800 */
PyModule_AddIntConstant(m, "TCSANOW", TCSANOW);
PyModule_AddIntConstant(m, "TCSADRAIN", TCSADRAIN);
PyModule_AddIntConstant(m, "TCSAFLUSH", TCSAFLUSH);
/* TODO(jart): TCSASOFT */
PyModule_AddIntConstant(m, "TCIFLUSH", TCIFLUSH);
PyModule_AddIntConstant(m, "TCOFLUSH", TCOFLUSH);
PyModule_AddIntConstant(m, "TCIOFLUSH", TCIOFLUSH);
PyModule_AddIntConstant(m, "TCOOFF", TCOOFF);
PyModule_AddIntConstant(m, "TCOON", TCOON);
PyModule_AddIntConstant(m, "TCIOFF", TCIOFF);
PyModule_AddIntConstant(m, "TCION", TCION);
if (IGNBRK) PyModule_AddIntConstant(m, "IGNBRK", IGNBRK);
if (BRKINT) PyModule_AddIntConstant(m, "BRKINT", BRKINT);
if (IGNPAR) PyModule_AddIntConstant(m, "IGNPAR", IGNPAR);
if (PARMRK) PyModule_AddIntConstant(m, "PARMRK", PARMRK);
if (INPCK) PyModule_AddIntConstant(m, "INPCK", INPCK);
if (ISTRIP) PyModule_AddIntConstant(m, "ISTRIP", ISTRIP);
if (INLCR) PyModule_AddIntConstant(m, "INLCR", INLCR);
if (IGNCR) PyModule_AddIntConstant(m, "IGNCR", IGNCR);
if (ICRNL) PyModule_AddIntConstant(m, "ICRNL", ICRNL);
if (IUCLC) PyModule_AddIntConstant(m, "IUCLC", IUCLC);
if (IXON) PyModule_AddIntConstant(m, "IXON", IXON);
if (IXANY) PyModule_AddIntConstant(m, "IXANY", IXANY);
if (IXOFF) PyModule_AddIntConstant(m, "IXOFF", IXOFF);
if (IMAXBEL) PyModule_AddIntConstant(m, "IMAXBEL", IMAXBEL);
PyModule_AddIntConstant(m, "OPOST", OPOST);
if (OLCUC) PyModule_AddIntConstant(m, "OLCUC", OLCUC);
if (ONLCR) PyModule_AddIntConstant(m, "ONLCR", ONLCR);
if (OCRNL) PyModule_AddIntConstant(m, "OCRNL", OCRNL);
if (ONOCR) PyModule_AddIntConstant(m, "ONOCR", ONOCR);
if (ONLRET) PyModule_AddIntConstant(m, "ONLRET", ONLRET);
if (OFILL) PyModule_AddIntConstant(m, "OFILL", OFILL);
if (OFDEL) PyModule_AddIntConstant(m, "OFDEL", OFDEL);
if (NLDLY) PyModule_AddIntConstant(m, "NLDLY", NLDLY);
if (CRDLY) PyModule_AddIntConstant(m, "CRDLY", CRDLY);
if (TABDLY) PyModule_AddIntConstant(m, "TABDLY", TABDLY);
if (BSDLY) PyModule_AddIntConstant(m, "BSDLY", BSDLY);
if (VTDLY) PyModule_AddIntConstant(m, "VTDLY", VTDLY);
if (FFDLY) PyModule_AddIntConstant(m, "FFDLY", FFDLY);
PyModule_AddIntConstant(m, "NL0", NL0);
if (NL1) PyModule_AddIntConstant(m, "NL1", NL1);
PyModule_AddIntConstant(m, "CR0", CR0);
if (CR1) PyModule_AddIntConstant(m, "CR1", CR1);
if (CR2) PyModule_AddIntConstant(m, "CR2", CR2);
if (CR3) PyModule_AddIntConstant(m, "CR3", CR3);
PyModule_AddIntConstant(m, "TAB0", TAB0);
if (TAB1) PyModule_AddIntConstant(m, "TAB1", TAB1);
if (TAB2) PyModule_AddIntConstant(m, "TAB2", TAB2);
if (TAB3) PyModule_AddIntConstant(m, "TAB3", TAB3);
if (XTABS) PyModule_AddIntConstant(m, "XTABS", XTABS);
PyModule_AddIntConstant(m, "BS0", BS0);
if (BS1) PyModule_AddIntConstant(m, "BS1", BS1);
PyModule_AddIntConstant(m, "VT0", VT0);
if (VT1) PyModule_AddIntConstant(m, "VT1", VT1);
PyModule_AddIntConstant(m, "FF0", FF0);
if (FF1) PyModule_AddIntConstant(m, "FF1", FF1);
if (CSIZE) PyModule_AddIntConstant(m, "CSIZE", CSIZE);
if (CSTOPB) PyModule_AddIntConstant(m, "CSTOPB", CSTOPB);
if (CREAD) PyModule_AddIntConstant(m, "CREAD", CREAD);
if (PARENB) PyModule_AddIntConstant(m, "PARENB", PARENB);
if (PARODD) PyModule_AddIntConstant(m, "PARODD", PARODD);
if (HUPCL) PyModule_AddIntConstant(m, "HUPCL", HUPCL);
if (CLOCAL) PyModule_AddIntConstant(m, "CLOCAL", CLOCAL);
if (CIBAUD) PyModule_AddIntConstant(m, "CIBAUD", CIBAUD);
PyModule_AddIntConstant(m, "CS5", CS5);
if (CS6) PyModule_AddIntConstant(m, "CS6", CS6);
if (CS7) PyModule_AddIntConstant(m, "CS7", CS7);
if (CS8) PyModule_AddIntConstant(m, "CS8", CS8);
PyModule_AddIntConstant(m, "ISIG", ISIG);
PyModule_AddIntConstant(m, "ICANON", ICANON);
if (XCASE) PyModule_AddIntConstant(m, "XCASE", XCASE);
PyModule_AddIntConstant(m, "ECHO", ECHO);
PyModule_AddIntConstant(m, "ECHOE", ECHOE);
PyModule_AddIntConstant(m, "ECHOK", ECHOK);
PyModule_AddIntConstant(m, "ECHONL", ECHONL);
PyModule_AddIntConstant(m, "ECHOCTL", ECHOCTL);
PyModule_AddIntConstant(m, "ECHOPRT", ECHOPRT);
PyModule_AddIntConstant(m, "ECHOKE", ECHOKE);
PyModule_AddIntConstant(m, "FLUSHO", FLUSHO);
PyModule_AddIntConstant(m, "NOFLSH", NOFLSH);
PyModule_AddIntConstant(m, "TOSTOP", TOSTOP);
PyModule_AddIntConstant(m, "PENDIN", PENDIN);
PyModule_AddIntConstant(m, "IEXTEN", IEXTEN);
/* TODO(jart): CRTSCTS */
/* termios.c_cc[ð] */
PyModule_AddIntConstant(m, "VINTR", VINTR);
PyModule_AddIntConstant(m, "VQUIT", VQUIT);
PyModule_AddIntConstant(m, "VERASE", VERASE);
PyModule_AddIntConstant(m, "VKILL", VKILL);
PyModule_AddIntConstant(m, "VEOF", VEOF);
PyModule_AddIntConstant(m, "VTIME", VTIME);
PyModule_AddIntConstant(m, "VMIN", VMIN);
if (VSWTC) PyModule_AddIntConstant(m, "VSWTC", VSWTC);
PyModule_AddIntConstant(m, "VSTART", VSTART);
PyModule_AddIntConstant(m, "VSTOP", VSTOP);
PyModule_AddIntConstant(m, "VSUSP", VSUSP);
PyModule_AddIntConstant(m, "VEOL", VEOL);
PyModule_AddIntConstant(m, "VREPRINT", VREPRINT);
PyModule_AddIntConstant(m, "VDISCARD", VDISCARD);
PyModule_AddIntConstant(m, "VWERASE", VWERASE);
PyModule_AddIntConstant(m, "VLNEXT", VLNEXT);
PyModule_AddIntConstant(m, "VEOL2", VEOL2);
if (CBAUD) PyModule_AddIntConstant(m, "CBAUD", CBAUD);
/* <sys/ttydefaults.h> */
PyModule_AddIntConstant(m, "CEOF", CEOF);
PyModule_AddIntConstant(m, "CDSUSP", CDSUSP);
PyModule_AddIntConstant(m, "CEOL", CEOL);
PyModule_AddIntConstant(m, "CFLUSH", CFLUSH);
PyModule_AddIntConstant(m, "CINTR", CINTR);
PyModule_AddIntConstant(m, "CKILL", CKILL);
PyModule_AddIntConstant(m, "CLNEXT", CLNEXT);
PyModule_AddIntConstant(m, "CEOT", CEOT);
PyModule_AddIntConstant(m, "CERASE", CERASE);
PyModule_AddIntConstant(m, "CQUIT", CQUIT);
PyModule_AddIntConstant(m, "CRPRNT", CRPRNT);
PyModule_AddIntConstant(m, "CSTART", CSTART);
PyModule_AddIntConstant(m, "CSTOP", CSTOP);
PyModule_AddIntConstant(m, "CSUSP", CSUSP);
PyModule_AddIntConstant(m, "CWERASE", CWERASE);
/* ioctl */
PyModule_AddIntConstant(m, "FIOCLEX", FIOCLEX);
PyModule_AddIntConstant(m, "FIONCLEX", FIONCLEX);
PyModule_AddIntConstant(m, "FIONBIO", FIONBIO);
PyModule_AddIntConstant(m, "FIONREAD", FIONREAD);
PyModule_AddIntConstant(m, "FIOASYNC", FIOASYNC);
if (EXTA) PyModule_AddIntConstant(m, "EXTA", EXTA);
if (EXTB) PyModule_AddIntConstant(m, "EXTB", EXTB);
/* TODO(jart): IBSHIFT */
/* TODO(jart): CC */
/* TODO(jart): MASK */
/* TODO(jart): SHIFT */
/* TODO(jart): NCC */
if (NCCS) PyModule_AddIntConstant(m, "NCCS", NCCS);
/* TODO(jart): MOUSE */
/* TODO(jart): PPP */
/* TODO(jart): SLIP */
/* TODO(jart): STRIP */
/* TODO(jart): TTY */
if (TCFLSH) PyModule_AddIntConstant(m, "TCFLSH", TCFLSH);
/* TODO(jart): TCGETA */
if (TCGETS) PyModule_AddIntConstant(m, "TCGETS", TCGETS);
if (TCSBRK) PyModule_AddIntConstant(m, "TCSBRK", TCSBRK);
/* TODO(jart): TCSBRKP */
/* TODO(jart): TCSETA */
/* TODO(jart): TCSETAF */
/* TODO(jart): TCSETAW */
if (TCSETS) PyModule_AddIntConstant(m, "TCSETS", TCSETS);
if (TCSETSF) PyModule_AddIntConstant(m, "TCSETSF", TCSETSF);
if (TCSETSW) PyModule_AddIntConstant(m, "TCSETSW", TCSETSW);
if (TCXONC) PyModule_AddIntConstant(m, "TCXONC", TCXONC);
if (TIOCCONS) PyModule_AddIntConstant(m, "TIOCCONS", TIOCCONS);
/* TODO(jart): TIOCEXCL */
if (TIOCGETD) PyModule_AddIntConstant(m, "TIOCGETD", TIOCGETD);
/* TODO(jart): TIOCGICOUNT */
/* TODO(jart): TIOCGLCKTRMIOS */
if (TIOCGPGRP) PyModule_AddIntConstant(m, "TIOCGPGRP", TIOCGPGRP);
/* TODO(jart): TIOCGSERIAL */
/* TODO(jart): TIOCGSOFTCAR */
PyModule_AddIntConstant(m, "TIOCGWINSZ", TIOCGWINSZ);
PyModule_AddIntConstant(m, "TIOCSWINSZ", TIOCSWINSZ);
/* TODO(jart): TIOCINQ */
/* TODO(jart): TIOCLINUX */
if (TIOCMBIC) PyModule_AddIntConstant(m, "TIOCMBIC", TIOCMBIC);
if (TIOCMBIS) PyModule_AddIntConstant(m, "TIOCMBIS", TIOCMBIS);
if (TIOCMGET) PyModule_AddIntConstant(m, "TIOCMGET", TIOCMGET);
/* TODO(jart): TIOCMIWAIT */
if (TIOCMSET) PyModule_AddIntConstant(m, "TIOCMSET", TIOCMSET);
if (TIOCM_CAR) PyModule_AddIntConstant(m, "TIOCM_CAR", TIOCM_CAR);
if (TIOCM_CD) PyModule_AddIntConstant(m, "TIOCM_CD", TIOCM_CD);
if (TIOCM_CTS) PyModule_AddIntConstant(m, "TIOCM_CTS", TIOCM_CTS);
if (TIOCM_DSR) PyModule_AddIntConstant(m, "TIOCM_DSR", TIOCM_DSR);
if (TIOCM_DTR) PyModule_AddIntConstant(m, "TIOCM_DTR", TIOCM_DTR);
if (TIOCM_LE) PyModule_AddIntConstant(m, "TIOCM_LE", TIOCM_LE);
if (TIOCM_RI) PyModule_AddIntConstant(m, "TIOCM_RI", TIOCM_RI);
if (TIOCM_RNG) PyModule_AddIntConstant(m, "TIOCM_RNG", TIOCM_RNG);
if (TIOCM_RTS) PyModule_AddIntConstant(m, "TIOCM_RTS", TIOCM_RTS);
if (TIOCM_SR) PyModule_AddIntConstant(m, "TIOCM_SR", TIOCM_SR);
if (TIOCM_ST) PyModule_AddIntConstant(m, "TIOCM_ST", TIOCM_ST);
if (TIOCNOTTY) PyModule_AddIntConstant(m, "TIOCNOTTY", TIOCNOTTY);
if (TIOCNXCL) PyModule_AddIntConstant(m, "TIOCNXCL", TIOCNXCL);
if (TIOCOUTQ) PyModule_AddIntConstant(m, "TIOCOUTQ", TIOCOUTQ);
if (TIOCPKT != -1) PyModule_AddIntConstant(m, "TIOCPKT", TIOCPKT);
/* TODO(jart): DATA */
/* TODO(jart): DOSTOP */
/* TODO(jart): FLUSHREAD */
/* TODO(jart): FLUSHWRITE */
/* TODO(jart): NOSTOP */
/* TODO(jart): START */
/* TODO(jart): STOP */
if (TIOCSCTTY) PyModule_AddIntConstant(m, "TIOCSCTTY", TIOCSCTTY);
/* TODO(jart): TIOCSERCONFIG */
if (TIOCSERGETLSR) PyModule_AddIntConstant(m, "TIOCSERGETLSR", TIOCSERGETLSR);
if (TIOCSERGETMULTI) PyModule_AddIntConstant(m, "TIOCSERGETMULTI", TIOCSERGETMULTI);
/* TODO(jart): TIOCSERGSTRUCT */
/* TODO(jart): TIOCSERGWILD */
if (TIOCSERSETMULTI) PyModule_AddIntConstant(m, "TIOCSERSETMULTI", TIOCSERSETMULTI);
/* TODO(jart): TIOCSERSWILD */
if (TIOCSER_TEMT) PyModule_AddIntConstant(m, "TIOCSER_TEMT", TIOCSER_TEMT);
if (TIOCSETD) PyModule_AddIntConstant(m, "TIOCSETD", TIOCSETD);
/* TODO(jart): TIOCSLCKTRMIOS */
if (TIOCSPGRP) PyModule_AddIntConstant(m, "TIOCSPGRP", TIOCSPGRP);
/* TODO(jart): TIOCSSERIAL */
/* TODO(jart): TIOCSSOFTCAR */
if (TIOCSTI) PyModule_AddIntConstant(m, "TIOCSTI", TIOCSTI);
/* TODO(jart): TIOCTTYGSTRUCT */
return m;
}
_Section(".rodata.pytab.1") const struct _inittab _PyImport_Inittab_termios = {
"termios",
PyInit_termios,
};
| 30,391 | 799 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Modules/pwdmodule.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:8;coding:utf-8 -*-â
âvi: set net ft=c ts=4 sts=4 sw=4 fenc=utf-8 :viâ
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ¡
â Python 3 â
â https://docs.python.org/3/license.html â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
#include "third_party/musl/passwd.h"
#include "third_party/python/Include/bytesobject.h"
#include "third_party/python/Include/import.h"
#include "third_party/python/Include/listobject.h"
#include "third_party/python/Include/modsupport.h"
#include "third_party/python/Include/object.h"
#include "third_party/python/Include/pyerrors.h"
#include "third_party/python/Include/pymacro.h"
#include "third_party/python/Include/structseq.h"
#include "third_party/python/Include/unicodeobject.h"
#include "third_party/python/Include/yoink.h"
#include "third_party/python/Modules/clinic/pwdmodule.inc"
#include "third_party/python/Modules/posixmodule.h"
/* clang-format off */
PYTHON_PROVIDE("pwd");
PYTHON_PROVIDE("pwd.getpwall");
PYTHON_PROVIDE("pwd.getpwnam");
PYTHON_PROVIDE("pwd.getpwuid");
PYTHON_PROVIDE("pwd.struct_passwd");
/* UNIX password file access module */
/*[clinic input]
module pwd
[clinic start generated code]*/
/*[clinic end generated code: output=da39a3ee5e6b4b0d input=60f628ef356b97b6]*/
static PyStructSequence_Field struct_pwd_type_fields[] = {
{"pw_name", PyDoc_STR("user name")},
{"pw_passwd", PyDoc_STR("password")},
{"pw_uid", PyDoc_STR("user id")},
{"pw_gid", PyDoc_STR("group id")},
{"pw_gecos", PyDoc_STR("real name")},
{"pw_dir", PyDoc_STR("home directory")},
{"pw_shell", PyDoc_STR("shell program")},
{0}
};
PyDoc_STRVAR(struct_passwd__doc__,
"pwd.struct_passwd: Results from getpw*() routines.\n\n\
This object may be accessed either as a tuple of\n\
(pw_name,pw_passwd,pw_uid,pw_gid,pw_gecos,pw_dir,pw_shell)\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,
};
PyDoc_STRVAR(pwd__doc__,
"This module provides access to the Unix password database.\n\
It is available on all Unix versions.\n\
\n\
Password database entries are reported as 7-tuples containing the following\n\
items from the password database (see `<pwd.h>'), in order:\n\
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;
static void
sets(PyObject *v, int i, const char* val)
{
if (val) {
PyObject *o = PyUnicode_DecodeFSDefault(val);
PyStructSequence_SET_ITEM(v, i, o);
}
else {
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;
#define SETI(i,val) PyStructSequence_SET_ITEM(v, i, PyLong_FromLong((long) val))
#define SETS(i,val) sets(v, i, val)
SETS(setIndex++, p->pw_name);
#if defined(HAVE_STRUCT_PASSWD_PW_PASSWD) && !defined(__ANDROID__)
SETS(setIndex++, p->pw_passwd);
#else
SETS(setIndex++, "");
#endif
PyStructSequence_SET_ITEM(v, setIndex++, _PyLong_FromUid(p->pw_uid));
PyStructSequence_SET_ITEM(v, setIndex++, _PyLong_FromGid(p->pw_gid));
#if defined(HAVE_STRUCT_PASSWD_PW_GECOS)
SETS(setIndex++, p->pw_gecos);
#else
SETS(setIndex++, "");
#endif
SETS(setIndex++, p->pw_dir);
SETS(setIndex++, p->pw_shell);
#undef SETS
#undef SETI
if (PyErr_Occurred()) {
Py_XDECREF(v);
return NULL;
}
return v;
}
/*[clinic input]
pwd.getpwuid
uidobj: object
/
Return the password database entry for the given numeric user ID.
See `help(pwd)` for more on password database entries.
[clinic start generated code]*/
static PyObject *
pwd_getpwuid(PyObject *module, PyObject *uidobj)
/*[clinic end generated code: output=c4ee1d4d429b86c4 input=ae64d507a1c6d3e8]*/
{
uid_t uid;
struct passwd *p;
if (!_Py_Uid_Converter(uidobj, &uid)) {
if (PyErr_ExceptionMatches(PyExc_OverflowError))
PyErr_Format(PyExc_KeyError,
"getpwuid(): uid not found");
return NULL;
}
if ((p = getpwuid(uid)) == NULL) {
PyObject *uid_obj = _PyLong_FromUid(uid);
if (uid_obj == NULL)
return NULL;
PyErr_Format(PyExc_KeyError,
"getpwuid(): uid not found: %S", uid_obj);
Py_DECREF(uid_obj);
return NULL;
}
return mkpwent(p);
}
/*[clinic input]
pwd.getpwnam
arg: unicode
/
Return the password database entry for the given user name.
See `help(pwd)` for more on password database entries.
[clinic start generated code]*/
static PyObject *
pwd_getpwnam_impl(PyObject *module, PyObject *arg)
/*[clinic end generated code: output=6abeee92430e43d2 input=d5f7e700919b02d3]*/
{
char *name;
struct passwd *p;
PyObject *bytes, *retval = NULL;
if ((bytes = PyUnicode_EncodeFSDefault(arg)) == NULL)
return NULL;
/* check for embedded null bytes */
if (PyBytes_AsStringAndSize(bytes, &name, NULL) == -1)
goto out;
if ((p = getpwnam(name)) == NULL) {
PyErr_Format(PyExc_KeyError,
"getpwnam(): name not found: %R", arg);
goto out;
}
retval = mkpwent(p);
out:
Py_DECREF(bytes);
return retval;
}
#ifdef HAVE_GETPWENT
/*[clinic input]
pwd.getpwall
Return a list of all available password database entries, in arbitrary order.
See help(pwd) for more on password database entries.
[clinic start generated code]*/
static PyObject *
pwd_getpwall_impl(PyObject *module)
/*[clinic end generated code: output=4853d2f5a0afac8a input=d7ecebfd90219b85]*/
{
PyObject *d;
struct passwd *p;
if ((d = PyList_New(0)) == NULL)
return NULL;
setpwent();
while ((p = getpwent()) != NULL) {
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[] = {
PWD_GETPWUID_METHODDEF
PWD_GETPWNAM_METHODDEF
#ifdef HAVE_GETPWENT
PWD_GETPWALL_METHODDEF
#endif
{NULL, NULL} /* sentinel */
};
static struct PyModuleDef pwdmodule = {
PyModuleDef_HEAD_INIT,
"pwd",
pwd__doc__,
-1,
pwd_methods,
NULL,
NULL,
NULL,
NULL
};
PyMODINIT_FUNC
PyInit_pwd(void)
{
PyObject *m;
m = PyModule_Create(&pwdmodule);
if (m == NULL)
return NULL;
if (!initialized) {
if (PyStructSequence_InitType2(&StructPwdType,
&struct_pwd_type_desc) < 0)
return NULL;
initialized = 1;
}
Py_INCREF((PyObject *) &StructPwdType);
PyModule_AddObject(m, "struct_passwd", (PyObject *) &StructPwdType);
return m;
}
_Section(".rodata.pytab.1") const struct _inittab _PyImport_Inittab_pwd = {
"pwd",
PyInit_pwd,
};
| 7,823 | 273 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Modules/grpmodule.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:8;coding:utf-8 -*-â
âvi: set net ft=c ts=4 sts=4 sw=4 fenc=utf-8 :viâ
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ¡
â Python 3 â
â https://docs.python.org/3/license.html â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
#include "third_party/musl/passwd.h"
#include "third_party/python/Include/abstract.h"
#include "third_party/python/Include/bytesobject.h"
#include "third_party/python/Include/dictobject.h"
#include "third_party/python/Include/import.h"
#include "third_party/python/Include/listobject.h"
#include "third_party/python/Include/modsupport.h"
#include "third_party/python/Include/object.h"
#include "third_party/python/Include/pyerrors.h"
#include "third_party/python/Include/pymacro.h"
#include "third_party/python/Include/structseq.h"
#include "third_party/python/Include/unicodeobject.h"
#include "third_party/python/Include/warnings.h"
#include "third_party/python/Include/yoink.h"
#include "third_party/python/Modules/clinic/grpmodule.inc"
#include "third_party/python/Modules/posixmodule.h"
/* clang-format off */
PYTHON_PROVIDE("grp");
PYTHON_PROVIDE("grp.getgrall");
PYTHON_PROVIDE("grp.getgrgid");
PYTHON_PROVIDE("grp.getgrnam");
PYTHON_PROVIDE("grp.struct_group");
/* UNIX group file access module */
/*[clinic input]
module grp
[clinic start generated code]*/
/*[clinic end generated code: output=da39a3ee5e6b4b0d input=cade63f2ed1bd9f8]*/
static PyStructSequence_Field struct_group_type_fields[] = {
{"gr_name", PyDoc_STR("group name")},
{"gr_passwd", PyDoc_STR("password")},
{"gr_gid", PyDoc_STR("group id")},
{"gr_mem", PyDoc_STR("group members")},
{0}
};
PyDoc_STRVAR(struct_group__doc__,
"grp.struct_group: Results from getgr*() routines.\n\n\
This object may be accessed either as a tuple of\n\
(gr_name,gr_passwd,gr_gid,gr_mem)\n\
or via the object attributes as named in the above tuple.\n");
static PyStructSequence_Desc struct_group_type_desc = {
"grp.struct_group",
struct_group__doc__,
struct_group_type_fields,
4,
};
static int initialized;
static PyTypeObject StructGrpType;
static PyObject *
mkgrent(struct group *p)
{
int setIndex = 0;
PyObject *v = PyStructSequence_New(&StructGrpType), *w;
char **member;
if (v == NULL)
return NULL;
if ((w = PyList_New(0)) == NULL) {
Py_DECREF(v);
return NULL;
}
for (member = p->gr_mem; *member != NULL; member++) {
PyObject *x = PyUnicode_DecodeFSDefault(*member);
if (x == NULL || PyList_Append(w, x) != 0) {
Py_XDECREF(x);
Py_DECREF(w);
Py_DECREF(v);
return NULL;
}
Py_DECREF(x);
}
#define SET(i,val) PyStructSequence_SET_ITEM(v, i, val)
SET(setIndex++, PyUnicode_DecodeFSDefault(p->gr_name));
if (p->gr_passwd)
SET(setIndex++, PyUnicode_DecodeFSDefault(p->gr_passwd));
else {
SET(setIndex++, Py_None);
Py_INCREF(Py_None);
}
SET(setIndex++, _PyLong_FromGid(p->gr_gid));
SET(setIndex++, w);
#undef SET
if (PyErr_Occurred()) {
Py_DECREF(v);
return NULL;
}
return v;
}
/*[clinic input]
grp.getgrgid
id: object
Return the group database entry for the given numeric group ID.
If id is not valid, raise KeyError.
[clinic start generated code]*/
static PyObject *
grp_getgrgid_impl(PyObject *module, PyObject *id)
/*[clinic end generated code: output=30797c289504a1ba input=15fa0e2ccf5cda25]*/
{
PyObject *py_int_id;
gid_t gid;
struct group *p;
if (!_Py_Gid_Converter(id, &gid)) {
if (!PyErr_ExceptionMatches(PyExc_TypeError)) {
return NULL;
}
PyErr_Clear();
if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
"group id must be int, not %.200",
id->ob_type->tp_name) < 0) {
return NULL;
}
py_int_id = PyNumber_Long(id);
if (!py_int_id)
return NULL;
if (!_Py_Gid_Converter(py_int_id, &gid)) {
Py_DECREF(py_int_id);
return NULL;
}
Py_DECREF(py_int_id);
}
if ((p = getgrgid(gid)) == NULL) {
PyObject *gid_obj = _PyLong_FromGid(gid);
if (gid_obj == NULL)
return NULL;
PyErr_Format(PyExc_KeyError, "getgrgid(): gid not found: %S", gid_obj);
Py_DECREF(gid_obj);
return NULL;
}
return mkgrent(p);
}
/*[clinic input]
grp.getgrnam
name: unicode
Return the group database entry for the given group name.
If name is not valid, raise KeyError.
[clinic start generated code]*/
static PyObject *
grp_getgrnam_impl(PyObject *module, PyObject *name)
/*[clinic end generated code: output=67905086f403c21c input=08ded29affa3c863]*/
{
char *name_chars;
struct group *p;
PyObject *bytes, *retval = NULL;
if ((bytes = PyUnicode_EncodeFSDefault(name)) == NULL)
return NULL;
/* check for embedded null bytes */
if (PyBytes_AsStringAndSize(bytes, &name_chars, NULL) == -1)
goto out;
if ((p = getgrnam(name_chars)) == NULL) {
PyErr_Format(PyExc_KeyError, "getgrnam(): name not found: %R", name);
goto out;
}
retval = mkgrent(p);
out:
Py_DECREF(bytes);
return retval;
}
/*[clinic input]
grp.getgrall
Return a list of all available group entries, in arbitrary order.
An entry whose name starts with '+' or '-' represents an instruction
to use YP/NIS and may not be accessible via getgrnam or getgrgid.
[clinic start generated code]*/
static PyObject *
grp_getgrall_impl(PyObject *module)
/*[clinic end generated code: output=585dad35e2e763d7 input=d7df76c825c367df]*/
{
PyObject *d;
struct group *p;
if ((d = PyList_New(0)) == NULL)
return NULL;
setgrent();
while ((p = getgrent()) != NULL) {
PyObject *v = mkgrent(p);
if (v == NULL || PyList_Append(d, v) != 0) {
Py_XDECREF(v);
Py_DECREF(d);
endgrent();
return NULL;
}
Py_DECREF(v);
}
endgrent();
return d;
}
static PyMethodDef grp_methods[] = {
GRP_GETGRGID_METHODDEF
GRP_GETGRNAM_METHODDEF
GRP_GETGRALL_METHODDEF
{NULL, NULL}
};
PyDoc_STRVAR(grp__doc__,
"Access to the Unix group database.\n\
\n\
Group entries are reported as 4-tuples containing the following fields\n\
from the group database, in order:\n\
\n\
gr_name - name of the group\n\
gr_passwd - group password (encrypted); often empty\n\
gr_gid - numeric ID of the group\n\
gr_mem - list of members\n\
\n\
The gid is an integer, name and password are strings. (Note that most\n\
users are not explicitly listed as members of the groups they are in\n\
according to the password database. Check both databases to get\n\
complete membership information.)");
static struct PyModuleDef grpmodule = {
PyModuleDef_HEAD_INIT,
"grp",
grp__doc__,
-1,
grp_methods,
NULL,
NULL,
NULL,
NULL
};
PyMODINIT_FUNC
PyInit_grp(void)
{
PyObject *m, *d;
m = PyModule_Create(&grpmodule);
if (m == NULL)
return NULL;
d = PyModule_GetDict(m);
if (!initialized) {
if (PyStructSequence_InitType2(&StructGrpType,
&struct_group_type_desc) < 0)
return NULL;
}
if (PyDict_SetItemString(d, "struct_group",
(PyObject *)&StructGrpType) < 0)
return NULL;
initialized = 1;
return m;
}
_Section(".rodata.pytab.1") const struct _inittab _PyImport_Inittab_grp = {
"grp",
PyInit_grp,
};
| 8,241 | 285 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Modules/faulthandler.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:8;coding:utf-8 -*-â
âvi: set net ft=c ts=4 sts=4 sw=4 fenc=utf-8 :viâ
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ¡
â Python 3 â
â https://docs.python.org/3/license.html â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
#include "libc/calls/calls.h"
#include "libc/calls/struct/sigaction.h"
#include "libc/errno.h"
#include "libc/sysv/consts/rlimit.h"
#include "libc/sysv/consts/sa.h"
#include "libc/sysv/consts/sig.h"
#include "libc/sysv/consts/ss.h"
#include "third_party/python/Include/abstract.h"
#include "third_party/python/Include/boolobject.h"
#include "third_party/python/Include/ceval.h"
#include "third_party/python/Include/dictobject.h"
#include "third_party/python/Include/fileutils.h"
#include "third_party/python/Include/import.h"
#include "third_party/python/Include/longobject.h"
#include "third_party/python/Include/modsupport.h"
#include "third_party/python/Include/objimpl.h"
#include "third_party/python/Include/pydebug.h"
#include "third_party/python/Include/pyerrors.h"
#include "third_party/python/Include/pylifecycle.h"
#include "third_party/python/Include/pymacro.h"
#include "third_party/python/Include/pymem.h"
#include "third_party/python/Include/pythread.h"
#include "third_party/python/Include/sysmodule.h"
#include "third_party/python/Include/traceback.h"
#include "third_party/python/Include/yoink.h"
#include "third_party/python/pyconfig.h"
/* clang-format off */
PYTHON_PROVIDE("faulthandler");
PYTHON_PROVIDE("faulthandler._fatal_error");
PYTHON_PROVIDE("faulthandler._fatal_error_c_thread");
PYTHON_PROVIDE("faulthandler._read_null");
PYTHON_PROVIDE("faulthandler._sigabrt");
PYTHON_PROVIDE("faulthandler._sigfpe");
PYTHON_PROVIDE("faulthandler._sigsegv");
PYTHON_PROVIDE("faulthandler._stack_overflow");
PYTHON_PROVIDE("faulthandler.cancel_dump_traceback_later");
PYTHON_PROVIDE("faulthandler.disable");
PYTHON_PROVIDE("faulthandler.dump_traceback");
PYTHON_PROVIDE("faulthandler.dump_traceback_later");
PYTHON_PROVIDE("faulthandler.enable");
PYTHON_PROVIDE("faulthandler.is_enabled");
PYTHON_PROVIDE("faulthandler.register");
PYTHON_PROVIDE("faulthandler.unregister");
/* Allocate at maximum 100 MB of the stack to raise the stack overflow */
#define STACK_OVERFLOW_MAX_SIZE (100*1024*1024)
#ifdef WITH_THREAD
# define FAULTHANDLER_LATER
#endif
#ifndef MS_WINDOWS
/* register() is useless on Windows, because only SIGSEGV, SIGABRT and
SIGILL can be handled by the process, and these signals can only be used
with enable(), not using register() */
# define FAULTHANDLER_USER
#endif
#define PUTS(fd, str) _Py_write_noraise(fd, str, strlen(str))
_Py_IDENTIFIER(enable);
_Py_IDENTIFIER(fileno);
_Py_IDENTIFIER(flush);
_Py_IDENTIFIER(stderr);
#ifdef HAVE_SIGACTION
typedef struct sigaction _Py_sighandler_t;
#else
typedef PyOS_sighandler_t _Py_sighandler_t;
#endif
typedef struct {
int signum;
int enabled;
const char* name;
_Py_sighandler_t previous;
int all_threads;
} fault_handler_t;
static struct {
int enabled;
PyObject *file;
int fd;
int all_threads;
PyInterpreterState *interp;
#ifdef MS_WINDOWS
void *exc_handler;
#endif
} fatal_error = {0, NULL, -1, 0};
#ifdef FAULTHANDLER_LATER
static struct {
PyObject *file;
int fd;
PY_TIMEOUT_T timeout_us; /* timeout in microseconds */
int repeat;
PyInterpreterState *interp;
int exit_;
char *header;
size_t header_len;
/* The main thread always holds this lock. It is only released when
faulthandler_thread() is interrupted before this thread exits, or at
Python exit. */
PyThread_type_lock cancel_event;
/* released by child thread when joined */
PyThread_type_lock running;
} thread;
#endif
#ifdef FAULTHANDLER_USER
typedef struct {
int enabled;
PyObject *file;
int fd;
int all_threads;
int chain;
_Py_sighandler_t previous;
PyInterpreterState *interp;
} user_signal_t;
static user_signal_t *user_signals;
static void faulthandler_user(int signum);
#endif /* FAULTHANDLER_USER */
static fault_handler_t faulthandler_handlers[5];
static const size_t faulthandler_nsignals = \
Py_ARRAY_LENGTH(faulthandler_handlers);
static void faulthandler_handlers_init()
{
fault_handler_t local_handlers[] = {
#ifdef SIGBUS
{SIGBUS, 0, "Bus error", },
#endif
#ifdef SIGILL
{SIGILL, 0, "Illegal instruction", },
#endif
{SIGFPE, 0, "Floating point exception", },
{SIGABRT, 0, "Aborted", },
/* define SIGSEGV at the end to make it the default choice if searching the
handler fails in faulthandler_fatal_error() */
{SIGSEGV, 0, "Segmentation fault", }
};
_Static_assert(sizeof(faulthandler_handlers) == sizeof(local_handlers), "handler alloc error");
memcpy(faulthandler_handlers, local_handlers, sizeof(local_handlers));
}
#ifdef HAVE_SIGALTSTACK
static stack_t stack;
static stack_t old_stack;
#endif
/* Get the file descriptor of a file by calling its fileno() method and then
call its flush() method.
If file is NULL or Py_None, use sys.stderr as the new file.
If file is an integer, it will be treated as file descriptor.
On success, return the file descriptor and write the new file into *file_ptr.
On error, return -1. */
static int
faulthandler_get_fileno(PyObject **file_ptr)
{
PyObject *result;
long fd_long;
int fd;
PyObject *file = *file_ptr;
if (file == NULL || file == Py_None) {
file = _PySys_GetObjectId(&PyId_stderr);
if (file == NULL) {
PyErr_SetString(PyExc_RuntimeError, "unable to get sys.stderr");
return -1;
}
if (file == Py_None) {
PyErr_SetString(PyExc_RuntimeError, "sys.stderr is None");
return -1;
}
}
else if (PyLong_Check(file)) {
fd = _PyLong_AsInt(file);
if (fd == -1 && PyErr_Occurred())
return -1;
if (fd < 0) {
PyErr_SetString(PyExc_ValueError,
"file is not a valid file descripter");
return -1;
}
*file_ptr = NULL;
return fd;
}
result = _PyObject_CallMethodId(file, &PyId_fileno, NULL);
if (result == NULL)
return -1;
fd = -1;
if (PyLong_Check(result)) {
fd_long = PyLong_AsLong(result);
if (0 <= fd_long && fd_long < INT_MAX)
fd = (int)fd_long;
}
Py_DECREF(result);
if (fd == -1) {
PyErr_SetString(PyExc_RuntimeError,
"file.fileno() is not a valid file descriptor");
return -1;
}
result = _PyObject_CallMethodId(file, &PyId_flush, NULL);
if (result != NULL)
Py_DECREF(result);
else {
/* ignore flush() error */
PyErr_Clear();
}
*file_ptr = file;
return fd;
}
/* Get the state of the current thread: only call this function if the current
thread holds the GIL. Raise an exception on error. */
static PyThreadState*
get_thread_state(void)
{
PyThreadState *tstate = _PyThreadState_UncheckedGet();
if (tstate == NULL) {
/* just in case but very unlikely... */
PyErr_SetString(PyExc_RuntimeError,
"unable to get the current thread state");
return NULL;
}
return tstate;
}
static void
faulthandler_dump_traceback(int fd, int all_threads,
PyInterpreterState *interp)
{
static volatile int reentrant = 0;
PyThreadState *tstate;
if (reentrant)
return;
reentrant = 1;
#ifdef WITH_THREAD
/* SIGSEGV, SIGFPE, SIGABRT, SIGBUS and SIGILL are synchronous signals and
are thus delivered to the thread that caused the fault. Get the Python
thread state of the current thread.
PyThreadState_Get() doesn't give the state of the thread that caused the
fault if the thread released the GIL, and so this function cannot be
used. Read the thread local storage (TLS) instead: call
PyGILState_GetThisThreadState(). */
tstate = PyGILState_GetThisThreadState();
#else
tstate = _PyThreadState_UncheckedGet();
#endif
if (all_threads) {
(void)_Py_DumpTracebackThreads(fd, NULL, tstate);
}
else {
if (tstate != NULL)
_Py_DumpTraceback(fd, tstate);
}
reentrant = 0;
}
static PyObject*
faulthandler_dump_traceback_py(PyObject *self,
PyObject *args, PyObject *kwargs)
{
static char *kwlist[] = {"file", "all_threads", NULL};
PyObject *file = NULL;
int all_threads = 1;
PyThreadState *tstate;
const char *errmsg;
int fd;
if (!PyArg_ParseTupleAndKeywords(args, kwargs,
"|Oi:dump_traceback", kwlist,
&file, &all_threads))
return NULL;
fd = faulthandler_get_fileno(&file);
if (fd < 0)
return NULL;
tstate = get_thread_state();
if (tstate == NULL)
return NULL;
if (all_threads) {
errmsg = _Py_DumpTracebackThreads(fd, NULL, tstate);
if (errmsg != NULL) {
PyErr_SetString(PyExc_RuntimeError, errmsg);
return NULL;
}
}
else {
_Py_DumpTraceback(fd, tstate);
}
if (PyErr_CheckSignals())
return NULL;
Py_RETURN_NONE;
}
static void
faulthandler_disable_fatal_handler(fault_handler_t *handler)
{
if (!handler->enabled)
return;
handler->enabled = 0;
#ifdef HAVE_SIGACTION
(void)sigaction(handler->signum, &handler->previous, NULL);
#else
(void)signal(handler->signum, handler->previous);
#endif
}
/* Handler for SIGSEGV, SIGFPE, SIGABRT, SIGBUS and SIGILL signals.
Display the current Python traceback, restore the previous handler and call
the previous handler.
On Windows, don't explicitly call the previous handler, because the Windows
signal handler would not be called (for an unknown reason). The execution of
the program continues at faulthandler_fatal_error() exit, but the same
instruction will raise the same fault (signal), and so the previous handler
will be called.
This function is signal-safe and should only call signal-safe functions. */
static void
faulthandler_fatal_error(int signum)
{
const int fd = fatal_error.fd;
size_t i;
fault_handler_t *handler = NULL;
int save_errno = errno;
if (!fatal_error.enabled)
return;
for (i=0; i < faulthandler_nsignals; i++) {
handler = &faulthandler_handlers[i];
if (handler->signum == signum)
break;
}
if (handler == NULL) {
/* faulthandler_nsignals == 0 (unlikely) */
return;
}
/* restore the previous handler */
faulthandler_disable_fatal_handler(handler);
PUTS(fd, "Fatal Python error: ");
PUTS(fd, handler->name);
PUTS(fd, "\n\n");
faulthandler_dump_traceback(fd, fatal_error.all_threads,
fatal_error.interp);
errno = save_errno;
#ifdef MS_WINDOWS
if (signum == SIGSEGV) {
/* don't explicitly call the previous handler for SIGSEGV in this signal
handler, because the Windows signal handler would not be called */
return;
}
#endif
/* call the previous signal handler: it is called immediately if we use
sigaction() thanks to SA_NODEFER flag, otherwise it is deferred */
raise(signum);
}
#ifdef MS_WINDOWS
static int
faulthandler_ignore_exception(DWORD code)
{
/* bpo-30557: ignore exceptions which are not errors */
if (!(code & 0x80000000)) {
return 1;
}
/* bpo-31701: ignore MSC and COM exceptions
E0000000 + code */
if (code == 0xE06D7363 /* MSC exception ("Emsc") */
|| code == 0xE0434352 /* COM Callable Runtime exception ("ECCR") */) {
return 1;
}
/* Interesting exception: log it with the Python traceback */
return 0;
}
static LONG WINAPI
faulthandler_exc_handler(struct _EXCEPTION_POINTERS *exc_info)
{
const int fd = fatal_error.fd;
DWORD code = exc_info->ExceptionRecord->ExceptionCode;
DWORD flags = exc_info->ExceptionRecord->ExceptionFlags;
if (faulthandler_ignore_exception(code)) {
/* ignore the exception: call the next exception handler */
return EXCEPTION_CONTINUE_SEARCH;
}
PUTS(fd, "Windows fatal exception: ");
switch (code)
{
/* only format most common errors */
case EXCEPTION_ACCESS_VIOLATION: PUTS(fd, "access violation"); break;
case EXCEPTION_FLT_DIVIDE_BY_ZERO: PUTS(fd, "float divide by zero"); break;
case EXCEPTION_FLT_OVERFLOW: PUTS(fd, "float overflow"); break;
case EXCEPTION_INT_DIVIDE_BY_ZERO: PUTS(fd, "int divide by zero"); break;
case EXCEPTION_INT_OVERFLOW: PUTS(fd, "integer overflow"); break;
case EXCEPTION_IN_PAGE_ERROR: PUTS(fd, "page error"); break;
case EXCEPTION_STACK_OVERFLOW: PUTS(fd, "stack overflow"); break;
default:
PUTS(fd, "code 0x");
_Py_DumpHexadecimal(fd, code, 8);
}
PUTS(fd, "\n\n");
if (code == EXCEPTION_ACCESS_VIOLATION) {
/* disable signal handler for SIGSEGV */
size_t i;
for (i=0; i < faulthandler_nsignals; i++) {
fault_handler_t *handler = &faulthandler_handlers[i];
if (handler->signum == SIGSEGV) {
faulthandler_disable_fatal_handler(handler);
break;
}
}
}
faulthandler_dump_traceback(fd, fatal_error.all_threads,
fatal_error.interp);
/* call the next exception handler */
return EXCEPTION_CONTINUE_SEARCH;
}
#endif
/* Install the handler for fatal signals, faulthandler_fatal_error(). */
static int
faulthandler_enable(void)
{
size_t i;
if (fatal_error.enabled) {
return 0;
}
fatal_error.enabled = 1;
for (i=0; i < faulthandler_nsignals; i++) {
fault_handler_t *handler;
#ifdef HAVE_SIGACTION
struct sigaction action;
#endif
int err;
handler = &faulthandler_handlers[i];
assert(!handler->enabled);
#ifdef HAVE_SIGACTION
action.sa_handler = faulthandler_fatal_error;
sigemptyset(&action.sa_mask);
/* Do not prevent the signal from being received from within
its own signal handler */
action.sa_flags = SA_NODEFER;
#ifdef HAVE_SIGALTSTACK
if (stack.ss_sp != NULL) {
/* Call the signal handler on an alternate signal stack
provided by sigaltstack() */
action.sa_flags |= SA_ONSTACK;
}
#endif
err = sigaction(handler->signum, &action, &handler->previous);
#else
handler->previous = signal(handler->signum,
faulthandler_fatal_error);
err = (handler->previous == SIG_ERR);
#endif
if (err) {
PyErr_SetFromErrno(PyExc_RuntimeError);
return -1;
}
handler->enabled = 1;
}
#ifdef MS_WINDOWS
assert(fatal_error.exc_handler == NULL);
fatal_error.exc_handler = AddVectoredExceptionHandler(1, faulthandler_exc_handler);
#endif
return 0;
}
static PyObject*
faulthandler_py_enable(PyObject *self, PyObject *args, PyObject *kwargs)
{
static char *kwlist[] = {"file", "all_threads", NULL};
PyObject *file = NULL;
int all_threads = 1;
int fd;
PyThreadState *tstate;
if (!PyArg_ParseTupleAndKeywords(args, kwargs,
"|Oi:enable", kwlist, &file, &all_threads))
return NULL;
fd = faulthandler_get_fileno(&file);
if (fd < 0)
return NULL;
tstate = get_thread_state();
if (tstate == NULL)
return NULL;
Py_XINCREF(file);
Py_XSETREF(fatal_error.file, file);
fatal_error.fd = fd;
fatal_error.all_threads = all_threads;
fatal_error.interp = tstate->interp;
if (faulthandler_enable() < 0) {
return NULL;
}
Py_RETURN_NONE;
}
static void
faulthandler_disable(void)
{
unsigned int i;
fault_handler_t *handler;
if (fatal_error.enabled) {
fatal_error.enabled = 0;
for (i=0; i < faulthandler_nsignals; i++) {
handler = &faulthandler_handlers[i];
faulthandler_disable_fatal_handler(handler);
}
}
#ifdef MS_WINDOWS
if (fatal_error.exc_handler != NULL) {
RemoveVectoredExceptionHandler(fatal_error.exc_handler);
fatal_error.exc_handler = NULL;
}
#endif
Py_CLEAR(fatal_error.file);
}
static PyObject*
faulthandler_disable_py(PyObject *self)
{
if (!fatal_error.enabled) {
Py_INCREF(Py_False);
return Py_False;
}
faulthandler_disable();
Py_INCREF(Py_True);
return Py_True;
}
static PyObject*
faulthandler_is_enabled(PyObject *self)
{
return PyBool_FromLong(fatal_error.enabled);
}
#ifdef FAULTHANDLER_LATER
static void
faulthandler_thread(void *unused)
{
PyLockStatus st;
const char* errmsg;
int ok;
#if defined(HAVE_PTHREAD_SIGMASK) && !defined(HAVE_BROKEN_PTHREAD_SIGMASK)
sigset_t set;
/* we don't want to receive any signal */
sigfillset(&set);
pthread_sigmask(SIG_SETMASK, &set, NULL);
#endif
do {
st = PyThread_acquire_lock_timed(thread.cancel_event,
thread.timeout_us, 0);
if (st == PY_LOCK_ACQUIRED) {
PyThread_release_lock(thread.cancel_event);
break;
}
/* Timeout => dump traceback */
assert(st == PY_LOCK_FAILURE);
_Py_write_noraise(thread.fd, thread.header, (int)thread.header_len);
errmsg = _Py_DumpTracebackThreads(thread.fd, thread.interp, NULL);
ok = (errmsg == NULL);
if (thread.exit_)
_exit(1);
} while (ok && thread.repeat);
/* The only way out */
PyThread_release_lock(thread.running);
}
static void
cancel_dump_traceback_later(void)
{
/* Notify cancellation */
PyThread_release_lock(thread.cancel_event);
/* Wait for thread to join */
PyThread_acquire_lock(thread.running, 1);
PyThread_release_lock(thread.running);
/* The main thread should always hold the cancel_event lock */
PyThread_acquire_lock(thread.cancel_event, 1);
Py_CLEAR(thread.file);
if (thread.header) {
PyMem_Free(thread.header);
thread.header = NULL;
}
}
static char*
format_timeout(double timeout)
{
unsigned long us, sec, min, hour;
double intpart, fracpart;
char buffer[100];
fracpart = modf(timeout, &intpart);
sec = (unsigned long)intpart;
us = (unsigned long)(fracpart * 1e6);
min = sec / 60;
sec %= 60;
hour = min / 60;
min %= 60;
if (us != 0)
PyOS_snprintf(buffer, sizeof(buffer),
"Timeout (%lu:%02lu:%02lu.%06lu)!\n",
hour, min, sec, us);
else
PyOS_snprintf(buffer, sizeof(buffer),
"Timeout (%lu:%02lu:%02lu)!\n",
hour, min, sec);
return _PyMem_Strdup(buffer);
}
static PyObject*
faulthandler_dump_traceback_later(PyObject *self,
PyObject *args, PyObject *kwargs)
{
static char *kwlist[] = {"timeout", "repeat", "file", "exit", NULL};
double timeout;
PY_TIMEOUT_T timeout_us;
int repeat = 0;
PyObject *file = NULL;
int fd;
int exit = 0;
PyThreadState *tstate;
char *header;
size_t header_len;
if (!PyArg_ParseTupleAndKeywords(args, kwargs,
"d|iOi:dump_traceback_later", kwlist,
&timeout, &repeat, &file, &exit))
return NULL;
if ((timeout * 1e6) >= (double) PY_TIMEOUT_MAX) {
PyErr_SetString(PyExc_OverflowError, "timeout value is too large");
return NULL;
}
timeout_us = (PY_TIMEOUT_T)(timeout * 1e6);
if (timeout_us <= 0) {
PyErr_SetString(PyExc_ValueError, "timeout must be greater than 0");
return NULL;
}
tstate = get_thread_state();
if (tstate == NULL)
return NULL;
fd = faulthandler_get_fileno(&file);
if (fd < 0)
return NULL;
/* format the timeout */
header = format_timeout(timeout);
if (header == NULL)
return PyErr_NoMemory();
header_len = strlen(header);
/* Cancel previous thread, if running */
cancel_dump_traceback_later();
Py_XINCREF(file);
Py_XSETREF(thread.file, file);
thread.fd = fd;
thread.timeout_us = timeout_us;
thread.repeat = repeat;
thread.interp = tstate->interp;
thread.exit_ = exit;
thread.header = header;
thread.header_len = header_len;
/* Arm these locks to serve as events when released */
PyThread_acquire_lock(thread.running, 1);
if (PyThread_start_new_thread(faulthandler_thread, NULL) == -1) {
PyThread_release_lock(thread.running);
Py_CLEAR(thread.file);
PyMem_Free(header);
thread.header = NULL;
PyErr_SetString(PyExc_RuntimeError,
"unable to start watchdog thread");
return NULL;
}
Py_RETURN_NONE;
}
static PyObject*
faulthandler_cancel_dump_traceback_later_py(PyObject *self)
{
cancel_dump_traceback_later();
Py_RETURN_NONE;
}
#endif /* FAULTHANDLER_LATER */
#ifdef FAULTHANDLER_USER
static int
faulthandler_register(int signum, int chain, _Py_sighandler_t *p_previous)
{
#ifdef HAVE_SIGACTION
struct sigaction action;
action.sa_handler = faulthandler_user;
sigemptyset(&action.sa_mask);
/* if the signal is received while the kernel is executing a system
call, try to restart the system call instead of interrupting it and
return EINTR. */
action.sa_flags = SA_RESTART;
if (chain) {
/* do not prevent the signal from being received from within its
own signal handler */
action.sa_flags = SA_NODEFER;
}
#ifdef HAVE_SIGALTSTACK
if (stack.ss_sp != NULL) {
/* Call the signal handler on an alternate signal stack
provided by sigaltstack() */
action.sa_flags |= SA_ONSTACK;
}
#endif
return sigaction(signum, &action, p_previous);
#else
_Py_sighandler_t previous;
previous = signal(signum, faulthandler_user);
if (p_previous != NULL)
*p_previous = previous;
return (previous == SIG_ERR);
#endif
}
/* Handler of user signals (e.g. SIGUSR1).
Dump the traceback of the current thread, or of all threads if
thread.all_threads is true.
This function is signal safe and should only call signal safe functions. */
static void
faulthandler_user(int signum)
{
user_signal_t *user;
int save_errno = errno;
user = &user_signals[signum];
if (!user->enabled)
return;
faulthandler_dump_traceback(user->fd, user->all_threads, user->interp);
#ifdef HAVE_SIGACTION
if (user->chain) {
(void)sigaction(signum, &user->previous, NULL);
errno = save_errno;
/* call the previous signal handler */
raise(signum);
save_errno = errno;
(void)faulthandler_register(signum, user->chain, NULL);
errno = save_errno;
}
#else
if (user->chain) {
errno = save_errno;
/* call the previous signal handler */
user->previous(signum);
}
#endif
}
static int
check_signum(int signum)
{
unsigned int i;
for (i=0; i < faulthandler_nsignals; i++) {
if (faulthandler_handlers[i].signum == signum) {
PyErr_Format(PyExc_RuntimeError,
"signal %i cannot be registered, "
"use enable() instead",
signum);
return 0;
}
}
if (signum < 1 || Py_NSIG <= signum) {
PyErr_SetString(PyExc_ValueError, "signal number out of range");
return 0;
}
return 1;
}
static PyObject*
faulthandler_register_py(PyObject *self,
PyObject *args, PyObject *kwargs)
{
static char *kwlist[] = {"signum", "file", "all_threads", "chain", NULL};
int signum;
PyObject *file = NULL;
int all_threads = 1;
int chain = 0;
int fd;
user_signal_t *user;
_Py_sighandler_t previous;
PyThreadState *tstate;
int err;
if (!PyArg_ParseTupleAndKeywords(args, kwargs,
"i|Oii:register", kwlist,
&signum, &file, &all_threads, &chain))
return NULL;
if (!check_signum(signum))
return NULL;
tstate = get_thread_state();
if (tstate == NULL)
return NULL;
fd = faulthandler_get_fileno(&file);
if (fd < 0)
return NULL;
if (user_signals == NULL) {
user_signals = PyMem_Malloc(Py_NSIG * sizeof(user_signal_t));
if (user_signals == NULL)
return PyErr_NoMemory();
bzero(user_signals, Py_NSIG * sizeof(user_signal_t));
}
user = &user_signals[signum];
if (!user->enabled) {
err = faulthandler_register(signum, chain, &previous);
if (err) {
PyErr_SetFromErrno(PyExc_OSError);
return NULL;
}
user->previous = previous;
}
Py_XINCREF(file);
Py_XSETREF(user->file, file);
user->fd = fd;
user->all_threads = all_threads;
user->chain = chain;
user->interp = tstate->interp;
user->enabled = 1;
Py_RETURN_NONE;
}
static int
faulthandler_unregister(user_signal_t *user, int signum)
{
if (!user->enabled)
return 0;
user->enabled = 0;
#ifdef HAVE_SIGACTION
(void)sigaction(signum, &user->previous, NULL);
#else
(void)signal(signum, user->previous);
#endif
Py_CLEAR(user->file);
user->fd = -1;
return 1;
}
static PyObject*
faulthandler_unregister_py(PyObject *self, PyObject *args)
{
int signum;
user_signal_t *user;
int change;
if (!PyArg_ParseTuple(args, "i:unregister", &signum))
return NULL;
if (!check_signum(signum))
return NULL;
if (user_signals == NULL)
Py_RETURN_FALSE;
user = &user_signals[signum];
change = faulthandler_unregister(user, signum);
return PyBool_FromLong(change);
}
#endif /* FAULTHANDLER_USER */
static void
faulthandler_suppress_crash_report(void)
{
#ifdef MS_WINDOWS
UINT mode;
/* Configure Windows to not display the Windows Error Reporting dialog */
mode = SetErrorMode(SEM_NOGPFAULTERRORBOX);
SetErrorMode(mode | SEM_NOGPFAULTERRORBOX);
#endif
#ifdef HAVE_SYS_RESOURCE_H
struct rlimit rl;
/* Disable creation of core dump */
if (getrlimit(RLIMIT_CORE, &rl) == 0) {
rl.rlim_cur = 0;
setrlimit(RLIMIT_CORE, &rl);
}
#endif
#ifdef _MSC_VER
/* Visual Studio: configure abort() to not display an error message nor
open a popup asking to report the fault. */
_set_abort_behavior(0, _WRITE_ABORT_MSG | _CALL_REPORTFAULT);
#endif
}
static PyObject *
faulthandler_read_null(PyObject *self, PyObject *args)
{
volatile int *x;
volatile int y;
faulthandler_suppress_crash_report();
x = NULL;
y = *x;
return PyLong_FromLong(y);
}
static void
faulthandler_raise_sigsegv(void)
{
faulthandler_suppress_crash_report();
#if defined(MS_WINDOWS)
/* For SIGSEGV, faulthandler_fatal_error() restores the previous signal
handler and then gives back the execution flow to the program (without
explicitly calling the previous error handler). In a normal case, the
SIGSEGV was raised by the kernel because of a fault, and so if the
program retries to execute the same instruction, the fault will be
raised again.
Here the fault is simulated by a fake SIGSEGV signal raised by the
application. We have to raise SIGSEGV at lease twice: once for
faulthandler_fatal_error(), and one more time for the previous signal
handler. */
while(1)
raise(SIGSEGV);
#else
raise(SIGSEGV);
#endif
}
static PyObject *
faulthandler_sigsegv(PyObject *self, PyObject *args)
{
int release_gil = 0;
if (!PyArg_ParseTuple(args, "|i:_sigsegv", &release_gil))
return NULL;
if (release_gil) {
Py_BEGIN_ALLOW_THREADS
faulthandler_raise_sigsegv();
Py_END_ALLOW_THREADS
} else {
faulthandler_raise_sigsegv();
}
Py_RETURN_NONE;
}
#ifdef WITH_THREAD
static void
faulthandler_fatal_error_thread(void *plock)
{
PyThread_type_lock *lock = (PyThread_type_lock *)plock;
Py_FatalError("in new thread");
/* notify the caller that we are done */
PyThread_release_lock(lock);
}
static PyObject *
faulthandler_fatal_error_c_thread(PyObject *self, PyObject *args)
{
long thread;
PyThread_type_lock lock;
faulthandler_suppress_crash_report();
lock = PyThread_allocate_lock();
if (lock == NULL)
return PyErr_NoMemory();
PyThread_acquire_lock(lock, WAIT_LOCK);
thread = PyThread_start_new_thread(faulthandler_fatal_error_thread, lock);
if (thread == -1) {
PyThread_free_lock(lock);
PyErr_SetString(PyExc_RuntimeError, "unable to start the thread");
return NULL;
}
/* wait until the thread completes: it will never occur, since Py_FatalError()
exits the process immediately. */
PyThread_acquire_lock(lock, WAIT_LOCK);
PyThread_release_lock(lock);
PyThread_free_lock(lock);
Py_RETURN_NONE;
}
#endif
static PyObject *
faulthandler_sigfpe(PyObject *self, PyObject *args)
{
/* Do an integer division by zero: raise a SIGFPE on Intel CPU, but not on
PowerPC. Use volatile to disable compile-time optimizations. */
volatile int x = 1, y = 0, z;
faulthandler_suppress_crash_report();
z = x / y;
/* If the division by zero didn't raise a SIGFPE (e.g. on PowerPC),
raise it manually. */
raise(SIGFPE);
/* This line is never reached, but we pretend to make something with z
to silence a compiler warning. */
return PyLong_FromLong(z);
}
static PyObject *
faulthandler_sigabrt(PyObject *self, PyObject *args)
{
faulthandler_suppress_crash_report();
abort();
Py_RETURN_NONE;
}
static PyObject *
faulthandler_fatal_error_py(PyObject *self, PyObject *args)
{
char *message;
int release_gil = 0;
if (!PyArg_ParseTuple(args, "y|i:fatal_error", &message, &release_gil))
return NULL;
faulthandler_suppress_crash_report();
if (release_gil) {
Py_BEGIN_ALLOW_THREADS
Py_FatalError(message);
Py_END_ALLOW_THREADS
}
else {
Py_FatalError(message);
}
Py_RETURN_NONE;
}
#if defined(HAVE_SIGALTSTACK) && defined(HAVE_SIGACTION)
#define FAULTHANDLER_STACK_OVERFLOW
static dontinline
uintptr_t
stack_overflow(uintptr_t min_sp, uintptr_t max_sp, size_t *depth)
{
/* allocate 4096 bytes on the stack at each call */
unsigned char buffer[3500]; // [jart] or not
uintptr_t sp = (uintptr_t)&buffer;
*depth += 1;
if (sp < min_sp || max_sp < sp)
return sp;
buffer[0] = 1;
buffer[3500-1] = 0;
return stack_overflow(min_sp, max_sp, depth);
}
static PyObject *
faulthandler_stack_overflow(PyObject *self)
{
size_t depth, size;
uintptr_t sp = (uintptr_t)&depth;
uintptr_t stop;
faulthandler_suppress_crash_report();
depth = 0;
stop = stack_overflow(sp - STACK_OVERFLOW_MAX_SIZE,
sp + STACK_OVERFLOW_MAX_SIZE,
&depth);
if (sp < stop)
size = stop - sp;
else
size = sp - stop;
PyErr_Format(PyExc_RuntimeError,
"unable to raise a stack overflow (allocated %zu bytes "
"on the stack, %zu recursive calls)",
size, depth);
return NULL;
}
#endif /* defined(HAVE_SIGALTSTACK) && defined(HAVE_SIGACTION) */
static int
faulthandler_traverse(PyObject *module, visitproc visit, void *arg)
{
#ifdef FAULTHANDLER_USER
unsigned int signum;
#endif
#ifdef FAULTHANDLER_LATER
Py_VISIT(thread.file);
#endif
#ifdef FAULTHANDLER_USER
if (user_signals != NULL) {
for (signum=0; signum < Py_NSIG; signum++)
Py_VISIT(user_signals[signum].file);
}
#endif
Py_VISIT(fatal_error.file);
return 0;
}
#ifdef MS_WINDOWS
static PyObject *
faulthandler_raise_exception(PyObject *self, PyObject *args)
{
unsigned int code, flags = 0;
if (!PyArg_ParseTuple(args, "I|I:_raise_exception", &code, &flags))
return NULL;
faulthandler_suppress_crash_report();
RaiseException(code, flags, 0, NULL);
Py_RETURN_NONE;
}
#endif
PyDoc_STRVAR(module_doc,
"faulthandler module.");
static PyMethodDef module_methods[] = {
{"enable",
(PyCFunction)faulthandler_py_enable, METH_VARARGS|METH_KEYWORDS,
PyDoc_STR("enable(file=sys.stderr, all_threads=True): "
"enable the fault handler")},
{"disable", (PyCFunction)faulthandler_disable_py, METH_NOARGS,
PyDoc_STR("disable(): disable the fault handler")},
{"is_enabled", (PyCFunction)faulthandler_is_enabled, METH_NOARGS,
PyDoc_STR("is_enabled()->bool: check if the handler is enabled")},
{"dump_traceback",
(PyCFunction)faulthandler_dump_traceback_py, METH_VARARGS|METH_KEYWORDS,
PyDoc_STR("dump_traceback(file=sys.stderr, all_threads=True): "
"dump the traceback of the current thread, or of all threads "
"if all_threads is True, into file")},
#ifdef FAULTHANDLER_LATER
{"dump_traceback_later",
(PyCFunction)faulthandler_dump_traceback_later, METH_VARARGS|METH_KEYWORDS,
PyDoc_STR("dump_traceback_later(timeout, repeat=False, file=sys.stderrn, exit=False):\n"
"dump the traceback of all threads in timeout seconds,\n"
"or each timeout seconds if repeat is True. If exit is True, "
"call _exit(1) which is not safe.")},
{"cancel_dump_traceback_later",
(PyCFunction)faulthandler_cancel_dump_traceback_later_py, METH_NOARGS,
PyDoc_STR("cancel_dump_traceback_later():\ncancel the previous call "
"to dump_traceback_later().")},
#endif
#ifdef FAULTHANDLER_USER
{"register",
(PyCFunction)faulthandler_register_py, METH_VARARGS|METH_KEYWORDS,
PyDoc_STR("register(signum, file=sys.stderr, all_threads=True, chain=False): "
"register a handler for the signal 'signum': dump the "
"traceback of the current thread, or of all threads if "
"all_threads is True, into file")},
{"unregister",
faulthandler_unregister_py, METH_VARARGS|METH_KEYWORDS,
PyDoc_STR("unregister(signum): unregister the handler of the signal "
"'signum' registered by register()")},
#endif
{"_read_null", faulthandler_read_null, METH_NOARGS,
PyDoc_STR("_read_null(): read from NULL, raise "
"a SIGSEGV or SIGBUS signal depending on the platform")},
{"_sigsegv", faulthandler_sigsegv, METH_VARARGS,
PyDoc_STR("_sigsegv(release_gil=False): raise a SIGSEGV signal")},
#ifdef WITH_THREAD
{"_fatal_error_c_thread", faulthandler_fatal_error_c_thread, METH_NOARGS,
PyDoc_STR("fatal_error_c_thread(): "
"call Py_FatalError() in a new C thread.")},
#endif
{"_sigabrt", faulthandler_sigabrt, METH_NOARGS,
PyDoc_STR("_sigabrt(): raise a SIGABRT signal")},
{"_sigfpe", (PyCFunction)faulthandler_sigfpe, METH_NOARGS,
PyDoc_STR("_sigfpe(): raise a SIGFPE signal")},
{"_fatal_error", faulthandler_fatal_error_py, METH_VARARGS,
PyDoc_STR("_fatal_error(message): call Py_FatalError(message)")},
#ifdef FAULTHANDLER_STACK_OVERFLOW
{"_stack_overflow", (PyCFunction)faulthandler_stack_overflow, METH_NOARGS,
PyDoc_STR("_stack_overflow(): recursive call to raise a stack overflow")},
#endif
#ifdef MS_WINDOWS
{"_raise_exception", faulthandler_raise_exception, METH_VARARGS,
PyDoc_STR("raise_exception(code, flags=0): Call RaiseException(code, flags).")},
#endif
{NULL, NULL} /* sentinel */
};
static struct PyModuleDef module_def = {
PyModuleDef_HEAD_INIT,
"faulthandler",
module_doc,
0, /* non-negative size to be able to unload the module */
module_methods,
NULL,
faulthandler_traverse,
NULL,
NULL
};
PyMODINIT_FUNC
PyInit_faulthandler(void)
{
PyObject *m = PyModule_Create(&module_def);
if (m == NULL)
return NULL;
/* Add constants for unit tests */
#ifdef MS_WINDOWS
/* RaiseException() codes (prefixed by an underscore) */
if (PyModule_AddIntConstant(m, "_EXCEPTION_ACCESS_VIOLATION",
EXCEPTION_ACCESS_VIOLATION))
return NULL;
if (PyModule_AddIntConstant(m, "_EXCEPTION_INT_DIVIDE_BY_ZERO",
EXCEPTION_INT_DIVIDE_BY_ZERO))
return NULL;
if (PyModule_AddIntConstant(m, "_EXCEPTION_STACK_OVERFLOW",
EXCEPTION_STACK_OVERFLOW))
return NULL;
/* RaiseException() flags (prefixed by an underscore) */
if (PyModule_AddIntConstant(m, "_EXCEPTION_NONCONTINUABLE",
EXCEPTION_NONCONTINUABLE))
return NULL;
if (PyModule_AddIntConstant(m, "_EXCEPTION_NONCONTINUABLE_EXCEPTION",
EXCEPTION_NONCONTINUABLE_EXCEPTION))
return NULL;
#endif
return m;
}
/* Call faulthandler.enable() if the PYTHONFAULTHANDLER environment variable
is defined, or if sys._xoptions has a 'faulthandler' key. */
static int
faulthandler_env_options(void)
{
PyObject *xoptions, *key, *module, *res;
char *p;
if (!((p = Py_GETENV("PYTHONFAULTHANDLER")) && *p != '\0')) {
/* PYTHONFAULTHANDLER environment variable is missing
or an empty string */
int has_key;
xoptions = PySys_GetXOptions();
if (xoptions == NULL)
return -1;
key = PyUnicode_FromString("faulthandler");
if (key == NULL)
return -1;
has_key = PyDict_Contains(xoptions, key);
Py_DECREF(key);
if (has_key <= 0)
return has_key;
}
module = PyImport_ImportModule("faulthandler");
if (module == NULL) {
return -1;
}
res = _PyObject_CallMethodId(module, &PyId_enable, NULL);
Py_DECREF(module);
if (res == NULL)
return -1;
Py_DECREF(res);
return 0;
}
int _PyFaulthandler_Init(void)
{
#ifdef HAVE_SIGALTSTACK
int err;
/* Try to allocate an alternate stack for faulthandler() signal handler to
* be able to allocate memory on the stack, even on a stack overflow. If it
* fails, ignore the error. */
stack.ss_flags = 0;
stack.ss_size = SIGSTKSZ;
stack.ss_sp = PyMem_Malloc(stack.ss_size);
if (stack.ss_sp != NULL) {
err = sigaltstack(&stack, &old_stack);
if (err) {
PyMem_Free(stack.ss_sp);
stack.ss_sp = NULL;
}
}
#endif
#ifdef FAULTHANDLER_LATER
thread.file = NULL;
thread.cancel_event = PyThread_allocate_lock();
thread.running = PyThread_allocate_lock();
if (!thread.cancel_event || !thread.running) {
PyErr_SetString(PyExc_RuntimeError,
"could not allocate locks for faulthandler");
return -1;
}
PyThread_acquire_lock(thread.cancel_event, 1);
#endif
faulthandler_handlers_init();
return faulthandler_env_options();
}
void _PyFaulthandler_Fini(void)
{
#ifdef FAULTHANDLER_USER
unsigned int signum;
#endif
#ifdef FAULTHANDLER_LATER
/* later */
if (thread.cancel_event) {
cancel_dump_traceback_later();
PyThread_release_lock(thread.cancel_event);
PyThread_free_lock(thread.cancel_event);
thread.cancel_event = NULL;
}
if (thread.running) {
PyThread_free_lock(thread.running);
thread.running = NULL;
}
#endif
#ifdef FAULTHANDLER_USER
/* user */
if (user_signals != NULL) {
for (signum=0; signum < Py_NSIG; signum++)
faulthandler_unregister(&user_signals[signum], signum);
PyMem_Free(user_signals);
user_signals = NULL;
}
#endif
/* fatal */
faulthandler_disable();
#ifdef HAVE_SIGALTSTACK
if (stack.ss_sp != NULL) {
/* Fetch the current alt stack */
stack_t current_stack = {};
if (sigaltstack(NULL, ¤t_stack) == 0) {
if (current_stack.ss_sp == stack.ss_sp) {
/* The current alt stack is the one that we installed.
It is safe to restore the old stack that we found when
we installed ours */
sigaltstack(&old_stack, NULL);
} else {
/* Someone switched to a different alt stack and didn't
restore ours when they were done (if they're done).
There's not much we can do in this unlikely case */
}
}
PyMem_Free(stack.ss_sp);
stack.ss_sp = NULL;
}
#endif
}
_Section(".rodata.pytab.1") const struct _inittab _PyImport_Inittab_faulthandler = {
"faulthandler",
PyInit_faulthandler,
};
| 41,479 | 1,441 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Modules/xxlimited.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:8;coding:utf-8 -*-â
âvi: set net ft=c ts=4 sts=4 sw=4 fenc=utf-8 :viâ
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ¡
â Python 3 â
â https://docs.python.org/3/license.html â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
#include "third_party/python/Include/dictobject.h"
#include "third_party/python/Include/longobject.h"
#include "third_party/python/Include/methodobject.h"
#include "third_party/python/Include/modsupport.h"
#include "third_party/python/Include/object.h"
#include "third_party/python/Include/objimpl.h"
#include "third_party/python/Include/typeslots.h"
#include "third_party/python/Include/unicodeobject.h"
#include "third_party/python/Include/yoink.h"
/* clang-format off */
PYTHON_PROVIDE("xxlimited");
PYTHON_PROVIDE("xxlimited.Null");
PYTHON_PROVIDE("xxlimited.Str");
PYTHON_PROVIDE("xxlimited.Xxo");
PYTHON_PROVIDE("xxlimited.error");
PYTHON_PROVIDE("xxlimited.foo");
PYTHON_PROVIDE("xxlimited.new");
PYTHON_PROVIDE("xxlimited.roj");
/* Use this file as a template to start implementing a module that
also declares object types. All occurrences of 'Xxo' should be changed
to something reasonable for your objects. After that, all other
occurrences of 'xx' should be changed to something reasonable for your
module. If your module is named foo your sourcefile should be named
foomodule.c.
You will probably want to delete all references to 'x_attr' and add
your own types of attributes instead. Maybe you want to name your
local variables other than 'self'. If your object type is needed in
other files, you'll have to create a file "foobarobject.h"; see
floatobject.h for an example. */
/* Xxo objects */
static PyObject *ErrorObject;
typedef struct {
PyObject_HEAD
PyObject *x_attr; /* Attributes dictionary */
} XxoObject;
static PyObject *Xxo_Type;
#define XxoObject_Check(v) (Py_TYPE(v) == Xxo_Type)
static XxoObject *
newXxoObject(PyObject *arg)
{
XxoObject *self;
self = PyObject_GC_New(XxoObject, (PyTypeObject*)Xxo_Type);
if (self == NULL)
return NULL;
self->x_attr = NULL;
return self;
}
/* Xxo methods */
static int
Xxo_traverse(XxoObject *self, visitproc visit, void *arg)
{
Py_VISIT(self->x_attr);
return 0;
}
static void
Xxo_finalize(XxoObject *self)
{
Py_CLEAR(self->x_attr);
}
static PyObject *
Xxo_demo(XxoObject *self, PyObject *args)
{
PyObject *o = NULL;
if (!PyArg_ParseTuple(args, "|O:demo", &o))
return NULL;
/* Test availability of fast type checks */
if (o != NULL && PyUnicode_Check(o)) {
Py_INCREF(o);
return o;
}
Py_INCREF(Py_None);
return Py_None;
}
static PyMethodDef Xxo_methods[] = {
{"demo", (PyCFunction)Xxo_demo, METH_VARARGS,
PyDoc_STR("demo() -> None")},
{NULL, NULL} /* sentinel */
};
static PyObject *
Xxo_getattro(XxoObject *self, PyObject *name)
{
if (self->x_attr != NULL) {
PyObject *v = PyDict_GetItem(self->x_attr, name);
if (v != NULL) {
Py_INCREF(v);
return v;
}
}
return PyObject_GenericGetAttr((PyObject *)self, name);
}
static int
Xxo_setattr(XxoObject *self, const 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);
}
static PyType_Slot Xxo_Type_slots[] = {
{Py_tp_doc, "The Xxo type"},
{Py_tp_traverse, Xxo_traverse},
{Py_tp_finalize, Xxo_finalize},
{Py_tp_getattro, Xxo_getattro},
{Py_tp_setattr, Xxo_setattr},
{Py_tp_methods, Xxo_methods},
{0, 0},
};
static PyType_Spec Xxo_Type_spec = {
"xxlimited.Xxo",
sizeof(XxoObject),
0,
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC | Py_TPFLAGS_HAVE_FINALIZE,
Xxo_Type_slots
};
/* --------------------------------------------------------------------- */
/* Function of two integers returning integer */
PyDoc_STRVAR(xx_foo_doc,
"foo(i,j)\n\
\n\
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 PyLong_FromLong(res);
}
/* Function of no arguments returning new Xxo object */
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;
}
/* Test bad format character */
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;
}
/* ---------- */
static PyType_Slot Str_Type_slots[] = {
{Py_tp_base, NULL}, /* filled out in module init function */
{0, 0},
};
static PyType_Spec Str_Type_spec = {
"xxlimited.Str",
0,
0,
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
Str_Type_slots
};
/* ---------- */
static PyObject *
null_richcompare(PyObject *self, PyObject *other, int op)
{
Py_RETURN_NOTIMPLEMENTED;
}
static PyType_Slot Null_Type_slots[] = {
{Py_tp_base, NULL}, /* filled out in module init */
{Py_tp_new, NULL},
{Py_tp_richcompare, null_richcompare},
{0, 0}
};
static PyType_Spec Null_Type_spec = {
"xxlimited.Null",
0, /* basicsize */
0, /* itemsize */
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
Null_Type_slots
};
/* ---------- */
/* 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")},
{NULL, NULL} /* sentinel */
};
PyDoc_STRVAR(module_doc,
"This is a template module just for instruction.");
static int
xx_modexec(PyObject *m)
{
PyObject *o;
/* Due to cross platform compiler issues the slots must be filled
* here. It's required for portability to Windows without requiring
* C++. */
Null_Type_slots[0].pfunc = &PyBaseObject_Type;
Null_Type_slots[1].pfunc = PyType_GenericNew;
Str_Type_slots[0].pfunc = &PyUnicode_Type;
Xxo_Type = PyType_FromSpec(&Xxo_Type_spec);
if (Xxo_Type == NULL)
goto fail;
/* Add some symbolic constants to the module */
if (ErrorObject == NULL) {
ErrorObject = PyErr_NewException("xxlimited.error", NULL, NULL);
if (ErrorObject == NULL)
goto fail;
}
Py_INCREF(ErrorObject);
PyModule_AddObject(m, "error", ErrorObject);
/* Add Xxo */
o = PyType_FromSpec(&Xxo_Type_spec);
if (o == NULL)
goto fail;
PyModule_AddObject(m, "Xxo", o);
/* Add Str */
o = PyType_FromSpec(&Str_Type_spec);
if (o == NULL)
goto fail;
PyModule_AddObject(m, "Str", o);
/* Add Null */
o = PyType_FromSpec(&Null_Type_spec);
if (o == NULL)
goto fail;
PyModule_AddObject(m, "Null", o);
return 0;
fail:
Py_XDECREF(m);
return -1;
}
static PyModuleDef_Slot xx_slots[] = {
{Py_mod_exec, xx_modexec},
{0, NULL}
};
static struct PyModuleDef xxmodule = {
PyModuleDef_HEAD_INIT,
"xxlimited",
module_doc,
0,
xx_methods,
xx_slots,
NULL,
NULL,
NULL
};
/* Export function for the module (*must* be called PyInit_xx) */
PyMODINIT_FUNC
PyInit_xxlimited(void)
{
return PyModuleDef_Init(&xxmodule);
}
| 8,623 | 328 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Modules/_lsprof.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:8;coding:utf-8 -*-â
âvi: set net ft=c ts=4 sts=4 sw=4 fenc=utf-8 :viâ
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ¡
â Python 3 â
â https://docs.python.org/3/license.html â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
#include "libc/calls/struct/timeval.h"
#include "libc/time/struct/tm.h"
#include "libc/time/time.h"
#include "third_party/python/Include/abstract.h"
#include "third_party/python/Include/ceval.h"
#include "third_party/python/Include/dictobject.h"
#include "third_party/python/Include/floatobject.h"
#include "third_party/python/Include/frameobject.h"
#include "third_party/python/Include/import.h"
#include "third_party/python/Include/longobject.h"
#include "third_party/python/Include/modsupport.h"
#include "third_party/python/Include/objimpl.h"
#include "third_party/python/Include/pyerrors.h"
#include "third_party/python/Include/pymacro.h"
#include "third_party/python/Include/pymem.h"
#include "third_party/python/Include/structseq.h"
#include "third_party/python/Include/unicodeobject.h"
#include "third_party/python/Include/yoink.h"
#include "third_party/python/Modules/rotatingtree.h"
/* clang-format off */
PYTHON_PROVIDE("_lsprof");
PYTHON_PROVIDE("_lsprof.Profiler");
PYTHON_PROVIDE("_lsprof.profiler_entry");
PYTHON_PROVIDE("_lsprof.profiler_subentry");
/*** Selection of a high-precision timer ***/
#ifdef MS_WINDOWS
static long long
hpTimer(void)
{
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 */
}
#else /* !MS_WINDOWS */
static long long
hpTimer(void)
{
struct timeval tv;
long long ret;
#ifdef GETTIMEOFDAY_NO_TZ
gettimeofday(&tv);
#else
gettimeofday(&tv, (struct timezone *)NULL);
#endif
ret = tv.tv_sec;
ret = ret * 1000000 + tv.tv_usec;
return ret;
}
static double
hpTimerUnit(void)
{
return 0.000001;
}
#endif /* MS_WINDOWS */
/************************************************************/
/* Written by Brett Rosen and Ted Czotter */
struct _ProfilerEntry;
/* represents a function called from another function */
typedef struct _ProfilerSubEntry {
rotating_node_t header;
long long tt;
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 */
long long tt; /* total time in this entry */
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 {
long long t0;
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;
} ProfilerObject;
#define POF_ENABLED 0x001
#define POF_SUBCALLS 0x002
#define POF_BUILTINS 0x004
#define POF_NOMEMORY 0x100
static PyTypeObject PyProfiler_Type;
#define PyProfiler_Check(op) PyObject_TypeCheck(op, &PyProfiler_Type)
#define PyProfiler_CheckExact(op) (Py_TYPE(op) == &PyProfiler_Type)
/*** External Timers ***/
#define DOUBLE_TIMER_PRECISION 4294967296.0
static PyObject *empty_tuple;
static long long CallExternalTimer(ProfilerObject *pObj)
{
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 long long internally
we convert it to a large integer */
double val = PyFloat_AsDouble(o);
/* error handling delayed to the code below */
result = (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())
/*** 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;
PyObject *modname = NULL;
if (mod != NULL) {
if (PyUnicode_Check(mod)) {
modname = mod;
Py_INCREF(modname);
}
else if (PyModule_Check(mod)) {
modname = PyModule_GetNameObject(mod);
if (modname == NULL)
PyErr_Clear();
}
}
if (modname != NULL) {
if (!_PyUnicode_EqualToASCIIString(modname, "builtins")) {
PyObject *result;
result = PyUnicode_FromFormat("<%U.%s>", modname,
fn->m_ml->ml_name);
Py_DECREF(modname);
return result;
}
Py_DECREF(modname);
}
return PyUnicode_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 = PyUnicode_FromString(fn->m_ml->ml_name);
PyObject *modname = fn->m_module;
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;
}
}
/* Otherwise, use __module__ */
PyErr_Clear();
if (modname != NULL && PyUnicode_Check(modname))
return PyUnicode_FromFormat("<built-in method %S.%s>",
modname, fn->m_ml->ml_name);
else
return PyUnicode_FromFormat("<built-in method %s>",
fn->m_ml->ml_name);
}
}
static ProfilerEntry*
newProfilerEntry(ProfilerObject *pObj, void *key, PyObject *userObj)
{
ProfilerEntry *self;
self = (ProfilerEntry*) PyMem_Malloc(sizeof(ProfilerEntry));
if (self == NULL) {
pObj->flags |= POF_NOMEMORY;
return NULL;
}
userObj = normalizeUserObj(userObj);
if (userObj == NULL) {
PyErr_Clear();
PyMem_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);
}
static ProfilerSubEntry *
getSubEntry(ProfilerObject *pObj, ProfilerEntry *caller, ProfilerEntry* entry)
{
return (ProfilerSubEntry*) RotatingTree_Get(&caller->calls,
(void *)entry);
}
static ProfilerSubEntry *
newSubEntry(ProfilerObject *pObj, ProfilerEntry *caller, ProfilerEntry* entry)
{
ProfilerSubEntry *self;
self = (ProfilerSubEntry*) PyMem_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;
PyMem_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);
PyMem_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) {
PyMem_Free(pObj->currentProfilerContext);
pObj->currentProfilerContext = NULL;
}
while (pObj->freelistProfilerContext) {
ProfilerContext *c = pObj->freelistProfilerContext;
pObj->freelistProfilerContext = c->previous;
PyMem_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);
}
static void
Stop(ProfilerObject *pObj, ProfilerContext *self, ProfilerEntry *entry)
{
long long tt = CALL_TIMER(pObj) - self->t0;
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*)
PyMem_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);
}
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;
}
static int
profiler_callback(PyObject *self, PyFrameObject *frame, int what,
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. */
/* 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;
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;
}
/************************************************************/
static PyStructSequence_Field profiler_entry_fields[] = {
{"code", PyDoc_STR("code object or built-in function name")},
{"callcount", PyDoc_STR("how many times this was called")},
{"reccallcount", PyDoc_STR("how many times called recursively")},
{"totaltime", PyDoc_STR("total time in this entry")},
{"inlinetime", PyDoc_STR("inline time in this entry (not in subcalls)")},
{"calls", PyDoc_STR("details of the calls")},
{0}
};
static PyStructSequence_Field profiler_subentry_fields[] = {
{"code", PyDoc_STR("called code object or built-in function name")},
{"callcount", PyDoc_STR("how many times this is called")},
{"reccallcount", PyDoc_STR("how many times this is called recursively")},
{"totaltime", PyDoc_STR("total time spent in this call")},
{"inlinetime", PyDoc_STR("inline time (not in further subcalls)")},
{0}
};
static PyStructSequence_Desc profiler_entry_desc = {
"_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
};
static int initialized;
static PyTypeObject StatsEntryType;
static PyTypeObject StatsSubEntryType;
typedef struct {
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;
}
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;
}
PyDoc_STRVAR(getstats_doc, "\
getstats() -> list of profiler_entry objects\n\
\n\
Return all information collected by the profiler.\n\
Each profiler_entry is a tuple-like object with the\n\
following attributes:\n\
\n\
code code object\n\
callcount how many times this was called\n\
reccallcount how many times called recursively\n\
totaltime total time in this entry\n\
inlinetime inline time in this entry (not in subcalls)\n\
calls details of the calls\n\
\n\
The calls attribute is either None or a list of\n\
profiler_subentry objects:\n\
\n\
code called code object\n\
callcount how many times this is called\n\
reccallcount how many times this is called recursively\n\
totaltime total time spent in this call\n\
inlinetime inline time (not in further subcalls)\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;
}
static int
setSubcalls(ProfilerObject *pObj, int nvalue)
{
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) {
pObj->flags |= POF_BUILTINS;
}
return 0;
}
PyDoc_STRVAR(enable_doc, "\
enable(subcalls=True, builtins=True)\n\
\n\
Start collecting profiling information.\n\
If 'subcalls' is True, also records for each function\n\
statistics separated according to its current caller.\n\
If 'builtins' is True, records the time spent in\n\
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;
}
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)
PyMem_Free(pContext);
}
}
PyDoc_STRVAR(disable_doc, "\
disable()\n\
\n\
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;
}
PyDoc_STRVAR(clear_doc, "\
clear()\n\
\n\
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;
}
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);
}
static int
profiler_init(ProfilerObject *pObj, PyObject *args, PyObject *kw)
{
PyObject *timer = NULL;
double timeunit = 0.0;
int subcalls = 1;
int builtins = 1;
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;
pObj->externalTimerUnit = timeunit;
Py_XINCREF(timer);
Py_XSETREF(pObj->externalTimer, timer);
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}
};
PyDoc_STRVAR(profiler_doc, "\
Profiler(timer=None, timeunit=None, subcalls=True, builtins=True)\n\
\n\
Builds a profiler object using the specified timer function.\n\
The default timer is a fast built-in one based on real time.\n\
For custom timer functions returning integers, timeunit can\n\
be a float specifying a scale (i.e. how long each integer unit\n\
is, in seconds).\n\
");
static PyTypeObject PyProfiler_Type = {
PyVarObject_HEAD_INIT(NULL, 0)
"_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_reserved */
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}
};
static struct PyModuleDef _lsprofmodule = {
PyModuleDef_HEAD_INIT,
"_lsprof",
"Fast profiler",
-1,
moduleMethods,
NULL,
NULL,
NULL,
NULL
};
PyMODINIT_FUNC
PyInit__lsprof(void)
{
PyObject *module, *d;
module = PyModule_Create(&_lsprofmodule);
if (module == NULL)
return NULL;
d = PyModule_GetDict(module);
if (PyType_Ready(&PyProfiler_Type) < 0)
return NULL;
PyDict_SetItemString(d, "Profiler", (PyObject *)&PyProfiler_Type);
if (!initialized) {
if (PyStructSequence_InitType2(&StatsEntryType,
&profiler_entry_desc) < 0)
return NULL;
if (PyStructSequence_InitType2(&StatsSubEntryType,
&profiler_subentry_desc) < 0)
return NULL;
}
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;
return module;
}
_Section(".rodata.pytab.1") const struct _inittab _PyImport_Inittab__lsprof = {
"_lsprof",
PyInit__lsprof,
};
| 29,422 | 916 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Modules/zipimport.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:8;coding:utf-8 -*-â
âvi: set net ft=c ts=4 sts=4 sw=4 fenc=utf-8 :viâ
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ¡
â Python 3 â
â https://docs.python.org/3/license.html â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
#include "libc/intrin/bits.h"
#include "libc/calls/calls.h"
#include "libc/calls/weirdtypes.h"
#include "libc/sysv/consts/s.h"
#include "libc/time/struct/tm.h"
#include "libc/time/time.h"
#include "third_party/python/Include/abstract.h"
#include "third_party/python/Include/boolobject.h"
#include "third_party/python/Include/bytesobject.h"
#include "third_party/python/Include/code.h"
#include "third_party/python/Include/compile.h"
#include "third_party/python/Include/dictobject.h"
#include "third_party/python/Include/fileutils.h"
#include "third_party/python/Include/import.h"
#include "third_party/python/Include/longobject.h"
#include "third_party/python/Include/marshal.h"
#include "third_party/python/Include/modsupport.h"
#include "third_party/python/Include/objimpl.h"
#include "third_party/python/Include/osdefs.h"
#include "third_party/python/Include/patchlevel.h"
#include "third_party/python/Include/pgenheaders.h"
#include "third_party/python/Include/pydebug.h"
#include "third_party/python/Include/pyerrors.h"
#include "third_party/python/Include/pymem.h"
#include "third_party/python/Include/pystate.h"
#include "third_party/python/Include/pythonrun.h"
#include "third_party/python/Include/structmember.h"
#include "third_party/python/Include/sysmodule.h"
#include "third_party/python/Include/unicodeobject.h"
#include "third_party/python/Include/yoink.h"
/* clang-format off */
PYTHON_PROVIDE("zipimport");
PYTHON_PROVIDE("zipimport.ZipImportError");
PYTHON_PROVIDE("zipimport._zip_directory_cache");
PYTHON_PROVIDE("zipimport.zipimporter");
PYTHON_YOINK("encodings.ascii");
PYTHON_YOINK("encodings.cp437");
PYTHON_YOINK("encodings.utf_8");
#define IS_SOURCE 0x0
#define IS_BYTECODE 0x1
#define IS_PACKAGE 0x2
struct st_zip_searchorder {
char suffix[14];
int type;
};
#ifdef ALTSEP
_Py_IDENTIFIER(replace);
#endif
/* zip_searchorder defines how we search for a module in the Zip
archive: we first search for a package __init__, then for
non-package .pyc, and .py entries. The .pyc entries
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__.py", IS_PACKAGE | IS_SOURCE},
{".pyc", IS_BYTECODE},
{".py", IS_SOURCE},
{"", 0}
};
/* zipimporter object definition and support */
typedef struct _zipimporter ZipImporter;
struct _zipimporter {
PyObject_HEAD
PyObject *archive; /* pathname of the Zip archive,
decoded from the filesystem encoding */
PyObject *prefix; /* file prefix: "a/sub/directory/",
encoded to the filesystem encoding */
PyObject *files; /* dict with file info {path: toc_entry} */
};
static PyObject *ZipImportError;
/* read_directory() cache */
static PyObject *zip_directory_cache = NULL;
/* forward decls */
static PyObject *read_directory(PyObject *archive);
static PyObject *get_data(PyObject *archive, PyObject *toc_entry);
static PyObject *get_module_code(ZipImporter *self, PyObject *fullname,
int *p_ispackage, PyObject **p_modpath);
#define ZipImporter_Check(op) PyObject_TypeCheck(op, &ZipImporter_Type)
/* zipimporter.__init__
Split the "subdirectory" from the Zip archive path, lookup a matching
entry in sys.path_importer_cache, fetch the file directory from there
if found, or else read it from the archive. */
static int
zipimporter_init(ZipImporter *self, PyObject *args, PyObject *kwds)
{
PyObject *path, *files, *tmp;
PyObject *filename = NULL;
Py_ssize_t len, flen;
if (!_PyArg_NoKeywords("zipimporter()", kwds))
return -1;
if (!PyArg_ParseTuple(args, "O&:zipimporter",
PyUnicode_FSDecoder, &path))
return -1;
if (PyUnicode_READY(path) == -1)
return -1;
len = PyUnicode_GET_LENGTH(path);
if (len == 0) {
PyErr_SetString(ZipImportError, "archive path is empty");
goto error;
}
#ifdef ALTSEP
tmp = _PyObject_CallMethodId(path, &PyId_replace, "CC", ALTSEP, SEP);
if (!tmp)
goto error;
Py_DECREF(path);
path = tmp;
#endif
filename = path;
Py_INCREF(filename);
flen = len;
for (;;) {
struct stat statbuf;
int rv;
rv = _Py_stat(filename, &statbuf);
if (rv == -2)
goto error;
if (rv == 0) {
/* it exists */
if (!S_ISREG(statbuf.st_mode))
/* it's a not file */
Py_CLEAR(filename);
break;
}
Py_CLEAR(filename);
/* back up one path element */
flen = PyUnicode_FindChar(path, SEP, 0, flen, -1);
if (flen == -1)
break;
filename = PyUnicode_Substring(path, 0, flen);
if (filename == NULL)
goto error;
}
if (filename == NULL) {
PyErr_SetString(ZipImportError, "not a Zip file");
goto error;
}
if (PyUnicode_READY(filename) < 0)
goto error;
files = PyDict_GetItem(zip_directory_cache, filename);
if (files == NULL) {
files = read_directory(filename);
if (files == NULL)
goto error;
if (PyDict_SetItem(zip_directory_cache, filename, files) != 0)
goto error;
}
else
Py_INCREF(files);
self->files = files;
/* Transfer reference */
self->archive = filename;
filename = NULL;
/* Check if there is a prefix directory following the filename. */
if (flen != len) {
tmp = PyUnicode_Substring(path, flen+1,
PyUnicode_GET_LENGTH(path));
if (tmp == NULL)
goto error;
self->prefix = tmp;
if (PyUnicode_READ_CHAR(path, len-1) != SEP) {
/* add trailing SEP */
tmp = PyUnicode_FromFormat("%U%c", self->prefix, SEP);
if (tmp == NULL)
goto error;
Py_SETREF(self->prefix, tmp);
}
}
else
self->prefix = PyUnicode_New(0, 0);
Py_DECREF(path);
return 0;
error:
Py_DECREF(path);
Py_XDECREF(filename);
return -1;
}
/* GC support. */
static int
zipimporter_traverse(PyObject *obj, visitproc visit, void *arg)
{
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);
}
static PyObject *
zipimporter_repr(ZipImporter *self)
{
if (self->archive == NULL)
return PyUnicode_FromString("<zipimporter object \"???\">");
else if (self->prefix != NULL && PyUnicode_GET_LENGTH(self->prefix) != 0)
return PyUnicode_FromFormat("<zipimporter object \"%U%c%U\">",
self->archive, SEP, self->prefix);
else
return PyUnicode_FromFormat("<zipimporter object \"%U\">",
self->archive);
}
/* return fullname.split(".")[-1] */
static PyObject *
get_subname(PyObject *fullname)
{
Py_ssize_t len, dot;
if (PyUnicode_READY(fullname) < 0)
return NULL;
len = PyUnicode_GET_LENGTH(fullname);
dot = PyUnicode_FindChar(fullname, '.', 0, len, -1);
if (dot == -1) {
Py_INCREF(fullname);
return fullname;
} else
return PyUnicode_Substring(fullname, dot+1, len);
}
/* Given a (sub)modulename, write the potential file path in the
archive (without extension) to the path buffer. Return the
length of the resulting string.
return self.prefix + name.replace('.', os.sep) */
static PyObject*
make_filename(PyObject *prefix, PyObject *name)
{
PyObject *pathobj;
Py_UCS4 *p, *buf;
Py_ssize_t len;
len = PyUnicode_GET_LENGTH(prefix) + PyUnicode_GET_LENGTH(name) + 1;
p = buf = PyMem_New(Py_UCS4, len);
if (buf == NULL) {
PyErr_NoMemory();
return NULL;
}
if (!PyUnicode_AsUCS4(prefix, p, len, 0)) {
PyMem_Free(buf);
return NULL;
}
p += PyUnicode_GET_LENGTH(prefix);
len -= PyUnicode_GET_LENGTH(prefix);
if (!PyUnicode_AsUCS4(name, p, len, 1)) {
PyMem_Free(buf);
return NULL;
}
for (; *p; p++) {
if (*p == '.')
*p = SEP;
}
pathobj = PyUnicode_FromKindAndData(PyUnicode_4BYTE_KIND,
buf, p-buf);
PyMem_Free(buf);
return pathobj;
}
enum zi_module_info {
MI_ERROR,
MI_NOT_FOUND,
MI_MODULE,
MI_PACKAGE
};
/* Does this path represent a directory?
on error, return < 0
if not a dir, return 0
if a dir, return 1
*/
static int
check_is_directory(ZipImporter *self, PyObject* prefix, PyObject *path)
{
PyObject *dirpath;
int res;
/* See if this is a "directory". If so, it's eligible to be part
of a namespace package. We test by seeing if the name, with an
appended path separator, exists. */
dirpath = PyUnicode_FromFormat("%U%U%c", prefix, path, SEP);
if (dirpath == NULL)
return -1;
/* If dirpath is present in self->files, we have a directory. */
res = PyDict_Contains(self->files, dirpath);
Py_DECREF(dirpath);
return res;
}
/* Return some information about a module. */
static enum zi_module_info
get_module_info(ZipImporter *self, PyObject *fullname)
{
PyObject *subname;
PyObject *path, *fullpath, *item;
struct st_zip_searchorder *zso;
subname = get_subname(fullname);
if (subname == NULL)
return MI_ERROR;
path = make_filename(self->prefix, subname);
Py_DECREF(subname);
if (path == NULL)
return MI_ERROR;
for (zso = zip_searchorder; *zso->suffix; zso++) {
fullpath = PyUnicode_FromFormat("%U%s", path, zso->suffix);
if (fullpath == NULL) {
Py_DECREF(path);
return MI_ERROR;
}
item = PyDict_GetItem(self->files, fullpath);
Py_DECREF(fullpath);
if (item != NULL) {
Py_DECREF(path);
if (zso->type & IS_PACKAGE)
return MI_PACKAGE;
else
return MI_MODULE;
}
}
Py_DECREF(path);
return MI_NOT_FOUND;
}
typedef enum {
FL_ERROR = -1, /* error */
FL_NOT_FOUND, /* no loader or namespace portions found */
FL_MODULE_FOUND, /* module/package found */
FL_NS_FOUND /* namespace portion found: */
/* *namespace_portion will point to the name */
} find_loader_result;
/* The guts of "find_loader" and "find_module".
*/
static find_loader_result
find_loader(ZipImporter *self, PyObject *fullname, PyObject **namespace_portion)
{
enum zi_module_info mi;
*namespace_portion = NULL;
mi = get_module_info(self, fullname);
if (mi == MI_ERROR)
return FL_ERROR;
if (mi == MI_NOT_FOUND) {
/* Not a module or regular package. See if this is a directory, and
therefore possibly a portion of a namespace package. */
find_loader_result result = FL_NOT_FOUND;
PyObject *subname;
int is_dir;
/* We're only interested in the last path component of fullname;
earlier components are recorded in self->prefix. */
subname = get_subname(fullname);
if (subname == NULL) {
return FL_ERROR;
}
is_dir = check_is_directory(self, self->prefix, subname);
if (is_dir < 0)
result = FL_ERROR;
else if (is_dir) {
/* This is possibly a portion of a namespace
package. Return the string representing its path,
without a trailing separator. */
*namespace_portion = PyUnicode_FromFormat("%U%c%U%U",
self->archive, SEP,
self->prefix, subname);
if (*namespace_portion == NULL)
result = FL_ERROR;
else
result = FL_NS_FOUND;
}
Py_DECREF(subname);
return result;
}
/* This is a module or package. */
return FL_MODULE_FOUND;
}
/* Check whether we can satisfy the import of the module named by
'fullname'. Return self if we can, None if we can't. */
static PyObject *
zipimporter_find_module(PyObject *obj, PyObject *args)
{
ZipImporter *self = (ZipImporter *)obj;
PyObject *path = NULL;
PyObject *fullname;
PyObject *namespace_portion = NULL;
PyObject *result = NULL;
if (!PyArg_ParseTuple(args, "U|O:zipimporter.find_module", &fullname, &path))
return NULL;
switch (find_loader(self, fullname, &namespace_portion)) {
case FL_ERROR:
return NULL;
case FL_NS_FOUND:
/* A namespace portion is not allowed via find_module, so return None. */
Py_DECREF(namespace_portion);
/* FALL THROUGH */
case FL_NOT_FOUND:
result = Py_None;
break;
case FL_MODULE_FOUND:
result = (PyObject *)self;
break;
default:
PyErr_BadInternalCall();
return NULL;
}
Py_INCREF(result);
return result;
}
/* Check whether we can satisfy the import of the module named by
'fullname', or whether it could be a portion of a namespace
package. Return self if we can load it, a string containing the
full path if it's a possible namespace portion, None if we
can't load it. */
static PyObject *
zipimporter_find_loader(PyObject *obj, PyObject *args)
{
ZipImporter *self = (ZipImporter *)obj;
PyObject *path = NULL;
PyObject *fullname;
PyObject *result = NULL;
PyObject *namespace_portion = NULL;
if (!PyArg_ParseTuple(args, "U|O:zipimporter.find_module", &fullname, &path))
return NULL;
switch (find_loader(self, fullname, &namespace_portion)) {
case FL_ERROR:
return NULL;
case FL_NOT_FOUND: /* Not found, return (None, []) */
result = Py_BuildValue("O[]", Py_None);
break;
case FL_MODULE_FOUND: /* Return (self, []) */
result = Py_BuildValue("O[]", self);
break;
case FL_NS_FOUND: /* Return (None, [namespace_portion]) */
result = Py_BuildValue("O[O]", Py_None, namespace_portion);
Py_DECREF(namespace_portion);
return result;
default:
PyErr_BadInternalCall();
return NULL;
}
return result;
}
/* Load and return the module named by 'fullname'. */
static PyObject *
zipimporter_load_module(PyObject *obj, PyObject *args)
{
ZipImporter *self = (ZipImporter *)obj;
PyObject *code = NULL, *mod, *dict;
PyObject *fullname;
PyObject *modpath = NULL;
int ispackage;
if (!PyArg_ParseTuple(args, "U:zipimporter.load_module",
&fullname))
return NULL;
if (PyUnicode_READY(fullname) == -1)
return NULL;
code = get_module_code(self, fullname, &ispackage, &modpath);
if (code == NULL)
goto error;
mod = PyImport_AddModuleObject(fullname);
if (mod == NULL)
goto error;
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, *subname;
int err;
subname = get_subname(fullname);
if (subname == NULL)
goto error;
fullpath = PyUnicode_FromFormat("%U%c%U%U",
self->archive, SEP,
self->prefix, subname);
Py_DECREF(subname);
if (fullpath == NULL)
goto error;
pkgpath = Py_BuildValue("[N]", fullpath);
if (pkgpath == NULL)
goto error;
err = PyDict_SetItemString(dict, "__path__", pkgpath);
Py_DECREF(pkgpath);
if (err != 0)
goto error;
}
mod = PyImport_ExecCodeModuleObject(fullname, code, modpath, NULL);
Py_CLEAR(code);
if (mod == NULL)
goto error;
if (Py_VerboseFlag)
PySys_FormatStderr("import %U # loaded from Zip %U\n",
fullname, modpath);
Py_DECREF(modpath);
return mod;
error:
Py_XDECREF(code);
Py_XDECREF(modpath);
return NULL;
}
/* Return a string matching __file__ for the named module */
static PyObject *
zipimporter_get_filename(PyObject *obj, PyObject *args)
{
ZipImporter *self = (ZipImporter *)obj;
PyObject *fullname, *code, *modpath;
int ispackage;
if (!PyArg_ParseTuple(args, "U:zipimporter.get_filename",
&fullname))
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;
Py_DECREF(code); /* Only need the path info */
return modpath;
}
/* Return a bool signifying whether the module is a package or not. */
static PyObject *
zipimporter_is_package(PyObject *obj, PyObject *args)
{
ZipImporter *self = (ZipImporter *)obj;
PyObject *fullname;
enum zi_module_info mi;
if (!PyArg_ParseTuple(args, "U: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 %R", fullname);
return NULL;
}
return PyBool_FromLong(mi == MI_PACKAGE);
}
static PyObject *
zipimporter_get_data(PyObject *obj, PyObject *args)
{
ZipImporter *self = (ZipImporter *)obj;
PyObject *path, *key;
PyObject *toc_entry;
Py_ssize_t path_start, path_len, len;
if (!PyArg_ParseTuple(args, "U:zipimporter.get_data", &path))
return NULL;
#ifdef ALTSEP
path = _PyObject_CallMethodId((PyObject *)&PyUnicode_Type, &PyId_replace,
"OCC", path, ALTSEP, SEP);
if (!path)
return NULL;
#else
Py_INCREF(path);
#endif
if (PyUnicode_READY(path) == -1)
goto error;
path_len = PyUnicode_GET_LENGTH(path);
len = PyUnicode_GET_LENGTH(self->archive);
path_start = 0;
if (PyUnicode_Tailmatch(path, self->archive, 0, len, -1)
&& PyUnicode_READ_CHAR(path, len) == SEP) {
path_start = len + 1;
}
key = PyUnicode_Substring(path, path_start, path_len);
if (key == NULL)
goto error;
toc_entry = PyDict_GetItem(self->files, key);
if (toc_entry == NULL) {
PyErr_SetFromErrnoWithFilenameObject(PyExc_IOError, key);
Py_DECREF(key);
goto error;
}
Py_DECREF(key);
Py_DECREF(path);
return get_data(self->archive, toc_entry);
error:
Py_DECREF(path);
return NULL;
}
static PyObject *
zipimporter_get_code(PyObject *obj, PyObject *args)
{
ZipImporter *self = (ZipImporter *)obj;
PyObject *fullname;
if (!PyArg_ParseTuple(args, "U:zipimporter.get_code", &fullname))
return 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;
PyObject *fullname, *subname, *path, *fullpath;
enum zi_module_info mi;
if (!PyArg_ParseTuple(args, "U: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 %R", fullname);
return NULL;
}
subname = get_subname(fullname);
if (subname == NULL)
return NULL;
path = make_filename(self->prefix, subname);
Py_DECREF(subname);
if (path == NULL)
return NULL;
if (mi == MI_PACKAGE)
fullpath = PyUnicode_FromFormat("%U%c__init__.py", path, SEP);
else
fullpath = PyUnicode_FromFormat("%U.py", path);
Py_DECREF(path);
if (fullpath == NULL)
return NULL;
toc_entry = PyDict_GetItem(self->files, fullpath);
Py_DECREF(fullpath);
if (toc_entry != NULL) {
PyObject *res, *bytes;
bytes = get_data(self->archive, toc_entry);
if (bytes == NULL)
return NULL;
res = PyUnicode_FromStringAndSize(PyBytes_AS_STRING(bytes),
PyBytes_GET_SIZE(bytes));
Py_DECREF(bytes);
return res;
}
/* we have the module, but no source */
Py_INCREF(Py_None);
return Py_None;
}
PyDoc_STRVAR(doc_find_module,
"find_module(fullname, path=None) -> self or None.\n\
\n\
Search for a module specified by 'fullname'. 'fullname' must be the\n\
fully qualified (dotted) module name. It returns the zipimporter\n\
instance itself if the module was found, or None if it wasn't.\n\
The optional 'path' argument is ignored -- it's there for compatibility\n\
with the importer protocol.");
PyDoc_STRVAR(doc_find_loader,
"find_loader(fullname, path=None) -> self, str or None.\n\
\n\
Search for a module specified by 'fullname'. 'fullname' must be the\n\
fully qualified (dotted) module name. It returns the zipimporter\n\
instance itself if the module was found, a string containing the\n\
full path name if it's possibly a portion of a namespace package,\n\
or None otherwise. The optional 'path' argument is ignored -- it's\n\
there for compatibility with the importer protocol.");
PyDoc_STRVAR(doc_load_module,
"load_module(fullname) -> module.\n\
\n\
Load the module specified by 'fullname'. 'fullname' must be the\n\
fully qualified (dotted) module name. It returns the imported\n\
module, or raises ZipImportError if it wasn't found.");
PyDoc_STRVAR(doc_get_data,
"get_data(pathname) -> string with file data.\n\
\n\
Return the data associated with 'pathname'. Raise IOError if\n\
the file wasn't found.");
PyDoc_STRVAR(doc_is_package,
"is_package(fullname) -> bool.\n\
\n\
Return True if the module specified by fullname is a package.\n\
Raise ZipImportError if the module couldn't be found.");
PyDoc_STRVAR(doc_get_code,
"get_code(fullname) -> code object.\n\
\n\
Return the code object for the specified module. Raise ZipImportError\n\
if the module couldn't be found.");
PyDoc_STRVAR(doc_get_source,
"get_source(fullname) -> source string.\n\
\n\
Return the source code for the specified module. Raise ZipImportError\n\
if the module couldn't be found, return None if the archive does\n\
contain the module, but has no source for it.");
PyDoc_STRVAR(doc_get_filename,
"get_filename(fullname) -> filename string.\n\
\n\
Return the filename for the specified module.");
static PyMethodDef zipimporter_methods[] = {
{"find_module", zipimporter_find_module, METH_VARARGS,
doc_find_module},
{"find_loader", zipimporter_find_loader, METH_VARARGS,
doc_find_loader},
{"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}
};
PyDoc_STRVAR(zipimporter_doc,
"zipimporter(archivepath) -> zipimporter object\n\
\n\
Create a new zipimporter instance. 'archivepath' must be a path to\n\
a zipfile, or to a specific path inside a zipfile. For example, it can be\n\
'/tmp/myimport.zip', or '/tmp/myimport.zip/mydirectory', if mydirectory is a\n\
valid directory inside the archive.\n\
\n\
'ZipImportError is raised if 'archivepath' doesn't point to a valid Zip\n\
archive.\n\
\n\
The 'archive' attribute of zipimporter objects contains the name of the\n\
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_reserved */
(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 */
};
/* implementation */
static void
set_file_error(PyObject *archive, int eof)
{
if (eof) {
PyErr_SetString(PyExc_EOFError, "EOF read where not expected");
}
else {
PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, archive);
}
}
/*
read_directory(archive) -> files dict (new reference)
Given a path to a Zip archive, build a dict, mapping file names
(local to the archive, using SEP as a separator) to toc entries.
A toc_entry is a tuple:
(__file__, # value to use for __file__, available for all files,
# encoded to the filesystem encoding
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,
data_size and file_offset are 0.
*/
static PyObject *
read_directory(PyObject *archive)
{
PyObject *files = NULL;
FILE *fp;
unsigned short flags, compress, time, date, name_size;
unsigned int crc, data_size, file_size, header_size, header_offset;
unsigned long file_offset, header_position;
unsigned long arc_offset; /* Absolute offset to start of the zip-archive. */
unsigned int count, i;
unsigned char buffer[46];
char name[MAXPATHLEN + 5];
PyObject *nameobj = NULL;
PyObject *path;
const char *charset;
int bootstrap;
const char *errmsg = NULL;
fp = _Py_fopen_obj(archive, "rb");
if (fp == NULL) {
if (PyErr_ExceptionMatches(PyExc_OSError)) {
_PyErr_FormatFromCause(ZipImportError,
"can't open Zip file: %R", archive);
}
return NULL;
}
if (fseek(fp, -22, SEEK_END) == -1) {
goto file_error;
}
header_position = (unsigned long)ftell(fp);
if (header_position == (unsigned long)-1) {
goto file_error;
}
assert(header_position <= (unsigned long)LONG_MAX);
if (fread(buffer, 1, 22, fp) != 22) {
goto file_error;
}
if (READ32LE(buffer) != 0x06054B50u) {
/* Bad: End of Central Dir signature */
errmsg = "not a Zip file";
goto invalid_header;
}
header_size = READ32LE(buffer + 12);
header_offset = READ32LE(buffer + 16);
if (header_position < header_size) {
errmsg = "bad central directory size";
goto invalid_header;
}
if (header_position < header_offset) {
errmsg = "bad central directory offset";
goto invalid_header;
}
if (header_position - header_size < header_offset) {
errmsg = "bad central directory size or offset";
goto invalid_header;
}
header_position -= header_size;
arc_offset = header_position - header_offset;
files = PyDict_New();
if (files == NULL) {
goto error;
}
/* Start of Central Directory */
count = 0;
if (fseek(fp, (long)header_position, 0) == -1) {
goto file_error;
}
for (;;) {
PyObject *t;
size_t n;
int err;
n = fread(buffer, 1, 46, fp);
if (n < 4) {
goto eof_error;
}
/* Start of file header */
if (READ32LE(buffer) != 0x02014B50u) {
break; /* Bad: Central Dir File Header */
}
if (n != 46) {
goto eof_error;
}
flags = READ16LE(buffer + 8);
compress = READ16LE(buffer + 10);
time = READ16LE(buffer + 12);
date = READ16LE(buffer + 14);
crc = READ32LE(buffer + 16);
data_size = READ32LE(buffer + 20);
file_size = READ32LE(buffer + 24);
name_size = READ16LE(buffer + 28);
header_size = (unsigned int)name_size +
READ16LE(buffer + 30) /* extra field */ +
READ16LE(buffer + 32) /* comment */;
file_offset = READ32LE(buffer + 42);
if (file_offset > header_offset) {
errmsg = "bad local header offset";
goto invalid_header;
}
file_offset += arc_offset;
if (name_size > MAXPATHLEN) {
name_size = MAXPATHLEN;
}
if (fread(name, 1, name_size, fp) != name_size) {
goto file_error;
}
name[name_size] = '\0'; /* Add terminating null byte */
if (SEP != '/') {
for (i = 0; i < name_size; i++) {
if (name[i] == '/') {
name[i] = SEP;
}
}
}
/* Skip the rest of the header.
* On Windows, calling fseek to skip over the fields we don't use is
* slower than reading the data because fseek flushes stdio's
* internal buffers. See issue #8745. */
assert(header_size <= 3*0xFFFFu);
for (i = name_size; i < header_size; i++) {
if (getc(fp) == EOF) {
goto file_error;
}
}
bootstrap = 0;
if (flags & 0x0800) {
charset = "utf-8";
}
else if (!PyThreadState_GET()->interp->codecs_initialized) {
/* During bootstrap, we may need to load the encodings
package from a ZIP file. But the cp437 encoding is implemented
in Python in the encodings package.
Break out of this dependency by assuming that the path to
the encodings module is ASCII-only. */
charset = "ascii";
bootstrap = 1;
}
else {
charset = "cp437";
}
nameobj = PyUnicode_Decode(name, name_size, charset, NULL);
if (nameobj == NULL) {
if (bootstrap) {
PyErr_Format(PyExc_NotImplementedError,
"bootstrap issue: python%i%i.zip contains non-ASCII "
"filenames without the unicode flag",
PY_MAJOR_VERSION, PY_MINOR_VERSION);
}
goto error;
}
if (PyUnicode_READY(nameobj) == -1) {
goto error;
}
path = PyUnicode_FromFormat("%U%c%U", archive, SEP, nameobj);
if (path == NULL) {
goto error;
}
t = Py_BuildValue("NHIIkHHI", path, compress, data_size,
file_size, file_offset, time, date, crc);
if (t == NULL) {
goto error;
}
err = PyDict_SetItem(files, nameobj, t);
Py_CLEAR(nameobj);
Py_DECREF(t);
if (err != 0) {
goto error;
}
count++;
}
fclose(fp);
if (Py_VerboseFlag) {
PySys_FormatStderr("# zipimport: found %u names in %R\n",
count, archive);
}
return files;
eof_error:
set_file_error(archive, !ferror(fp));
goto error;
file_error:
PyErr_Format(ZipImportError, "can't read Zip file: %R", archive);
goto error;
invalid_header:
assert(errmsg != NULL);
PyErr_Format(ZipImportError, "%s: %R", errmsg, archive);
goto error;
error:
fclose(fp);
Py_XDECREF(files);
Py_XDECREF(nameobj);
return NULL;
}
/* Return the zlib.decompress function object, or NULL if zlib couldn't
be imported. The function is cached when found, so subsequent calls
don't import zlib again. */
static PyObject *
get_decompress_func(void)
{
static int importing_zlib = 0;
PyObject *zlib;
PyObject *decompress;
_Py_IDENTIFIER(decompress);
if (importing_zlib != 0)
/* Someone has a zlib.pyc 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_GetAttrId(zlib,
&PyId_decompress);
Py_DECREF(zlib);
}
else {
PyErr_Clear();
decompress = NULL;
}
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)
data as a new reference. */
static PyObject *
get_data(PyObject *archive, PyObject *toc_entry)
{
PyObject *raw_data = NULL, *data, *decompress;
char *buf;
FILE *fp;
PyObject *datapath;
unsigned short compress, time, date;
unsigned int crc;
Py_ssize_t data_size, file_size, bytes_size;
long file_offset, header_size;
unsigned char buffer[30];
const char *errmsg = NULL;
if (!PyArg_ParseTuple(toc_entry, "OHnnlHHI", &datapath, &compress,
&data_size, &file_size, &file_offset, &time,
&date, &crc)) {
return NULL;
}
if (data_size < 0) {
PyErr_Format(ZipImportError, "negative data size");
return NULL;
}
fp = _Py_fopen_obj(archive, "rb");
if (!fp) {
return NULL;
}
/* Check to make sure the local file header is correct */
if (fseek(fp, file_offset, 0) == -1) {
goto file_error;
}
if (fread(buffer, 1, 30, fp) != 30) {
goto eof_error;
}
if (READ32LE(buffer) != 0x04034B50u) {
/* Bad: Local File Header */
errmsg = "bad local file header";
goto invalid_header;
}
header_size = (unsigned int)30 +
READ16LE(buffer + 26) /* file name */ +
READ16LE(buffer + 28) /* extra field */;
if (file_offset > LONG_MAX - header_size) {
errmsg = "bad local file header size";
goto invalid_header;
}
file_offset += header_size; /* Start of file data */
if (data_size > LONG_MAX - 1) {
fclose(fp);
PyErr_NoMemory();
return NULL;
}
bytes_size = compress == 0 ? data_size : data_size + 1;
if (bytes_size == 0) {
bytes_size++;
}
raw_data = PyBytes_FromStringAndSize((char *)NULL, bytes_size);
if (raw_data == NULL) {
goto error;
}
buf = PyBytes_AsString(raw_data);
if (fseek(fp, file_offset, 0) == -1) {
goto file_error;
}
if (fread(buf, 1, data_size, fp) != (size_t)data_size) {
PyErr_SetString(PyExc_IOError,
"zipimport: can't read data");
goto error;
}
fclose(fp);
fp = 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 */
data = PyBytes_FromStringAndSize(buf, data_size);
Py_DECREF(raw_data);
return 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);
Py_DECREF(decompress);
Py_DECREF(raw_data);
return data;
eof_error:
set_file_error(archive, !ferror(fp));
goto error;
file_error:
PyErr_Format(ZipImportError, "can't read Zip file: %R", archive);
goto error;
invalid_header:
assert(errmsg != NULL);
PyErr_Format(ZipImportError, "%s: %R", errmsg, archive);
goto error;
error:
if (fp != NULL) {
fclose(fp);
}
Py_XDECREF(raw_data);
return NULL;
}
/* Lenient date/time comparison function. The precision of the mtime
in the archive is lower than the mtime stored in a .pyc: we
must allow a difference of at most one second. */
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 */
if(Py_VerboseFlag)
PySys_WriteStderr("# mtime diff = %ld (should be <=1)\n", d);
return 1 || d <= 1;
}
/* Given the contents of a .pyc file in a buffer, unmarshal the data
and return the code object. Return None if it the magic word doesn't
match (we do this instead of raising an exception as we fall back
to .py if available and we don't want to mask other errors).
Returns a new reference. */
static PyObject *
unmarshal_code(PyObject *pathname, PyObject *data, time_t mtime)
{
PyObject *code;
unsigned char *buf = (unsigned char *)PyBytes_AsString(data);
Py_ssize_t size = PyBytes_Size(data);
if (size < 12) {
PyErr_SetString(ZipImportError,
"bad pyc data");
return NULL;
}
if (READ32LE(buf) != (unsigned int)PyImport_GetMagicNumber()) {
if (Py_VerboseFlag) {
PySys_FormatStderr("# %R has bad magic\n",
pathname);
}
Py_INCREF(Py_None);
return Py_None; /* signal caller to try alternative */
}
if (mtime != 0 && !eq_mtime(READ32LE(buf + 4), mtime)) {
if (Py_VerboseFlag) {
PySys_FormatStderr("# %R has bad mtime\n",
pathname);
}
Py_INCREF(Py_None);
return Py_None; /* signal caller to try alternative */
}
/* XXX the pyc's size field is ignored; timestamp collisions are probably
unimportant with zip files. */
code = PyMarshal_ReadObjectFromString((char *)buf + 12, size - 12);
if (code == NULL) {
return NULL;
}
if (!PyCode_Check(code)) {
Py_DECREF(code);
PyErr_Format(PyExc_TypeError,
"compiled module %R is not a code object",
pathname);
return NULL;
}
return code;
}
/* Replace any occurrences of "\r\n?" in the input string with "\n".
This converts DOS and Mac line endings to Unix line endings.
Also append a trailing "\n" to be compatible with
PyParser_SimpleParseFile(). Returns a new reference. */
static PyObject *
normalize_line_endings(PyObject *source)
{
char *buf, *q, *p;
PyObject *fixed_source;
int len = 0;
p = PyBytes_AsString(source);
if (p == NULL) {
return PyBytes_FromStringAndSize("\n\0", 2);
}
/* one char extra for trailing \n and one for terminating \0 */
buf = (char *)PyMem_Malloc(PyBytes_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;
len++;
}
*q++ = '\n'; /* add trailing \n */
*q = '\0';
fixed_source = PyBytes_FromStringAndSize(buf, len + 2);
PyMem_Free(buf);
return fixed_source;
}
/* Given a string buffer containing Python source code, compile it
and return a code object as a new reference. */
static PyObject *
compile_source(PyObject *pathname, PyObject *source)
{
PyObject *code, *fixed_source;
fixed_source = normalize_line_endings(source);
if (fixed_source == NULL) {
return NULL;
}
code = Py_CompileStringObject(PyBytes_AsString(fixed_source),
pathname, Py_file_input, NULL, -1);
Py_DECREF(fixed_source);
return code;
}
/* Convert the date/time values found in the Zip archive to a value
that's compatible with the time stamp stored in .pyc files. */
static time_t
parse_dostime(int dostime, int dosdate)
{
struct tm stm;
bzero((void *) &stm, 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 */
return mktime(&stm);
}
/* Given a path to a .pyc file in the archive, return the
modification time of the matching .py file, or 0 if no source
is available. */
static time_t
get_mtime_of_source(ZipImporter *self, PyObject *path)
{
PyObject *toc_entry, *stripped;
time_t mtime;
/* strip 'c' from *.pyc */
if (PyUnicode_READY(path) == -1)
return (time_t)-1;
stripped = PyUnicode_FromKindAndData(PyUnicode_KIND(path),
PyUnicode_DATA(path),
PyUnicode_GET_LENGTH(path) - 1);
if (stripped == NULL)
return (time_t)-1;
toc_entry = PyDict_GetItem(self->files, stripped);
Py_DECREF(stripped);
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 = PyLong_AsLong(PyTuple_GetItem(toc_entry, 5));
date = PyLong_AsLong(PyTuple_GetItem(toc_entry, 6));
mtime = parse_dostime(time, date);
} else
mtime = 0;
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)
{
PyObject *data, *modpath, *code;
data = get_data(self->archive, toc_entry);
if (data == NULL)
return NULL;
modpath = 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 associated with the module specified by
'fullname'. */
static PyObject *
get_module_code(ZipImporter *self, PyObject *fullname,
int *p_ispackage, PyObject **p_modpath)
{
PyObject *code = NULL, *toc_entry, *subname;
PyObject *path, *fullpath = NULL;
struct st_zip_searchorder *zso;
subname = get_subname(fullname);
if (subname == NULL)
return NULL;
path = make_filename(self->prefix, subname);
Py_DECREF(subname);
if (path == NULL)
return NULL;
for (zso = zip_searchorder; *zso->suffix; zso++) {
code = NULL;
fullpath = PyUnicode_FromFormat("%U%s", path, zso->suffix);
if (fullpath == NULL)
goto exit;
if (Py_VerboseFlag > 1)
PySys_FormatStderr("# trying %U%c%U\n",
self->archive, (int)SEP, fullpath);
toc_entry = PyDict_GetItem(self->files, fullpath);
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, fullpath);
if (mtime == (time_t)-1 && PyErr_Occurred()) {
goto exit;
}
}
Py_CLEAR(fullpath);
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 = PyTuple_GetItem(toc_entry, 0);
Py_INCREF(*p_modpath);
}
goto exit;
}
else
Py_CLEAR(fullpath);
}
PyErr_Format(ZipImportError, "can't find module %R", fullname);
exit:
Py_DECREF(path);
Py_XDECREF(fullpath);
return code;
}
/* Module init */
PyDoc_STRVAR(zipimport_doc,
"zipimport provides support for importing Python modules from Zip archives.\n\
\n\
This module exports three objects:\n\
- zipimporter: a class; its constructor takes a path to a Zip archive.\n\
- ZipImportError: exception raised by zipimporter objects. It's a\n\
subclass of ImportError, so it can be caught as ImportError, too.\n\
- _zip_directory_cache: a dict, mapping archive paths to zip directory\n\
info dicts, as used in zipimporter._files.\n\
\n\
It is usually not needed to use the zipimport module explicitly; it is\n\
used by the builtin import mechanism for sys.path items that are paths\n\
to Zip archives.");
static struct PyModuleDef zipimportmodule = {
PyModuleDef_HEAD_INIT,
"zipimport",
zipimport_doc,
-1,
NULL,
NULL,
NULL,
NULL,
NULL
};
PyMODINIT_FUNC
PyInit_zipimport(void)
{
PyObject *mod;
if (PyType_Ready(&ZipImporter_Type) < 0)
return NULL;
/* Correct directory separator */
zip_searchorder[0].suffix[0] = SEP;
zip_searchorder[1].suffix[0] = SEP;
mod = PyModule_Create(&zipimportmodule);
if (mod == NULL)
return NULL;
ZipImportError = PyErr_NewException("zipimport.ZipImportError",
PyExc_ImportError, NULL);
if (ZipImportError == NULL)
return NULL;
Py_INCREF(ZipImportError);
if (PyModule_AddObject(mod, "ZipImportError",
ZipImportError) < 0)
return NULL;
Py_INCREF(&ZipImporter_Type);
if (PyModule_AddObject(mod, "zipimporter",
(PyObject *)&ZipImporter_Type) < 0)
return NULL;
zip_directory_cache = PyDict_New();
if (zip_directory_cache == NULL)
return NULL;
Py_INCREF(zip_directory_cache);
if (PyModule_AddObject(mod, "_zip_directory_cache",
zip_directory_cache) < 0)
return NULL;
return mod;
}
_Section(".rodata.pytab.1") const struct _inittab _PyImport_Inittab_zipimport = {
"zipimport",
PyInit_zipimport,
};
| 50,183 | 1,608 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Modules/tlsmodule.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:8;coding:utf-8 -*-â
âvi: set net ft=c ts=4 sts=4 sw=4 fenc=utf-8 :viâ
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ¡
â Copyright 2021 Justine Alexandra Roberts Tunney â
â â
â Copying of this file is authorized only if (1) you are Justine Tunney, â
â or (2) you make absolutely no changes to your copy. â
â â
â THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL â
â WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED â
â WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE â
â AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL â
â DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR â
â PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER â
â TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR â
â PERFORMANCE OF THIS SOFTWARE. â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
#define PY_SSIZE_T_CLEAN
#include "libc/assert.h"
#include "libc/calls/calls.h"
#include "libc/errno.h"
#include "libc/macros.internal.h"
#include "libc/mem/gc.internal.h"
#include "libc/str/str.h"
#include "net/https/https.h"
#include "third_party/mbedtls/ctr_drbg.h"
#include "third_party/mbedtls/debug.h"
#include "third_party/mbedtls/error.h"
#include "third_party/mbedtls/ssl.h"
#include "third_party/python/Include/abstract.h"
#include "third_party/python/Include/import.h"
#include "third_party/python/Include/longobject.h"
#include "third_party/python/Include/modsupport.h"
#include "third_party/python/Include/object.h"
#include "third_party/python/Include/objimpl.h"
#include "third_party/python/Include/pyerrors.h"
#include "third_party/python/Include/pymacro.h"
#include "third_party/python/Include/structmember.h"
#include "third_party/python/Include/yoink.h"
/* clang-format off */
/**
* @fileoverview Enough TLS support for HttpsClient so far.
*/
PYTHON_PROVIDE("tls");
#if 0
#define LOG(...) kprintf(__VA_ARGS__)
#else
#define LOG(...) (void)0
#endif
struct Tls {
PyObject_HEAD
int fd;
PyObject *todo;
mbedtls_ssl_config conf;
mbedtls_ssl_context ssl;
mbedtls_ctr_drbg_context rng;
};
static PyObject *TlsError;
static PyTypeObject tls_type;
static PyObject *
SetTlsError(int rc)
{
char b[128];
mbedtls_strerror(rc, b, sizeof(b));
PyErr_SetString(TlsError, b);
return NULL;
}
static int
TlsSend(void *c, const unsigned char *p, size_t n)
{
int rc;
struct Tls *self = c;
for (;;) {
rc = write(self->fd, p, n);
if (rc != -1) {
return rc;
} else if (errno == EINTR) {
if (PyErr_CheckSignals()) {
return -1;
}
} else {
PyErr_SetFromErrno(PyExc_OSError);
return -1;
}
}
}
static int
TlsRecv(void *c, unsigned char *p, size_t n, uint32_t t)
{
int rc;
struct Tls *self = c;
for (;;) {
rc = read(self->fd, p, n);
if (rc != -1) {
return rc;
} else if (errno == EINTR) {
if (PyErr_CheckSignals()) {
return -1;
}
} else {
PyErr_SetFromErrno(PyExc_OSError);
return -1;
}
}
}
static struct Tls *
tls_new(int fd, const char *host, PyObject *todo)
{
struct Tls *self;
LOG("TLS.new\n");
if ((self = PyObject_New(struct Tls, &tls_type))) {
self->fd = fd;
self->todo = todo;
Py_INCREF(todo);
InitializeRng(&self->rng);
mbedtls_ssl_init(&self->ssl);
mbedtls_ssl_config_init(&self->conf);
mbedtls_ssl_config_defaults(&self->conf,
MBEDTLS_SSL_IS_CLIENT,
MBEDTLS_SSL_TRANSPORT_STREAM,
MBEDTLS_SSL_PRESET_DEFAULT);
mbedtls_ssl_conf_rng(&self->conf, mbedtls_ctr_drbg_random, &self->rng);
mbedtls_ssl_conf_ca_chain(&self->conf, GetSslRoots(), 0);
/* mbedtls_ssl_conf_dbg(&self->conf, TlsDebug, 0); */
/* mbedtls_debug_threshold = 5; */
if (host && *host) {
mbedtls_ssl_conf_authmode(&self->conf, MBEDTLS_SSL_VERIFY_REQUIRED);
mbedtls_ssl_set_hostname(&self->ssl, host);
} else {
mbedtls_ssl_conf_authmode(&self->conf, MBEDTLS_SSL_VERIFY_NONE);
}
mbedtls_ssl_set_bio(&self->ssl, self, TlsSend, 0, TlsRecv);
mbedtls_ssl_setup(&self->ssl, &self->conf);
self->conf.disable_compression = true;
}
return self;
}
static void
tls_dealloc(struct Tls *self)
{
LOG("TLS.dealloc\n");
if (self->fd != -1) {
LOG("TLS CLOSING\n");
close(self->fd);
}
Py_DECREF(self->todo);
if (PyErr_Occurred()) {
PyErr_Clear();
}
mbedtls_ssl_free(&self->ssl);
mbedtls_ctr_drbg_free(&self->rng);
mbedtls_ssl_config_free(&self->conf);
PyObject_Del(self);
}
PyDoc_STRVAR(tls_send__doc__, "\
send($self, bytes, /)\n\
--\n\n\
Sends bytes as ciphertext to file descriptor, returning number\n\
of bytes from buffer transmitted, or raising OSError/TlsError.");
static PyObject *
tls_send(struct Tls *self, PyObject *args)
{
int rc;
PyObject *res;
Py_buffer data;
LOG("TLS.send\n");
if (!PyArg_ParseTuple(args, "y*:send", &data)) return 0;
rc = mbedtls_ssl_write(&self->ssl, data.buf, data.len);
if (rc != -1) {
if (rc >= 0) {
res = PyLong_FromLong(rc);
} else {
SetTlsError(rc);
LOG("TLS CLOSING\n");
close(self->fd);
self->fd = -1;
res = 0;
}
} else {
res = 0;
}
PyBuffer_Release(&data);
return res;
}
PyDoc_STRVAR(tls_sendall__doc__, "\
sendall($self, bytes, /)\n\
--\n\n\
Sends all bytes to file descriptor as ciphertext, returning number\n\
of bytes from buffer transmitted, or raising OSError / TlsError.");
static PyObject *
tls_sendall(struct Tls *self, PyObject *args)
{
LOG("TLS.sendall\n");
int rc;
Py_ssize_t i;
PyObject *res;
Py_buffer data;
if (!PyArg_ParseTuple(args, "y*:sendall", &data)) return 0;
for (i = 0;;) {
rc = mbedtls_ssl_write(&self->ssl, (char *)data.buf + i, data.len - i);
if (rc > 0) {
if ((i += rc) == data.len) {
res = Py_None;
Py_INCREF(res);
break;
}
} else {
if (rc != -1) {
SetTlsError(rc);
LOG("TLS CLOSING\n");
close(self->fd);
self->fd = -1;
}
res = 0;
break;
}
}
PyBuffer_Release(&data);
return res;
}
PyDoc_STRVAR(tls_recv__doc__, "\
recv($self, nbytes, /)\n\
--\n\n\
Receives deciphered bytes from file descriptor, returning bytes\n\
or raising OSError / TlsError.");
static PyObject *
tls_recv(struct Tls *self, PyObject *args)
{
LOG("TLS.recv\n");
int rc;
Py_ssize_t n;
PyObject *res, *buf;
if (!PyArg_ParseTuple(args, "n:recv", &n)) return 0;
if (n < 0) {
PyErr_SetString(PyExc_ValueError,
"negative buffersize in recv");
return NULL;
}
if (!(buf = PyBytes_FromStringAndSize(0, n))) return 0;
rc = mbedtls_ssl_read(&self->ssl, PyBytes_AS_STRING(buf), n);
if (rc != -1) {
if (rc >= 0) {
if (rc != n) {
_PyBytes_Resize(&buf, rc);
}
res = buf;
} else {
Py_DECREF(buf);
SetTlsError(rc);
LOG("TLS CLOSING\n");
close(self->fd);
self->fd = -1;
res = 0;
}
} else {
Py_DECREF(buf);
res = 0;
}
return res;
}
PyDoc_STRVAR(tls_recv_into__doc__, "\
recv_into($self, buf, /)\n\
--\n\n\
Reads into an existing buffer...");
static PyObject *
tls_recv_into(struct Tls *self, PyObject *args)
{
LOG("TLS.recv_into\n");
int rc;
Py_ssize_t n;
PyObject *res;
Py_buffer buf;
if (!PyArg_ParseTuple(args, "w*:recv_into", &buf)) return 0;
rc = mbedtls_ssl_read(&self->ssl, buf.buf, buf.len);
if (rc != -1) {
if (rc >= 0) {
res = PyLong_FromLong(rc);
LOG("got %d\n", rc);
} else {
SetTlsError(rc);
LOG("TLS CLOSING\n");
close(self->fd);
self->fd = -1;
res = 0;
}
} else {
res = 0;
}
PyBuffer_Release(&buf);
return res;
}
PyDoc_STRVAR(tls_fileno__doc__, "\
fileno($self, /)\n\
--\n\n\
Returns file descriptor passed to constructor.");
static PyObject *
tls_fileno(struct Tls *self, PyObject *unused)
{
LOG("TLS.fileno\n");
return PyLong_FromLong(self->fd);
}
PyDoc_STRVAR(tls_shutdown__doc__, "\
shutdown($self, how, /)\n\
--\n\n\
Does nothing currently.");
static PyObject *
tls_shutdown(struct Tls *self, PyObject *unused)
{
LOG("TLS.shutdown\n");
Py_RETURN_NONE;
}
PyDoc_STRVAR(tls_close__doc__, "\
close($self, /)\n\
--\n\n\
Closes SSL connection and file descriptor.");
static PyObject *
tls_close(struct Tls *self, PyObject *unused)
{
int rc, fd;
/* TODO(jart): do nothing until we can figure out how to own fd */
Py_RETURN_NONE;
fd = self->fd;
if (fd != -1) {
self->fd = -1;
rc = mbedtls_ssl_close_notify(&self->ssl);
if (rc) {
LOG("TLS CLOSING\n");
close(fd);
if (rc != -1) {
SetTlsError(rc);
}
return 0;
}
LOG("TLS CLOSING\n");
rc = close(fd);
if (rc == -1) {
return PyErr_SetFromErrno(PyExc_OSError);
}
}
Py_RETURN_NONE;
}
PyDoc_STRVAR(tls_handshake__doc__, "\
handshake($self, /)\n\
--\n\n\
Handshakes SSL connection and file descriptor.");
static PyObject *
tls_handshake(struct Tls *self, PyObject *unused)
{
int rc;
LOG("TLS.handshake\n");
rc = mbedtls_ssl_handshake(&self->ssl);
if (rc) {
LOG("TLS CLOSING\n");
close(self->fd);
self->fd = -1;
if (rc != -1) {
if (rc == MBEDTLS_ERR_X509_CERT_VERIFY_FAILED) {
PyErr_SetString(TlsError, gc(DescribeSslVerifyFailure(self->ssl.session_negotiate->verify_result)));
} else {
SetTlsError(rc);
}
}
return 0;
}
Py_RETURN_NONE;
}
static PyMethodDef tls_methods[] = {
{"handshake", (PyCFunction)tls_handshake, METH_NOARGS, tls_handshake__doc__},
{"recv", (PyCFunction)tls_recv, METH_VARARGS, tls_recv__doc__},
{"recv_into", (PyCFunction)tls_recv_into, METH_VARARGS, tls_recv_into__doc__},
{"send", (PyCFunction)tls_send, METH_VARARGS, tls_send__doc__},
{"sendall", (PyCFunction)tls_sendall, METH_VARARGS, tls_sendall__doc__},
{"fileno", (PyCFunction)tls_fileno, METH_NOARGS, tls_fileno__doc__},
{"shutdown", (PyCFunction)tls_shutdown, METH_VARARGS, tls_shutdown__doc__},
{"close", (PyCFunction)tls_close, METH_NOARGS, tls_close__doc__},
{0}
};
static PyObject *
tls_repr(struct Tls *self)
{
return PyUnicode_FromFormat("<TLS object @ %p>", self);
}
PyDoc_STRVAR(tls_doc,
"An MbedTLS object.");
static PyTypeObject tls_type = {
PyVarObject_HEAD_INIT(NULL, 0)
/*tp_name*/ "tls.TLS",
/*tp_basicsize*/ sizeof(struct Tls),
/*tp_itemsize*/ 0,
/*tp_dealloc*/ (destructor)tls_dealloc,
/*tp_print*/ 0,
/*tp_getattr*/ 0,
/*tp_setattr*/ 0,
/*tp_reserved*/ 0,
/*tp_repr*/ (reprfunc)tls_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,
/*tp_doc*/ tls_doc,
/*tp_traverse*/ 0,
/*tp_clear*/ 0,
/*tp_richcompare*/ 0,
/*tp_weaklistoffset*/ 0,
/*tp_iter*/ 0,
/*tp_iternext*/ 0,
/*tp_methods*/ tls_methods,
/*tp_members*/ 0,
/*tp_getset*/ 0,
/*tp_base*/ 0,
/*tp_dict*/ 0,
/*tp_descr_get*/ 0,
/*tp_descr_set*/ 0,
/*tp_dictoffset*/ 0,
};
PyDoc_STRVAR(newclient__doc__,
"newclient($module, fd, host)\n\
--\n\n\
Creates TLS client.");
static PyObject *
newclient(PyObject *self, PyObject *args)
{
int rc, fd;
PyObject *todo;
struct Tls *tls;
const char *host;
if (!PyArg_ParseTuple(args, "isO:newclient", &fd, &host, &todo)) return 0;
tls = tls_new(fd, host, todo);
return (PyObject *)tls;
}
static struct PyMethodDef mbedtls_functions[] = {
{"newclient", (PyCFunction)newclient, METH_VARARGS, newclient__doc__},
{0}
};
static struct PyModuleDef mbedtls_module = {
PyModuleDef_HEAD_INIT,
"tls",
NULL,
-1,
mbedtls_functions
};
PyMODINIT_FUNC
PyInit_tls(void)
{
PyObject *m, *mbedtls_md_meth_names;
Py_TYPE(&tls_type) = &PyType_Type;
if (PyType_Ready(&tls_type) < 0) return 0;
if (!(m = PyModule_Create(&mbedtls_module))) return 0;
Py_INCREF((PyObject *)&tls_type);
PyModule_AddObject(m, "TLS", (PyObject *)&tls_type);
TlsError = PyErr_NewException("tls.TlsError", NULL, NULL);
Py_INCREF(TlsError);
PyModule_AddObject(m, "TlsError", TlsError);
return m;
}
_Section(".rodata.pytab.1") const struct _inittab _PyImport_Inittab_tls = {
"tls",
PyInit_tls,
};
| 14,271 | 502 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Modules/_decimal/README.txt |
About
=====
_decimal.c is a wrapper for the libmpdec library. libmpdec is a fast C
library for correctly-rounded arbitrary precision decimal floating point
arithmetic. It is a complete implementation of Mike Cowlishaw/IBM's
General Decimal Arithmetic Specification.
Build process for the module
============================
As usual, the build process for _decimal.so is driven by setup.py in the top
level directory. setup.py autodetects the following build configurations:
1) x64 - 64-bit Python, x86_64 processor (AMD, Intel)
2) uint128 - 64-bit Python, compiler provides __uint128_t (gcc)
3) ansi64 - 64-bit Python, ANSI C
4) ppro - 32-bit Python, x86 CPU, PentiumPro or later
5) ansi32 - 32-bit Python, ANSI C
6) ansi-legacy - 32-bit Python, compiler without uint64_t
7) universal - Mac OS only (multi-arch)
It is possible to override autodetection by exporting:
PYTHON_DECIMAL_WITH_MACHINE=value, where value is one of the above options.
NOTE
====
decimal.so is not built from a static libmpdec.a since doing so led to
failures on AIX (user report) and Windows (mixing static and dynamic CRTs
causes locale problems and more).
| 1,210 | 47 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Modules/_decimal/docstrings.h | #ifndef DOCSTRINGS_H
#define DOCSTRINGS_H
/* clang-format off */
#include "third_party/python/Include/pymacro.h"
/******************************************************************************/
/* Module */
/******************************************************************************/
PyDoc_STRVAR(doc__decimal,
"C decimal arithmetic module");
PyDoc_STRVAR(doc_getcontext,
"getcontext($module, /)\n--\n\n\
Get the current default context.\n\
\n");
PyDoc_STRVAR(doc_setcontext,
"setcontext($module, context, /)\n--\n\n\
Set a new default context.\n\
\n");
PyDoc_STRVAR(doc_localcontext,
"localcontext($module, /, ctx=None)\n--\n\n\
Return a context manager that will set the default context to a copy of ctx\n\
on entry to the with-statement and restore the previous default context when\n\
exiting the with-statement. If no context is specified, a copy of the current\n\
default context is used.\n\
\n");
#ifdef EXTRA_FUNCTIONALITY
PyDoc_STRVAR(doc_ieee_context,
"IEEEContext($module, bits, /)\n--\n\n\
Return a context object initialized to the proper values for one of the\n\
IEEE interchange formats. The argument must be a multiple of 32 and less\n\
than IEEE_CONTEXT_MAX_BITS. For the most common values, the constants\n\
DECIMAL32, DECIMAL64 and DECIMAL128 are provided.\n\
\n");
#endif
/******************************************************************************/
/* Decimal Object and Methods */
/******************************************************************************/
PyDoc_STRVAR(doc_decimal,
"Decimal(value=\"0\", context=None)\n--\n\n\
Construct a new Decimal object. 'value' can be an integer, string, tuple,\n\
or another Decimal object. If no value is given, return Decimal('0'). The\n\
context does not affect the conversion and is only passed to determine if\n\
the InvalidOperation trap is active.\n\
\n");
PyDoc_STRVAR(doc_adjusted,
"adjusted($self, /)\n--\n\n\
Return the adjusted exponent of the number. Defined as exp + digits - 1.\n\
\n");
PyDoc_STRVAR(doc_as_tuple,
"as_tuple($self, /)\n--\n\n\
Return a tuple representation of the number.\n\
\n");
PyDoc_STRVAR(doc_as_integer_ratio,
"as_integer_ratio($self, /)\n--\n\n\
Decimal.as_integer_ratio() -> (int, int)\n\
\n\
Return a pair of integers, whose ratio is exactly equal to the original\n\
Decimal and with a positive denominator. The ratio is in lowest terms.\n\
Raise OverflowError on infinities and a ValueError on NaNs.\n\
\n");
PyDoc_STRVAR(doc_canonical,
"canonical($self, /)\n--\n\n\
Return the canonical encoding of the argument. Currently, the encoding\n\
of a Decimal instance is always canonical, so this operation returns its\n\
argument unchanged.\n\
\n");
PyDoc_STRVAR(doc_compare,
"compare($self, /, other, context=None)\n--\n\n\
Compare self to other. Return a decimal value:\n\
\n\
a or b is a NaN ==> Decimal('NaN')\n\
a < b ==> Decimal('-1')\n\
a == b ==> Decimal('0')\n\
a > b ==> Decimal('1')\n\
\n");
PyDoc_STRVAR(doc_compare_signal,
"compare_signal($self, /, other, context=None)\n--\n\n\
Identical to compare, except that all NaNs signal.\n\
\n");
PyDoc_STRVAR(doc_compare_total,
"compare_total($self, /, other, context=None)\n--\n\n\
Compare two operands using their abstract representation rather than\n\
their numerical value. Similar to the compare() method, but the result\n\
gives a total ordering on Decimal instances. Two Decimal instances with\n\
the same numeric value but different representations compare unequal\n\
in this ordering:\n\
\n\
>>> Decimal('12.0').compare_total(Decimal('12'))\n\
Decimal('-1')\n\
\n\
Quiet and signaling NaNs are also included in the total ordering. The result\n\
of this function is Decimal('0') if both operands have the same representation,\n\
Decimal('-1') if the first operand is lower in the total order than the second,\n\
and Decimal('1') if the first operand is higher in the total order than the\n\
second operand. See the specification for details of the total order.\n\
\n\
This operation is unaffected by context and is quiet: no flags are changed\n\
and no rounding is performed. As an exception, the C version may raise\n\
InvalidOperation if the second operand cannot be converted exactly.\n\
\n");
PyDoc_STRVAR(doc_compare_total_mag,
"compare_total_mag($self, /, other, context=None)\n--\n\n\
Compare two operands using their abstract representation rather than their\n\
value as in compare_total(), but ignoring the sign of each operand.\n\
\n\
x.compare_total_mag(y) is equivalent to x.copy_abs().compare_total(y.copy_abs()).\n\
\n\
This operation is unaffected by context and is quiet: no flags are changed\n\
and no rounding is performed. As an exception, the C version may raise\n\
InvalidOperation if the second operand cannot be converted exactly.\n\
\n");
PyDoc_STRVAR(doc_conjugate,
"conjugate($self, /)\n--\n\n\
Return self.\n\
\n");
PyDoc_STRVAR(doc_copy_abs,
"copy_abs($self, /)\n--\n\n\
Return the absolute value of the argument. This operation is unaffected by\n\
context and is quiet: no flags are changed and no rounding is performed.\n\
\n");
PyDoc_STRVAR(doc_copy_negate,
"copy_negate($self, /)\n--\n\n\
Return the negation of the argument. This operation is unaffected by context\n\
and is quiet: no flags are changed and no rounding is performed.\n\
\n");
PyDoc_STRVAR(doc_copy_sign,
"copy_sign($self, /, other, context=None)\n--\n\n\
Return a copy of the first operand with the sign set to be the same as the\n\
sign of the second operand. For example:\n\
\n\
>>> Decimal('2.3').copy_sign(Decimal('-1.5'))\n\
Decimal('-2.3')\n\
\n\
This operation is unaffected by context and is quiet: no flags are changed\n\
and no rounding is performed. As an exception, the C version may raise\n\
InvalidOperation if the second operand cannot be converted exactly.\n\
\n");
PyDoc_STRVAR(doc_exp,
"exp($self, /, context=None)\n--\n\n\
Return the value of the (natural) exponential function e**x at the given\n\
number. The function always uses the ROUND_HALF_EVEN mode and the result\n\
is correctly rounded.\n\
\n");
PyDoc_STRVAR(doc_from_float,
"from_float($type, f, /)\n--\n\n\
Class method that converts a float to a decimal number, exactly.\n\
Since 0.1 is not exactly representable in binary floating point,\n\
Decimal.from_float(0.1) is not the same as Decimal('0.1').\n\
\n\
>>> Decimal.from_float(0.1)\n\
Decimal('0.1000000000000000055511151231257827021181583404541015625')\n\
>>> Decimal.from_float(float('nan'))\n\
Decimal('NaN')\n\
>>> Decimal.from_float(float('inf'))\n\
Decimal('Infinity')\n\
>>> Decimal.from_float(float('-inf'))\n\
Decimal('-Infinity')\n\
\n\
\n");
PyDoc_STRVAR(doc_fma,
"fma($self, /, other, third, context=None)\n--\n\n\
Fused multiply-add. Return self*other+third with no rounding of the\n\
intermediate product self*other.\n\
\n\
>>> Decimal(2).fma(3, 5)\n\
Decimal('11')\n\
\n\
\n");
PyDoc_STRVAR(doc_is_canonical,
"is_canonical($self, /)\n--\n\n\
Return True if the argument is canonical and False otherwise. Currently,\n\
a Decimal instance is always canonical, so this operation always returns\n\
True.\n\
\n");
PyDoc_STRVAR(doc_is_finite,
"is_finite($self, /)\n--\n\n\
Return True if the argument is a finite number, and False if the argument\n\
is infinite or a NaN.\n\
\n");
PyDoc_STRVAR(doc_is_infinite,
"is_infinite($self, /)\n--\n\n\
Return True if the argument is either positive or negative infinity and\n\
False otherwise.\n\
\n");
PyDoc_STRVAR(doc_is_nan,
"is_nan($self, /)\n--\n\n\
Return True if the argument is a (quiet or signaling) NaN and False\n\
otherwise.\n\
\n");
PyDoc_STRVAR(doc_is_normal,
"is_normal($self, /, context=None)\n--\n\n\
Return True if the argument is a normal finite non-zero number with an\n\
adjusted exponent greater than or equal to Emin. Return False if the\n\
argument is zero, subnormal, infinite or a NaN.\n\
\n");
PyDoc_STRVAR(doc_is_qnan,
"is_qnan($self, /)\n--\n\n\
Return True if the argument is a quiet NaN, and False otherwise.\n\
\n");
PyDoc_STRVAR(doc_is_signed,
"is_signed($self, /)\n--\n\n\
Return True if the argument has a negative sign and False otherwise.\n\
Note that both zeros and NaNs can carry signs.\n\
\n");
PyDoc_STRVAR(doc_is_snan,
"is_snan($self, /)\n--\n\n\
Return True if the argument is a signaling NaN and False otherwise.\n\
\n");
PyDoc_STRVAR(doc_is_subnormal,
"is_subnormal($self, /, context=None)\n--\n\n\
Return True if the argument is subnormal, and False otherwise. A number is\n\
subnormal if it is non-zero, finite, and has an adjusted exponent less\n\
than Emin.\n\
\n");
PyDoc_STRVAR(doc_is_zero,
"is_zero($self, /)\n--\n\n\
Return True if the argument is a (positive or negative) zero and False\n\
otherwise.\n\
\n");
PyDoc_STRVAR(doc_ln,
"ln($self, /, context=None)\n--\n\n\
Return the natural (base e) logarithm of the operand. The function always\n\
uses the ROUND_HALF_EVEN mode and the result is correctly rounded.\n\
\n");
PyDoc_STRVAR(doc_log10,
"log10($self, /, context=None)\n--\n\n\
Return the base ten logarithm of the operand. The function always uses the\n\
ROUND_HALF_EVEN mode and the result is correctly rounded.\n\
\n");
PyDoc_STRVAR(doc_logb,
"logb($self, /, context=None)\n--\n\n\
For a non-zero number, return the adjusted exponent of the operand as a\n\
Decimal instance. If the operand is a zero, then Decimal('-Infinity') is\n\
returned and the DivisionByZero condition is raised. If the operand is\n\
an infinity then Decimal('Infinity') is returned.\n\
\n");
PyDoc_STRVAR(doc_logical_and,
"logical_and($self, /, other, context=None)\n--\n\n\
Return the digit-wise 'and' of the two (logical) operands.\n\
\n");
PyDoc_STRVAR(doc_logical_invert,
"logical_invert($self, /, context=None)\n--\n\n\
Return the digit-wise inversion of the (logical) operand.\n\
\n");
PyDoc_STRVAR(doc_logical_or,
"logical_or($self, /, other, context=None)\n--\n\n\
Return the digit-wise 'or' of the two (logical) operands.\n\
\n");
PyDoc_STRVAR(doc_logical_xor,
"logical_xor($self, /, other, context=None)\n--\n\n\
Return the digit-wise 'exclusive or' of the two (logical) operands.\n\
\n");
PyDoc_STRVAR(doc_max,
"max($self, /, other, context=None)\n--\n\n\
Maximum of self and other. If one operand is a quiet NaN and the other is\n\
numeric, the numeric operand is returned.\n\
\n");
PyDoc_STRVAR(doc_max_mag,
"max_mag($self, /, other, context=None)\n--\n\n\
Similar to the max() method, but the comparison is done using the absolute\n\
values of the operands.\n\
\n");
PyDoc_STRVAR(doc_min,
"min($self, /, other, context=None)\n--\n\n\
Minimum of self and other. If one operand is a quiet NaN and the other is\n\
numeric, the numeric operand is returned.\n\
\n");
PyDoc_STRVAR(doc_min_mag,
"min_mag($self, /, other, context=None)\n--\n\n\
Similar to the min() method, but the comparison is done using the absolute\n\
values of the operands.\n\
\n");
PyDoc_STRVAR(doc_next_minus,
"next_minus($self, /, context=None)\n--\n\n\
Return the largest number representable in the given context (or in the\n\
current default context if no context is given) that is smaller than the\n\
given operand.\n\
\n");
PyDoc_STRVAR(doc_next_plus,
"next_plus($self, /, context=None)\n--\n\n\
Return the smallest number representable in the given context (or in the\n\
current default context if no context is given) that is larger than the\n\
given operand.\n\
\n");
PyDoc_STRVAR(doc_next_toward,
"next_toward($self, /, other, context=None)\n--\n\n\
If the two operands are unequal, return the number closest to the first\n\
operand in the direction of the second operand. If both operands are\n\
numerically equal, return a copy of the first operand with the sign set\n\
to be the same as the sign of the second operand.\n\
\n");
PyDoc_STRVAR(doc_normalize,
"normalize($self, /, context=None)\n--\n\n\
Normalize the number by stripping the rightmost trailing zeros and\n\
converting any result equal to Decimal('0') to Decimal('0e0'). Used\n\
for producing canonical values for members of an equivalence class.\n\
For example, Decimal('32.100') and Decimal('0.321000e+2') both normalize\n\
to the equivalent value Decimal('32.1').\n\
\n");
PyDoc_STRVAR(doc_number_class,
"number_class($self, /, context=None)\n--\n\n\
Return a string describing the class of the operand. The returned value\n\
is one of the following ten strings:\n\
\n\
* '-Infinity', indicating that the operand is negative infinity.\n\
* '-Normal', indicating that the operand is a negative normal number.\n\
* '-Subnormal', indicating that the operand is negative and subnormal.\n\
* '-Zero', indicating that the operand is a negative zero.\n\
* '+Zero', indicating that the operand is a positive zero.\n\
* '+Subnormal', indicating that the operand is positive and subnormal.\n\
* '+Normal', indicating that the operand is a positive normal number.\n\
* '+Infinity', indicating that the operand is positive infinity.\n\
* 'NaN', indicating that the operand is a quiet NaN (Not a Number).\n\
* 'sNaN', indicating that the operand is a signaling NaN.\n\
\n\
\n");
PyDoc_STRVAR(doc_quantize,
"quantize($self, /, exp, rounding=None, context=None)\n--\n\n\
Return a value equal to the first operand after rounding and having the\n\
exponent of the second operand.\n\
\n\
>>> Decimal('1.41421356').quantize(Decimal('1.000'))\n\
Decimal('1.414')\n\
\n\
Unlike other operations, if the length of the coefficient after the quantize\n\
operation would be greater than precision, then an InvalidOperation is signaled.\n\
This guarantees that, unless there is an error condition, the quantized exponent\n\
is always equal to that of the right-hand operand.\n\
\n\
Also unlike other operations, quantize never signals Underflow, even if the\n\
result is subnormal and inexact.\n\
\n\
If the exponent of the second operand is larger than that of the first, then\n\
rounding may be necessary. In this case, the rounding mode is determined by the\n\
rounding argument if given, else by the given context argument; if neither\n\
argument is given, the rounding mode of the current thread's context is used.\n\
\n");
PyDoc_STRVAR(doc_radix,
"radix($self, /)\n--\n\n\
Return Decimal(10), the radix (base) in which the Decimal class does\n\
all its arithmetic. Included for compatibility with the specification.\n\
\n");
PyDoc_STRVAR(doc_remainder_near,
"remainder_near($self, /, other, context=None)\n--\n\n\
Return the remainder from dividing self by other. This differs from\n\
self % other in that the sign of the remainder is chosen so as to minimize\n\
its absolute value. More precisely, the return value is self - n * other\n\
where n is the integer nearest to the exact value of self / other, and\n\
if two integers are equally near then the even one is chosen.\n\
\n\
If the result is zero then its sign will be the sign of self.\n\
\n");
PyDoc_STRVAR(doc_rotate,
"rotate($self, /, other, context=None)\n--\n\n\
Return the result of rotating the digits of the first operand by an amount\n\
specified by the second operand. The second operand must be an integer in\n\
the range -precision through precision. The absolute value of the second\n\
operand gives the number of places to rotate. If the second operand is\n\
positive then rotation is to the left; otherwise rotation is to the right.\n\
The coefficient of the first operand is padded on the left with zeros to\n\
length precision if necessary. The sign and exponent of the first operand are\n\
unchanged.\n\
\n");
PyDoc_STRVAR(doc_same_quantum,
"same_quantum($self, /, other, context=None)\n--\n\n\
Test whether self and other have the same exponent or whether both are NaN.\n\
\n\
This operation is unaffected by context and is quiet: no flags are changed\n\
and no rounding is performed. As an exception, the C version may raise\n\
InvalidOperation if the second operand cannot be converted exactly.\n\
\n");
PyDoc_STRVAR(doc_scaleb,
"scaleb($self, /, other, context=None)\n--\n\n\
Return the first operand with the exponent adjusted the second. Equivalently,\n\
return the first operand multiplied by 10**other. The second operand must be\n\
an integer.\n\
\n");
PyDoc_STRVAR(doc_shift,
"shift($self, /, other, context=None)\n--\n\n\
Return the result of shifting the digits of the first operand by an amount\n\
specified by the second operand. The second operand must be an integer in\n\
the range -precision through precision. The absolute value of the second\n\
operand gives the number of places to shift. If the second operand is\n\
positive, then the shift is to the left; otherwise the shift is to the\n\
right. Digits shifted into the coefficient are zeros. The sign and exponent\n\
of the first operand are unchanged.\n\
\n");
PyDoc_STRVAR(doc_sqrt,
"sqrt($self, /, context=None)\n--\n\n\
Return the square root of the argument to full precision. The result is\n\
correctly rounded using the ROUND_HALF_EVEN rounding mode.\n\
\n");
PyDoc_STRVAR(doc_to_eng_string,
"to_eng_string($self, /, context=None)\n--\n\n\
Convert to an engineering-type string. Engineering notation has an exponent\n\
which is a multiple of 3, so there are up to 3 digits left of the decimal\n\
place. For example, Decimal('123E+1') is converted to Decimal('1.23E+3').\n\
\n\
The value of context.capitals determines whether the exponent sign is lower\n\
or upper case. Otherwise, the context does not affect the operation.\n\
\n");
PyDoc_STRVAR(doc_to_integral,
"to_integral($self, /, rounding=None, context=None)\n--\n\n\
Identical to the to_integral_value() method. The to_integral() name has been\n\
kept for compatibility with older versions.\n\
\n");
PyDoc_STRVAR(doc_to_integral_exact,
"to_integral_exact($self, /, rounding=None, context=None)\n--\n\n\
Round to the nearest integer, signaling Inexact or Rounded as appropriate if\n\
rounding occurs. The rounding mode is determined by the rounding parameter\n\
if given, else by the given context. If neither parameter is given, then the\n\
rounding mode of the current default context is used.\n\
\n");
PyDoc_STRVAR(doc_to_integral_value,
"to_integral_value($self, /, rounding=None, context=None)\n--\n\n\
Round to the nearest integer without signaling Inexact or Rounded. The\n\
rounding mode is determined by the rounding parameter if given, else by\n\
the given context. If neither parameter is given, then the rounding mode\n\
of the current default context is used.\n\
\n");
/******************************************************************************/
/* Context Object and Methods */
/******************************************************************************/
PyDoc_STRVAR(doc_context,
"Context(prec=None, rounding=None, Emin=None, Emax=None, capitals=None, clamp=None, flags=None, traps=None)\n--\n\n\
The context affects almost all operations and controls rounding,\n\
Over/Underflow, raising of exceptions and much more. A new context\n\
can be constructed as follows:\n\
\n\
>>> c = Context(prec=28, Emin=-425000000, Emax=425000000,\n\
... rounding=ROUND_HALF_EVEN, capitals=1, clamp=1,\n\
... traps=[InvalidOperation, DivisionByZero, Overflow],\n\
... flags=[])\n\
>>>\n\
\n\
\n");
#ifdef EXTRA_FUNCTIONALITY
PyDoc_STRVAR(doc_ctx_apply,
"apply($self, x, /)\n--\n\n\
Apply self to Decimal x.\n\
\n");
#endif
PyDoc_STRVAR(doc_ctx_clear_flags,
"clear_flags($self, /)\n--\n\n\
Reset all flags to False.\n\
\n");
PyDoc_STRVAR(doc_ctx_clear_traps,
"clear_traps($self, /)\n--\n\n\
Set all traps to False.\n\
\n");
PyDoc_STRVAR(doc_ctx_copy,
"copy($self, /)\n--\n\n\
Return a duplicate of the context with all flags cleared.\n\
\n");
PyDoc_STRVAR(doc_ctx_copy_decimal,
"copy_decimal($self, x, /)\n--\n\n\
Return a copy of Decimal x.\n\
\n");
PyDoc_STRVAR(doc_ctx_create_decimal,
"create_decimal($self, num=\"0\", /)\n--\n\n\
Create a new Decimal instance from num, using self as the context. Unlike the\n\
Decimal constructor, this function observes the context limits.\n\
\n");
PyDoc_STRVAR(doc_ctx_create_decimal_from_float,
"create_decimal_from_float($self, f, /)\n--\n\n\
Create a new Decimal instance from float f. Unlike the Decimal.from_float()\n\
class method, this function observes the context limits.\n\
\n");
PyDoc_STRVAR(doc_ctx_Etiny,
"Etiny($self, /)\n--\n\n\
Return a value equal to Emin - prec + 1, which is the minimum exponent value\n\
for subnormal results. When underflow occurs, the exponent is set to Etiny.\n\
\n");
PyDoc_STRVAR(doc_ctx_Etop,
"Etop($self, /)\n--\n\n\
Return a value equal to Emax - prec + 1. This is the maximum exponent\n\
if the _clamp field of the context is set to 1 (IEEE clamp mode). Etop()\n\
must not be negative.\n\
\n");
PyDoc_STRVAR(doc_ctx_abs,
"abs($self, x, /)\n--\n\n\
Return the absolute value of x.\n\
\n");
PyDoc_STRVAR(doc_ctx_add,
"add($self, x, y, /)\n--\n\n\
Return the sum of x and y.\n\
\n");
PyDoc_STRVAR(doc_ctx_canonical,
"canonical($self, x, /)\n--\n\n\
Return a new instance of x.\n\
\n");
PyDoc_STRVAR(doc_ctx_compare,
"compare($self, x, y, /)\n--\n\n\
Compare x and y numerically.\n\
\n");
PyDoc_STRVAR(doc_ctx_compare_signal,
"compare_signal($self, x, y, /)\n--\n\n\
Compare x and y numerically. All NaNs signal.\n\
\n");
PyDoc_STRVAR(doc_ctx_compare_total,
"compare_total($self, x, y, /)\n--\n\n\
Compare x and y using their abstract representation.\n\
\n");
PyDoc_STRVAR(doc_ctx_compare_total_mag,
"compare_total_mag($self, x, y, /)\n--\n\n\
Compare x and y using their abstract representation, ignoring sign.\n\
\n");
PyDoc_STRVAR(doc_ctx_copy_abs,
"copy_abs($self, x, /)\n--\n\n\
Return a copy of x with the sign set to 0.\n\
\n");
PyDoc_STRVAR(doc_ctx_copy_negate,
"copy_negate($self, x, /)\n--\n\n\
Return a copy of x with the sign inverted.\n\
\n");
PyDoc_STRVAR(doc_ctx_copy_sign,
"copy_sign($self, x, y, /)\n--\n\n\
Copy the sign from y to x.\n\
\n");
PyDoc_STRVAR(doc_ctx_divide,
"divide($self, x, y, /)\n--\n\n\
Return x divided by y.\n\
\n");
PyDoc_STRVAR(doc_ctx_divide_int,
"divide_int($self, x, y, /)\n--\n\n\
Return x divided by y, truncated to an integer.\n\
\n");
PyDoc_STRVAR(doc_ctx_divmod,
"divmod($self, x, y, /)\n--\n\n\
Return quotient and remainder of the division x / y.\n\
\n");
PyDoc_STRVAR(doc_ctx_exp,
"exp($self, x, /)\n--\n\n\
Return e ** x.\n\
\n");
PyDoc_STRVAR(doc_ctx_fma,
"fma($self, x, y, z, /)\n--\n\n\
Return x multiplied by y, plus z.\n\
\n");
PyDoc_STRVAR(doc_ctx_is_canonical,
"is_canonical($self, x, /)\n--\n\n\
Return True if x is canonical, False otherwise.\n\
\n");
PyDoc_STRVAR(doc_ctx_is_finite,
"is_finite($self, x, /)\n--\n\n\
Return True if x is finite, False otherwise.\n\
\n");
PyDoc_STRVAR(doc_ctx_is_infinite,
"is_infinite($self, x, /)\n--\n\n\
Return True if x is infinite, False otherwise.\n\
\n");
PyDoc_STRVAR(doc_ctx_is_nan,
"is_nan($self, x, /)\n--\n\n\
Return True if x is a qNaN or sNaN, False otherwise.\n\
\n");
PyDoc_STRVAR(doc_ctx_is_normal,
"is_normal($self, x, /)\n--\n\n\
Return True if x is a normal number, False otherwise.\n\
\n");
PyDoc_STRVAR(doc_ctx_is_qnan,
"is_qnan($self, x, /)\n--\n\n\
Return True if x is a quiet NaN, False otherwise.\n\
\n");
PyDoc_STRVAR(doc_ctx_is_signed,
"is_signed($self, x, /)\n--\n\n\
Return True if x is negative, False otherwise.\n\
\n");
PyDoc_STRVAR(doc_ctx_is_snan,
"is_snan($self, x, /)\n--\n\n\
Return True if x is a signaling NaN, False otherwise.\n\
\n");
PyDoc_STRVAR(doc_ctx_is_subnormal,
"is_subnormal($self, x, /)\n--\n\n\
Return True if x is subnormal, False otherwise.\n\
\n");
PyDoc_STRVAR(doc_ctx_is_zero,
"is_zero($self, x, /)\n--\n\n\
Return True if x is a zero, False otherwise.\n\
\n");
PyDoc_STRVAR(doc_ctx_ln,
"ln($self, x, /)\n--\n\n\
Return the natural (base e) logarithm of x.\n\
\n");
PyDoc_STRVAR(doc_ctx_log10,
"log10($self, x, /)\n--\n\n\
Return the base 10 logarithm of x.\n\
\n");
PyDoc_STRVAR(doc_ctx_logb,
"logb($self, x, /)\n--\n\n\
Return the exponent of the magnitude of the operand's MSD.\n\
\n");
PyDoc_STRVAR(doc_ctx_logical_and,
"logical_and($self, x, y, /)\n--\n\n\
Digit-wise and of x and y.\n\
\n");
PyDoc_STRVAR(doc_ctx_logical_invert,
"logical_invert($self, x, /)\n--\n\n\
Invert all digits of x.\n\
\n");
PyDoc_STRVAR(doc_ctx_logical_or,
"logical_or($self, x, y, /)\n--\n\n\
Digit-wise or of x and y.\n\
\n");
PyDoc_STRVAR(doc_ctx_logical_xor,
"logical_xor($self, x, y, /)\n--\n\n\
Digit-wise xor of x and y.\n\
\n");
PyDoc_STRVAR(doc_ctx_max,
"max($self, x, y, /)\n--\n\n\
Compare the values numerically and return the maximum.\n\
\n");
PyDoc_STRVAR(doc_ctx_max_mag,
"max_mag($self, x, y, /)\n--\n\n\
Compare the values numerically with their sign ignored.\n\
\n");
PyDoc_STRVAR(doc_ctx_min,
"min($self, x, y, /)\n--\n\n\
Compare the values numerically and return the minimum.\n\
\n");
PyDoc_STRVAR(doc_ctx_min_mag,
"min_mag($self, x, y, /)\n--\n\n\
Compare the values numerically with their sign ignored.\n\
\n");
PyDoc_STRVAR(doc_ctx_minus,
"minus($self, x, /)\n--\n\n\
Minus corresponds to the unary prefix minus operator in Python, but applies\n\
the context to the result.\n\
\n");
PyDoc_STRVAR(doc_ctx_multiply,
"multiply($self, x, y, /)\n--\n\n\
Return the product of x and y.\n\
\n");
PyDoc_STRVAR(doc_ctx_next_minus,
"next_minus($self, x, /)\n--\n\n\
Return the largest representable number smaller than x.\n\
\n");
PyDoc_STRVAR(doc_ctx_next_plus,
"next_plus($self, x, /)\n--\n\n\
Return the smallest representable number larger than x.\n\
\n");
PyDoc_STRVAR(doc_ctx_next_toward,
"next_toward($self, x, y, /)\n--\n\n\
Return the number closest to x, in the direction towards y.\n\
\n");
PyDoc_STRVAR(doc_ctx_normalize,
"normalize($self, x, /)\n--\n\n\
Reduce x to its simplest form. Alias for reduce(x).\n\
\n");
PyDoc_STRVAR(doc_ctx_number_class,
"number_class($self, x, /)\n--\n\n\
Return an indication of the class of x.\n\
\n");
PyDoc_STRVAR(doc_ctx_plus,
"plus($self, x, /)\n--\n\n\
Plus corresponds to the unary prefix plus operator in Python, but applies\n\
the context to the result.\n\
\n");
PyDoc_STRVAR(doc_ctx_power,
"power($self, /, a, b, modulo=None)\n--\n\n\
Compute a**b. If 'a' is negative, then 'b' must be integral. The result\n\
will be inexact unless 'a' is integral and the result is finite and can\n\
be expressed exactly in 'precision' digits. In the Python version the\n\
result is always correctly rounded, in the C version the result is almost\n\
always correctly rounded.\n\
\n\
If modulo is given, compute (a**b) % modulo. The following restrictions\n\
hold:\n\
\n\
* all three arguments must be integral\n\
* 'b' must be nonnegative\n\
* at least one of 'a' or 'b' must be nonzero\n\
* modulo must be nonzero and less than 10**prec in absolute value\n\
\n\
\n");
PyDoc_STRVAR(doc_ctx_quantize,
"quantize($self, x, y, /)\n--\n\n\
Return a value equal to x (rounded), having the exponent of y.\n\
\n");
PyDoc_STRVAR(doc_ctx_radix,
"radix($self, /)\n--\n\n\
Return 10.\n\
\n");
PyDoc_STRVAR(doc_ctx_remainder,
"remainder($self, x, y, /)\n--\n\n\
Return the remainder from integer division. The sign of the result,\n\
if non-zero, is the same as that of the original dividend.\n\
\n");
PyDoc_STRVAR(doc_ctx_remainder_near,
"remainder_near($self, x, y, /)\n--\n\n\
Return x - y * n, where n is the integer nearest the exact value of x / y\n\
(if the result is 0 then its sign will be the sign of x).\n\
\n");
PyDoc_STRVAR(doc_ctx_rotate,
"rotate($self, x, y, /)\n--\n\n\
Return a copy of x, rotated by y places.\n\
\n");
PyDoc_STRVAR(doc_ctx_same_quantum,
"same_quantum($self, x, y, /)\n--\n\n\
Return True if the two operands have the same exponent.\n\
\n");
PyDoc_STRVAR(doc_ctx_scaleb,
"scaleb($self, x, y, /)\n--\n\n\
Return the first operand after adding the second value to its exp.\n\
\n");
PyDoc_STRVAR(doc_ctx_shift,
"shift($self, x, y, /)\n--\n\n\
Return a copy of x, shifted by y places.\n\
\n");
PyDoc_STRVAR(doc_ctx_sqrt,
"sqrt($self, x, /)\n--\n\n\
Square root of a non-negative number to context precision.\n\
\n");
PyDoc_STRVAR(doc_ctx_subtract,
"subtract($self, x, y, /)\n--\n\n\
Return the difference between x and y.\n\
\n");
PyDoc_STRVAR(doc_ctx_to_eng_string,
"to_eng_string($self, x, /)\n--\n\n\
Convert a number to a string, using engineering notation.\n\
\n");
PyDoc_STRVAR(doc_ctx_to_integral,
"to_integral($self, x, /)\n--\n\n\
Identical to to_integral_value(x).\n\
\n");
PyDoc_STRVAR(doc_ctx_to_integral_exact,
"to_integral_exact($self, x, /)\n--\n\n\
Round to an integer. Signal if the result is rounded or inexact.\n\
\n");
PyDoc_STRVAR(doc_ctx_to_integral_value,
"to_integral_value($self, x, /)\n--\n\n\
Round to an integer.\n\
\n");
PyDoc_STRVAR(doc_ctx_to_sci_string,
"to_sci_string($self, x, /)\n--\n\n\
Convert a number to a string using scientific notation.\n\
\n");
#endif /* DOCSTRINGS_H */
| 29,014 | 879 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Modules/_decimal/_decimal.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:8;coding:utf-8 -*-â
âvi: set net ft=c ts=4 sts=4 sw=4 fenc=utf-8 :viâ
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ¡
â Copyright (c) 2008-2016 Stefan Krah. All rights reserved. â
â â
â Redistribution and use in source and binary forms, with or without â
â modification, are permitted provided that the following conditions â
â are met: â
â â
â 1. Redistributions of source code must retain the above copyright â
â notice, this list of conditions and the following disclaimer. â
â â
â 2. Redistributions in binary form must reproduce the above copyright â
â notice, this list of conditions and the following disclaimer in â
â the documentation and/or other materials provided with the â
â distribution. â
â â
â THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS "AS IS" AND â
â ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE â
â IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR â
â PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS â
â BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, â
â OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT â
â OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR â
â BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, â
â WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE â
â OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, â
â EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
#include "libc/fmt/fmt.h"
#include "third_party/python/Include/abstract.h"
#include "third_party/python/Include/boolobject.h"
#include "third_party/python/Include/complexobject.h"
#include "third_party/python/Include/descrobject.h"
#include "third_party/python/Include/dictobject.h"
#include "third_party/python/Include/floatobject.h"
#include "third_party/python/Include/import.h"
#include "third_party/python/Include/listobject.h"
#include "third_party/python/Include/longintrepr.h"
#include "third_party/python/Include/modsupport.h"
#include "third_party/python/Include/objimpl.h"
#include "third_party/python/Include/pyerrors.h"
#include "third_party/python/Include/pyhash.h"
#include "third_party/python/Include/pystate.h"
#include "third_party/python/Include/pythread.h"
#include "third_party/python/Include/structmember.h"
#include "third_party/python/Include/tupleobject.h"
#include "third_party/python/Include/yoink.h"
#include "third_party/python/Modules/_decimal/docstrings.h"
#include "third_party/python/Modules/_decimal/libmpdec/mpdecimal.h"
/* clang-format off */
PYTHON_PROVIDE("_decimal");
PYTHON_PROVIDE("_decimal.BasicContext");
PYTHON_PROVIDE("_decimal.Clamped");
PYTHON_PROVIDE("_decimal.Context");
PYTHON_PROVIDE("_decimal.ConversionSyntax");
PYTHON_PROVIDE("_decimal.Decimal");
PYTHON_PROVIDE("_decimal.DecimalException");
PYTHON_PROVIDE("_decimal.DecimalTuple");
PYTHON_PROVIDE("_decimal.DefaultContext");
PYTHON_PROVIDE("_decimal.DivisionByZero");
PYTHON_PROVIDE("_decimal.DivisionImpossible");
PYTHON_PROVIDE("_decimal.DivisionUndefined");
PYTHON_PROVIDE("_decimal.ExtendedContext");
PYTHON_PROVIDE("_decimal.FloatOperation");
PYTHON_PROVIDE("_decimal.HAVE_THREADS");
PYTHON_PROVIDE("_decimal.Inexact");
PYTHON_PROVIDE("_decimal.InvalidContext");
PYTHON_PROVIDE("_decimal.InvalidOperation");
PYTHON_PROVIDE("_decimal.MAX_EMAX");
PYTHON_PROVIDE("_decimal.MAX_PREC");
PYTHON_PROVIDE("_decimal.MIN_EMIN");
PYTHON_PROVIDE("_decimal.MIN_ETINY");
PYTHON_PROVIDE("_decimal.Overflow");
PYTHON_PROVIDE("_decimal.ROUND_05UP");
PYTHON_PROVIDE("_decimal.ROUND_CEILING");
PYTHON_PROVIDE("_decimal.ROUND_DOWN");
PYTHON_PROVIDE("_decimal.ROUND_FLOOR");
PYTHON_PROVIDE("_decimal.ROUND_HALF_DOWN");
PYTHON_PROVIDE("_decimal.ROUND_HALF_EVEN");
PYTHON_PROVIDE("_decimal.ROUND_HALF_UP");
PYTHON_PROVIDE("_decimal.ROUND_UP");
PYTHON_PROVIDE("_decimal.Rounded");
PYTHON_PROVIDE("_decimal.Subnormal");
PYTHON_PROVIDE("_decimal.Underflow");
PYTHON_PROVIDE("_decimal.__doc__");
PYTHON_PROVIDE("_decimal.__libmpdec_version__");
PYTHON_PROVIDE("_decimal.__loader__");
PYTHON_PROVIDE("_decimal.__name__");
PYTHON_PROVIDE("_decimal.__package__");
PYTHON_PROVIDE("_decimal.__spec__");
PYTHON_PROVIDE("_decimal.__version__");
PYTHON_PROVIDE("_decimal.getcontext");
PYTHON_PROVIDE("_decimal.localcontext");
PYTHON_PROVIDE("_decimal.setcontext");
PYTHON_YOINK("numbers");
PYTHON_YOINK("collections");
asm(".ident\t\"\\n\
libmpdec (BSD-2)\\n\
Copyright 2008-2016 Stefan Krah\"");
asm(".include \"libc/disclaimer.inc\"");
#if !defined(MPD_VERSION_HEX) || MPD_VERSION_HEX < 0x02040100
#error "libmpdec version >= 2.4.1 required"
#endif
/*
* Type sizes with assertions in mpdecimal.h and pyport.h:
* sizeof(size_t) == sizeof(Py_ssize_t)
* sizeof(size_t) == sizeof(mpd_uint_t) == sizeof(mpd_ssize_t)
*/
#ifdef TEST_COVERAGE
#undef Py_LOCAL_INLINE
#define Py_LOCAL_INLINE Py_LOCAL
#endif
#define MPD_Float_operation MPD_Not_implemented
#define BOUNDS_CHECK(x, MIN, MAX) x = (x < MIN || MAX < x) ? MAX : x
/* _Py_DEC_MINALLOC >= MPD_MINALLOC */
#define _Py_DEC_MINALLOC 4
typedef struct {
PyObject_HEAD
Py_hash_t hash;
mpd_t dec;
mpd_uint_t data[_Py_DEC_MINALLOC];
} PyDecObject;
typedef struct {
PyObject_HEAD
uint32_t *flags;
} PyDecSignalDictObject;
typedef struct {
PyObject_HEAD
mpd_context_t ctx;
PyObject *traps;
PyObject *flags;
int capitals;
#ifndef WITHOUT_THREADS
PyThreadState *tstate;
#endif
} PyDecContextObject;
typedef struct {
PyObject_HEAD
PyObject *local;
PyObject *global;
} PyDecContextManagerObject;
#undef MPD
#undef CTX
static PyTypeObject PyDec_Type;
static PyTypeObject *PyDecSignalDict_Type;
static PyTypeObject PyDecContext_Type;
static PyTypeObject PyDecContextManager_Type;
#define PyDec_CheckExact(v) (Py_TYPE(v) == &PyDec_Type)
#define PyDec_Check(v) PyObject_TypeCheck(v, &PyDec_Type)
#define PyDecSignalDict_Check(v) (Py_TYPE(v) == PyDecSignalDict_Type)
#define PyDecContext_Check(v) PyObject_TypeCheck(v, &PyDecContext_Type)
#define MPD(v) (&((PyDecObject *)v)->dec)
#define SdFlagAddr(v) (((PyDecSignalDictObject *)v)->flags)
#define SdFlags(v) (*((PyDecSignalDictObject *)v)->flags)
#define CTX(v) (&((PyDecContextObject *)v)->ctx)
#define CtxCaps(v) (((PyDecContextObject *)v)->capitals)
Py_LOCAL_INLINE(PyObject *)
incr_true(void)
{
Py_INCREF(Py_True);
return Py_True;
}
Py_LOCAL_INLINE(PyObject *)
incr_false(void)
{
Py_INCREF(Py_False);
return Py_False;
}
#ifdef WITHOUT_THREADS
/* Default module context */
static PyObject *module_context = NULL;
#else
/* Key for thread state dictionary */
static PyObject *tls_context_key = NULL;
/* Invariant: NULL or the most recently accessed thread local context */
static PyDecContextObject *cached_context = NULL;
#endif
/* Template for creating new thread contexts, calling Context() without
* arguments and initializing the module_context on first access. */
static PyObject *default_context_template = NULL;
/* Basic and extended context templates */
static PyObject *basic_context_template = NULL;
static PyObject *extended_context_template = NULL;
/* Error codes for functions that return signals or conditions */
#define DEC_INVALID_SIGNALS (MPD_Max_status+1U)
#define DEC_ERR_OCCURRED (DEC_INVALID_SIGNALS<<1)
#define DEC_ERRORS (DEC_INVALID_SIGNALS|DEC_ERR_OCCURRED)
typedef struct {
const char *name; /* condition or signal name */
const char *fqname; /* fully qualified name */
uint32_t flag; /* libmpdec flag */
PyObject *ex; /* corresponding exception */
} DecCondMap;
/* Top level Exception; inherits from ArithmeticError */
static PyObject *DecimalException = NULL;
/* Exceptions that correspond to IEEE signals */
#define SUBNORMAL 5
#define INEXACT 6
#define ROUNDED 7
#define SIGNAL_MAP_LEN 9
static DecCondMap signal_map[] = {
{"InvalidOperation", "decimal.InvalidOperation", MPD_IEEE_Invalid_operation, NULL},
{"FloatOperation", "decimal.FloatOperation", MPD_Float_operation, NULL},
{"DivisionByZero", "decimal.DivisionByZero", MPD_Division_by_zero, NULL},
{"Overflow", "decimal.Overflow", MPD_Overflow, NULL},
{"Underflow", "decimal.Underflow", MPD_Underflow, NULL},
{"Subnormal", "decimal.Subnormal", MPD_Subnormal, NULL},
{"Inexact", "decimal.Inexact", MPD_Inexact, NULL},
{"Rounded", "decimal.Rounded", MPD_Rounded, NULL},
{"Clamped", "decimal.Clamped", MPD_Clamped, NULL},
{NULL}
};
/* Exceptions that inherit from InvalidOperation */
static DecCondMap cond_map[] = {
{"InvalidOperation", "decimal.InvalidOperation", MPD_Invalid_operation, NULL},
{"ConversionSyntax", "decimal.ConversionSyntax", MPD_Conversion_syntax, NULL},
{"DivisionImpossible", "decimal.DivisionImpossible", MPD_Division_impossible, NULL},
{"DivisionUndefined", "decimal.DivisionUndefined", MPD_Division_undefined, NULL},
{"InvalidContext", "decimal.InvalidContext", MPD_Invalid_context, NULL},
#ifdef EXTRA_FUNCTIONALITY
{"MallocError", "decimal.MallocError", MPD_Malloc_error, NULL},
#endif
{NULL}
};
static const char *dec_signal_string[MPD_NUM_FLAGS] = {
"Clamped",
"InvalidOperation",
"DivisionByZero",
"InvalidOperation",
"InvalidOperation",
"InvalidOperation",
"Inexact",
"InvalidOperation",
"InvalidOperation",
"InvalidOperation",
"FloatOperation",
"Overflow",
"Rounded",
"Subnormal",
"Underflow",
};
#ifdef EXTRA_FUNCTIONALITY
#define _PY_DEC_ROUND_GUARD MPD_ROUND_GUARD
#else
#define _PY_DEC_ROUND_GUARD (MPD_ROUND_GUARD-1)
#endif
static PyObject *round_map[_PY_DEC_ROUND_GUARD];
static const char *invalid_rounding_err =
"valid values for rounding are:\n\
[ROUND_CEILING, ROUND_FLOOR, ROUND_UP, ROUND_DOWN,\n\
ROUND_HALF_UP, ROUND_HALF_DOWN, ROUND_HALF_EVEN,\n\
ROUND_05UP]";
static const char *invalid_signals_err =
"valid values for signals are:\n\
[InvalidOperation, FloatOperation, DivisionByZero,\n\
Overflow, Underflow, Subnormal, Inexact, Rounded,\n\
Clamped]";
#ifdef EXTRA_FUNCTIONALITY
static const char *invalid_flags_err =
"valid values for _flags or _traps are:\n\
signals:\n\
[DecIEEEInvalidOperation, DecFloatOperation, DecDivisionByZero,\n\
DecOverflow, DecUnderflow, DecSubnormal, DecInexact, DecRounded,\n\
DecClamped]\n\
conditions which trigger DecIEEEInvalidOperation:\n\
[DecInvalidOperation, DecConversionSyntax, DecDivisionImpossible,\n\
DecDivisionUndefined, DecFpuError, DecInvalidContext, DecMallocError]";
#endif
static int
value_error_int(const char *mesg)
{
PyErr_SetString(PyExc_ValueError, mesg);
return -1;
}
#ifdef CONFIG_32
static PyObject *
value_error_ptr(const char *mesg)
{
PyErr_SetString(PyExc_ValueError, mesg);
return NULL;
}
#endif
static int
type_error_int(const char *mesg)
{
PyErr_SetString(PyExc_TypeError, mesg);
return -1;
}
static int
runtime_error_int(const char *mesg)
{
PyErr_SetString(PyExc_RuntimeError, mesg);
return -1;
}
#define INTERNAL_ERROR_INT(funcname) \
return runtime_error_int("internal error in " funcname)
static PyObject *
runtime_error_ptr(const char *mesg)
{
PyErr_SetString(PyExc_RuntimeError, mesg);
return NULL;
}
#define INTERNAL_ERROR_PTR(funcname) \
return runtime_error_ptr("internal error in " funcname)
static void
dec_traphandler(mpd_context_t *ctx)
{
(void)ctx;
return; /* GCOV_NOT_REACHED */
}
static PyObject *
flags_as_exception(uint32_t flags)
{
DecCondMap *cm;
for (cm = signal_map; cm->name != NULL; cm++) {
if (flags&cm->flag) {
return cm->ex;
}
}
INTERNAL_ERROR_PTR("flags_as_exception");
}
Py_LOCAL_INLINE(uint32_t)
exception_as_flag(PyObject *ex)
{
DecCondMap *cm;
for (cm = signal_map; cm->name != NULL; cm++) {
if (cm->ex == ex) {
return cm->flag;
}
}
PyErr_SetString(PyExc_KeyError, invalid_signals_err);
return DEC_INVALID_SIGNALS;
}
static PyObject *
flags_as_list(uint32_t flags)
{
PyObject *list;
DecCondMap *cm;
list = PyList_New(0);
if (list == NULL) {
return NULL;
}
for (cm = cond_map; cm->name != NULL; cm++) {
if (flags&cm->flag) {
if (PyList_Append(list, cm->ex) < 0) {
goto error;
}
}
}
for (cm = signal_map+1; cm->name != NULL; cm++) {
if (flags&cm->flag) {
if (PyList_Append(list, cm->ex) < 0) {
goto error;
}
}
}
return list;
error:
Py_DECREF(list);
return NULL;
}
static PyObject *
signals_as_list(uint32_t flags)
{
PyObject *list;
DecCondMap *cm;
list = PyList_New(0);
if (list == NULL) {
return NULL;
}
for (cm = signal_map; cm->name != NULL; cm++) {
if (flags&cm->flag) {
if (PyList_Append(list, cm->ex) < 0) {
Py_DECREF(list);
return NULL;
}
}
}
return list;
}
static uint32_t
list_as_flags(PyObject *list)
{
PyObject *item;
uint32_t flags, x;
Py_ssize_t n, j;
assert(PyList_Check(list));
n = PyList_Size(list);
flags = 0;
for (j = 0; j < n; j++) {
item = PyList_GetItem(list, j);
x = exception_as_flag(item);
if (x & DEC_ERRORS) {
return x;
}
flags |= x;
}
return flags;
}
static PyObject *
flags_as_dict(uint32_t flags)
{
DecCondMap *cm;
PyObject *dict;
dict = PyDict_New();
if (dict == NULL) {
return NULL;
}
for (cm = signal_map; cm->name != NULL; cm++) {
PyObject *b = flags&cm->flag ? Py_True : Py_False;
if (PyDict_SetItem(dict, cm->ex, b) < 0) {
Py_DECREF(dict);
return NULL;
}
}
return dict;
}
static uint32_t
dict_as_flags(PyObject *val)
{
PyObject *b;
DecCondMap *cm;
uint32_t flags = 0;
int x;
if (!PyDict_Check(val)) {
PyErr_SetString(PyExc_TypeError,
"argument must be a signal dict");
return DEC_INVALID_SIGNALS;
}
if (PyDict_Size(val) != SIGNAL_MAP_LEN) {
PyErr_SetString(PyExc_KeyError,
"invalid signal dict");
return DEC_INVALID_SIGNALS;
}
for (cm = signal_map; cm->name != NULL; cm++) {
b = PyDict_GetItemWithError(val, cm->ex);
if (b == NULL) {
if (PyErr_Occurred()) {
return DEC_ERR_OCCURRED;
}
PyErr_SetString(PyExc_KeyError,
"invalid signal dict");
return DEC_INVALID_SIGNALS;
}
x = PyObject_IsTrue(b);
if (x < 0) {
return DEC_ERR_OCCURRED;
}
if (x == 1) {
flags |= cm->flag;
}
}
return flags;
}
#ifdef EXTRA_FUNCTIONALITY
static uint32_t
long_as_flags(PyObject *v)
{
long x;
x = PyLong_AsLong(v);
if (x == -1 && PyErr_Occurred()) {
return DEC_ERR_OCCURRED;
}
if (x < 0 || x > (long)MPD_Max_status) {
PyErr_SetString(PyExc_TypeError, invalid_flags_err);
return DEC_INVALID_SIGNALS;
}
return x;
}
#endif
static int
dec_addstatus(PyObject *context, uint32_t status)
{
mpd_context_t *ctx = CTX(context);
ctx->status |= status;
if (status & (ctx->traps|MPD_Malloc_error)) {
PyObject *ex, *siglist;
if (status & MPD_Malloc_error) {
PyErr_NoMemory();
return 1;
}
ex = flags_as_exception(ctx->traps&status);
if (ex == NULL) {
return 1; /* GCOV_NOT_REACHED */
}
siglist = flags_as_list(ctx->traps&status);
if (siglist == NULL) {
return 1;
}
PyErr_SetObject(ex, siglist);
Py_DECREF(siglist);
return 1;
}
return 0;
}
static int
getround(PyObject *v)
{
int i;
if (PyUnicode_Check(v)) {
for (i = 0; i < _PY_DEC_ROUND_GUARD; i++) {
if (v == round_map[i]) {
return i;
}
}
for (i = 0; i < _PY_DEC_ROUND_GUARD; i++) {
if (PyUnicode_Compare(v, round_map[i]) == 0) {
return i;
}
}
}
return type_error_int(invalid_rounding_err);
}
/******************************************************************************/
/* SignalDict Object */
/******************************************************************************/
/* The SignalDict is a MutableMapping that provides access to the
mpd_context_t flags, which reside in the context object. When a
new context is created, context.traps and context.flags are
initialized to new SignalDicts. Once a SignalDict is tied to
a context, it cannot be deleted. */
static int
signaldict_init(PyObject *self, PyObject *args, PyObject *kwds)
{
(void)args;
(void)kwds;
SdFlagAddr(self) = NULL;
return 0;
}
static Py_ssize_t
signaldict_len(PyObject *self)
{
(void)self;
return SIGNAL_MAP_LEN;
}
static PyObject *SignalTuple;
static PyObject *
signaldict_iter(PyObject *self)
{
(void)self;
return PyTuple_Type.tp_iter(SignalTuple);
}
static PyObject *
signaldict_getitem(PyObject *self, PyObject *key)
{
uint32_t flag;
flag = exception_as_flag(key);
if (flag & DEC_ERRORS) {
return NULL;
}
return SdFlags(self)&flag ? incr_true() : incr_false();
}
static int
signaldict_setitem(PyObject *self, PyObject *key, PyObject *value)
{
uint32_t flag;
int x;
if (value == NULL) {
return value_error_int("signal keys cannot be deleted");
}
flag = exception_as_flag(key);
if (flag & DEC_ERRORS) {
return -1;
}
x = PyObject_IsTrue(value);
if (x < 0) {
return -1;
}
if (x == 1) {
SdFlags(self) |= flag;
}
else {
SdFlags(self) &= ~flag;
}
return 0;
}
static PyObject *
signaldict_repr(PyObject *self)
{
DecCondMap *cm;
const char *n[SIGNAL_MAP_LEN]; /* name */
const char *b[SIGNAL_MAP_LEN]; /* bool */
int i;
assert(SIGNAL_MAP_LEN == 9);
for (cm=signal_map, i=0; cm->name != NULL; cm++, i++) {
n[i] = cm->fqname;
b[i] = SdFlags(self)&cm->flag ? "True" : "False";
}
return PyUnicode_FromFormat(
"{<class '%s'>:%s, <class '%s'>:%s, <class '%s'>:%s, "
"<class '%s'>:%s, <class '%s'>:%s, <class '%s'>:%s, "
"<class '%s'>:%s, <class '%s'>:%s, <class '%s'>:%s}",
n[0], b[0], n[1], b[1], n[2], b[2],
n[3], b[3], n[4], b[4], n[5], b[5],
n[6], b[6], n[7], b[7], n[8], b[8]);
}
static PyObject *
signaldict_richcompare(PyObject *v, PyObject *w, int op)
{
PyObject *res = Py_NotImplemented;
assert(PyDecSignalDict_Check(v));
if (op == Py_EQ || op == Py_NE) {
if (PyDecSignalDict_Check(w)) {
res = (SdFlags(v)==SdFlags(w)) ^ (op==Py_NE) ? Py_True : Py_False;
}
else if (PyDict_Check(w)) {
uint32_t flags = dict_as_flags(w);
if (flags & DEC_ERRORS) {
if (flags & DEC_INVALID_SIGNALS) {
/* non-comparable: Py_NotImplemented */
PyErr_Clear();
}
else {
return NULL;
}
}
else {
res = (SdFlags(v)==flags) ^ (op==Py_NE) ? Py_True : Py_False;
}
}
}
Py_INCREF(res);
return res;
}
static PyObject *
signaldict_copy(PyObject *self, PyObject *args)
{
(void)args;
return flags_as_dict(SdFlags(self));
}
static PyMappingMethods signaldict_as_mapping = {
(lenfunc)signaldict_len, /* mp_length */
(binaryfunc)signaldict_getitem, /* mp_subscript */
(objobjargproc)signaldict_setitem /* mp_ass_subscript */
};
static PyMethodDef signaldict_methods[] = {
{ "copy", (PyCFunction)signaldict_copy, METH_NOARGS, NULL},
{NULL, NULL}
};
static PyTypeObject PyDecSignalDictMixin_Type =
{
PyVarObject_HEAD_INIT(0, 0)
"decimal.SignalDictMixin", /* tp_name */
sizeof(PyDecSignalDictObject), /* tp_basicsize */
0, /* tp_itemsize */
0, /* tp_dealloc */
0, /* tp_print */
(getattrfunc) 0, /* tp_getattr */
(setattrfunc) 0, /* tp_setattr */
0, /* tp_reserved */
(reprfunc) signaldict_repr, /* tp_repr */
0, /* tp_as_number */
0, /* tp_as_sequence */
&signaldict_as_mapping, /* tp_as_mapping */
PyObject_HashNotImplemented, /* tp_hash */
0, /* tp_call */
(reprfunc) 0, /* tp_str */
PyObject_GenericGetAttr, /* tp_getattro */
(setattrofunc) 0, /* tp_setattro */
(PyBufferProcs *) 0, /* tp_as_buffer */
Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE|
Py_TPFLAGS_HAVE_GC, /* tp_flags */
0, /* tp_doc */
0, /* tp_traverse */
0, /* tp_clear */
signaldict_richcompare, /* tp_richcompare */
0, /* tp_weaklistoffset */
(getiterfunc)signaldict_iter, /* tp_iter */
0, /* tp_iternext */
signaldict_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)signaldict_init, /* tp_init */
0, /* tp_alloc */
PyType_GenericNew, /* tp_new */
};
/******************************************************************************/
/* Context Object, Part 1 */
/******************************************************************************/
#define Dec_CONTEXT_GET_SSIZE(mem) \
static PyObject * \
context_get##mem(PyObject *self, void *closure) \
{ \
(void)closure; \
return PyLong_FromSsize_t(mpd_get##mem(CTX(self))); \
}
#define Dec_CONTEXT_GET_ULONG(mem) \
static PyObject * \
context_get##mem(PyObject *self, void *closure) \
{ \
(void)closure; \
return PyLong_FromUnsignedLong(mpd_get##mem(CTX(self))); \
}
Dec_CONTEXT_GET_SSIZE(prec)
Dec_CONTEXT_GET_SSIZE(emax)
Dec_CONTEXT_GET_SSIZE(emin)
Dec_CONTEXT_GET_SSIZE(clamp)
#ifdef EXTRA_FUNCTIONALITY
Dec_CONTEXT_GET_ULONG(traps)
Dec_CONTEXT_GET_ULONG(status)
#endif
static PyObject *
context_getround(PyObject *self, void *closure)
{
int i = mpd_getround(CTX(self));
Py_INCREF(round_map[i]);
return round_map[i];
}
static PyObject *
context_getcapitals(PyObject *self, void *closure)
{
return PyLong_FromLong(CtxCaps(self));
}
#ifdef EXTRA_FUNCTIONALITY
static PyObject *
context_getallcr(PyObject *self, void *closure)
{
return PyLong_FromLong(mpd_getcr(CTX(self)));
}
#endif
static PyObject *
context_getetiny(PyObject *self, PyObject *dummy)
{
return PyLong_FromSsize_t(mpd_etiny(CTX(self)));
}
static PyObject *
context_getetop(PyObject *self, PyObject *dummy)
{
return PyLong_FromSsize_t(mpd_etop(CTX(self)));
}
static int
context_setprec(PyObject *self, PyObject *value, void *closure)
{
mpd_context_t *ctx;
mpd_ssize_t x;
x = PyLong_AsSsize_t(value);
if (x == -1 && PyErr_Occurred()) {
return -1;
}
ctx = CTX(self);
if (!mpd_qsetprec(ctx, x)) {
return value_error_int(
"valid range for prec is [1, MAX_PREC]");
}
return 0;
}
static int
context_setemin(PyObject *self, PyObject *value, void *closure)
{
mpd_context_t *ctx;
mpd_ssize_t x;
x = PyLong_AsSsize_t(value);
if (x == -1 && PyErr_Occurred()) {
return -1;
}
ctx = CTX(self);
if (!mpd_qsetemin(ctx, x)) {
return value_error_int(
"valid range for Emin is [MIN_EMIN, 0]");
}
return 0;
}
static int
context_setemax(PyObject *self, PyObject *value, void *closure)
{
mpd_context_t *ctx;
mpd_ssize_t x;
x = PyLong_AsSsize_t(value);
if (x == -1 && PyErr_Occurred()) {
return -1;
}
ctx = CTX(self);
if (!mpd_qsetemax(ctx, x)) {
return value_error_int(
"valid range for Emax is [0, MAX_EMAX]");
}
return 0;
}
#ifdef CONFIG_32
static PyObject *
context_unsafe_setprec(PyObject *self, PyObject *value)
{
mpd_context_t *ctx = CTX(self);
mpd_ssize_t x;
x = PyLong_AsSsize_t(value);
if (x == -1 && PyErr_Occurred()) {
return NULL;
}
if (x < 1 || x > 1070000000L) {
return value_error_ptr(
"valid range for unsafe prec is [1, 1070000000]");
}
ctx->prec = x;
Py_RETURN_NONE;
}
static PyObject *
context_unsafe_setemin(PyObject *self, PyObject *value)
{
mpd_context_t *ctx = CTX(self);
mpd_ssize_t x;
x = PyLong_AsSsize_t(value);
if (x == -1 && PyErr_Occurred()) {
return NULL;
}
if (x < -1070000000L || x > 0) {
return value_error_ptr(
"valid range for unsafe emin is [-1070000000, 0]");
}
ctx->emin = x;
Py_RETURN_NONE;
}
static PyObject *
context_unsafe_setemax(PyObject *self, PyObject *value)
{
mpd_context_t *ctx = CTX(self);
mpd_ssize_t x;
x = PyLong_AsSsize_t(value);
if (x == -1 && PyErr_Occurred()) {
return NULL;
}
if (x < 0 || x > 1070000000L) {
return value_error_ptr(
"valid range for unsafe emax is [0, 1070000000]");
}
ctx->emax = x;
Py_RETURN_NONE;
}
#endif
static int
context_setround(PyObject *self, PyObject *value, void *closure)
{
mpd_context_t *ctx;
int x;
x = getround(value);
if (x == -1) {
return -1;
}
ctx = CTX(self);
if (!mpd_qsetround(ctx, x)) {
INTERNAL_ERROR_INT("context_setround"); /* GCOV_NOT_REACHED */
}
return 0;
}
static int
context_setcapitals(PyObject *self, PyObject *value, void *closure)
{
mpd_ssize_t x;
x = PyLong_AsSsize_t(value);
if (x == -1 && PyErr_Occurred()) {
return -1;
}
if (x != 0 && x != 1) {
return value_error_int(
"valid values for capitals are 0 or 1");
}
CtxCaps(self) = (int)x;
return 0;
}
#ifdef EXTRA_FUNCTIONALITY
static int
context_settraps(PyObject *self, PyObject *value, void *closure)
{
mpd_context_t *ctx;
uint32_t flags;
flags = long_as_flags(value);
if (flags & DEC_ERRORS) {
return -1;
}
ctx = CTX(self);
if (!mpd_qsettraps(ctx, flags)) {
INTERNAL_ERROR_INT("context_settraps");
}
return 0;
}
#endif
static int
context_settraps_list(PyObject *self, PyObject *value)
{
mpd_context_t *ctx;
uint32_t flags;
flags = list_as_flags(value);
if (flags & DEC_ERRORS) {
return -1;
}
ctx = CTX(self);
if (!mpd_qsettraps(ctx, flags)) {
INTERNAL_ERROR_INT("context_settraps_list");
}
return 0;
}
static int
context_settraps_dict(PyObject *self, PyObject *value)
{
mpd_context_t *ctx;
uint32_t flags;
if (PyDecSignalDict_Check(value)) {
flags = SdFlags(value);
}
else {
flags = dict_as_flags(value);
if (flags & DEC_ERRORS) {
return -1;
}
}
ctx = CTX(self);
if (!mpd_qsettraps(ctx, flags)) {
INTERNAL_ERROR_INT("context_settraps_dict");
}
return 0;
}
#ifdef EXTRA_FUNCTIONALITY
static int
context_setstatus(PyObject *self, PyObject *value, void *closure)
{
mpd_context_t *ctx;
uint32_t flags;
flags = long_as_flags(value);
if (flags & DEC_ERRORS) {
return -1;
}
ctx = CTX(self);
if (!mpd_qsetstatus(ctx, flags)) {
INTERNAL_ERROR_INT("context_setstatus");
}
return 0;
}
#endif
static int
context_setstatus_list(PyObject *self, PyObject *value)
{
mpd_context_t *ctx;
uint32_t flags;
flags = list_as_flags(value);
if (flags & DEC_ERRORS) {
return -1;
}
ctx = CTX(self);
if (!mpd_qsetstatus(ctx, flags)) {
INTERNAL_ERROR_INT("context_setstatus_list");
}
return 0;
}
static int
context_setstatus_dict(PyObject *self, PyObject *value)
{
mpd_context_t *ctx;
uint32_t flags;
if (PyDecSignalDict_Check(value)) {
flags = SdFlags(value);
}
else {
flags = dict_as_flags(value);
if (flags & DEC_ERRORS) {
return -1;
}
}
ctx = CTX(self);
if (!mpd_qsetstatus(ctx, flags)) {
INTERNAL_ERROR_INT("context_setstatus_dict");
}
return 0;
}
static int
context_setclamp(PyObject *self, PyObject *value, void *closure)
{
mpd_context_t *ctx;
mpd_ssize_t x;
x = PyLong_AsSsize_t(value);
if (x == -1 && PyErr_Occurred()) {
return -1;
}
BOUNDS_CHECK(x, INT_MIN, INT_MAX);
ctx = CTX(self);
if (!mpd_qsetclamp(ctx, (int)x)) {
return value_error_int("valid values for clamp are 0 or 1");
}
return 0;
}
#ifdef EXTRA_FUNCTIONALITY
static int
context_setallcr(PyObject *self, PyObject *value, void *closure)
{
mpd_context_t *ctx;
mpd_ssize_t x;
x = PyLong_AsSsize_t(value);
if (x == -1 && PyErr_Occurred()) {
return -1;
}
BOUNDS_CHECK(x, INT_MIN, INT_MAX);
ctx = CTX(self);
if (!mpd_qsetcr(ctx, (int)x)) {
return value_error_int("valid values for _allcr are 0 or 1");
}
return 0;
}
#endif
static PyObject *
context_getattr(PyObject *self, PyObject *name)
{
PyObject *retval;
if (PyUnicode_Check(name)) {
if (PyUnicode_CompareWithASCIIString(name, "traps") == 0) {
retval = ((PyDecContextObject *)self)->traps;
Py_INCREF(retval);
return retval;
}
if (PyUnicode_CompareWithASCIIString(name, "flags") == 0) {
retval = ((PyDecContextObject *)self)->flags;
Py_INCREF(retval);
return retval;
}
}
return PyObject_GenericGetAttr(self, name);
}
static int
context_setattr(PyObject *self, PyObject *name, PyObject *value)
{
if (value == NULL) {
PyErr_SetString(PyExc_AttributeError,
"context attributes cannot be deleted");
return -1;
}
if (PyUnicode_Check(name)) {
if (PyUnicode_CompareWithASCIIString(name, "traps") == 0) {
return context_settraps_dict(self, value);
}
if (PyUnicode_CompareWithASCIIString(name, "flags") == 0) {
return context_setstatus_dict(self, value);
}
}
return PyObject_GenericSetAttr(self, name, value);
}
static PyObject *
context_clear_traps(PyObject *self, PyObject *dummy)
{
CTX(self)->traps = 0;
Py_RETURN_NONE;
}
static PyObject *
context_clear_flags(PyObject *self, PyObject *dummy)
{
CTX(self)->status = 0;
Py_RETURN_NONE;
}
#define DEC_DFLT_EMAX 999999
#define DEC_DFLT_EMIN -999999
static mpd_context_t dflt_ctx = {
28, DEC_DFLT_EMAX, DEC_DFLT_EMIN,
MPD_IEEE_Invalid_operation|MPD_Division_by_zero|MPD_Overflow,
0, 0, MPD_ROUND_HALF_EVEN, 0, 1
};
static PyObject *
context_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
PyDecContextObject *self = NULL;
mpd_context_t *ctx;
if (type == &PyDecContext_Type) {
self = PyObject_New(PyDecContextObject, &PyDecContext_Type);
}
else {
self = (PyDecContextObject *)type->tp_alloc(type, 0);
}
if (self == NULL) {
return NULL;
}
self->traps = PyObject_CallObject((PyObject *)PyDecSignalDict_Type, NULL);
if (self->traps == NULL) {
self->flags = NULL;
Py_DECREF(self);
return NULL;
}
self->flags = PyObject_CallObject((PyObject *)PyDecSignalDict_Type, NULL);
if (self->flags == NULL) {
Py_DECREF(self);
return NULL;
}
ctx = CTX(self);
if (default_context_template) {
*ctx = *CTX(default_context_template);
}
else {
*ctx = dflt_ctx;
}
SdFlagAddr(self->traps) = &ctx->traps;
SdFlagAddr(self->flags) = &ctx->status;
CtxCaps(self) = 1;
#ifndef WITHOUT_THREADS
self->tstate = NULL;
#endif
return (PyObject *)self;
}
static void
context_dealloc(PyDecContextObject *self)
{
#ifndef WITHOUT_THREADS
if (self == cached_context) {
cached_context = NULL;
}
#endif
Py_XDECREF(self->traps);
Py_XDECREF(self->flags);
Py_TYPE(self)->tp_free(self);
}
static int
context_init(PyObject *self, PyObject *args, PyObject *kwds)
{
static char *kwlist[] = {
"prec", "rounding", "Emin", "Emax", "capitals", "clamp",
"flags", "traps", NULL
};
PyObject *prec = Py_None;
PyObject *rounding = Py_None;
PyObject *emin = Py_None;
PyObject *emax = Py_None;
PyObject *capitals = Py_None;
PyObject *clamp = Py_None;
PyObject *status = Py_None;
PyObject *traps = Py_None;
int ret;
assert(PyTuple_Check(args));
if (!PyArg_ParseTupleAndKeywords(
args, kwds,
"|OOOOOOOO", kwlist,
&prec, &rounding, &emin, &emax, &capitals, &clamp, &status, &traps
)) {
return -1;
}
if (prec != Py_None && context_setprec(self, prec, NULL) < 0) {
return -1;
}
if (rounding != Py_None && context_setround(self, rounding, NULL) < 0) {
return -1;
}
if (emin != Py_None && context_setemin(self, emin, NULL) < 0) {
return -1;
}
if (emax != Py_None && context_setemax(self, emax, NULL) < 0) {
return -1;
}
if (capitals != Py_None && context_setcapitals(self, capitals, NULL) < 0) {
return -1;
}
if (clamp != Py_None && context_setclamp(self, clamp, NULL) < 0) {
return -1;
}
if (traps != Py_None) {
if (PyList_Check(traps)) {
ret = context_settraps_list(self, traps);
}
#ifdef EXTRA_FUNCTIONALITY
else if (PyLong_Check(traps)) {
ret = context_settraps(self, traps, NULL);
}
#endif
else {
ret = context_settraps_dict(self, traps);
}
if (ret < 0) {
return ret;
}
}
if (status != Py_None) {
if (PyList_Check(status)) {
ret = context_setstatus_list(self, status);
}
#ifdef EXTRA_FUNCTIONALITY
else if (PyLong_Check(status)) {
ret = context_setstatus(self, status, NULL);
}
#endif
else {
ret = context_setstatus_dict(self, status);
}
if (ret < 0) {
return ret;
}
}
return 0;
}
static PyObject *
context_repr(PyDecContextObject *self)
{
mpd_context_t *ctx;
char flags[MPD_MAX_SIGNAL_LIST];
char traps[MPD_MAX_SIGNAL_LIST];
int n, mem;
assert(PyDecContext_Check(self));
ctx = CTX(self);
mem = MPD_MAX_SIGNAL_LIST;
n = mpd_lsnprint_signals(flags, mem, ctx->status, dec_signal_string);
if (n < 0 || n >= mem) {
INTERNAL_ERROR_PTR("context_repr");
}
n = mpd_lsnprint_signals(traps, mem, ctx->traps, dec_signal_string);
if (n < 0 || n >= mem) {
INTERNAL_ERROR_PTR("context_repr");
}
return PyUnicode_FromFormat(
"Context(prec=%zd, rounding=%s, Emin=%zd, Emax=%zd, "
"capitals=%d, clamp=%d, flags=%s, traps=%s)",
ctx->prec, mpd_round_string[ctx->round], ctx->emin, ctx->emax,
self->capitals, ctx->clamp, flags, traps);
}
static void
init_basic_context(PyObject *v)
{
mpd_context_t ctx = dflt_ctx;
ctx.prec = 9;
ctx.traps |= (MPD_Underflow|MPD_Clamped);
ctx.round = MPD_ROUND_HALF_UP;
*CTX(v) = ctx;
CtxCaps(v) = 1;
}
static void
init_extended_context(PyObject *v)
{
mpd_context_t ctx = dflt_ctx;
ctx.prec = 9;
ctx.traps = 0;
*CTX(v) = ctx;
CtxCaps(v) = 1;
}
#ifdef EXTRA_FUNCTIONALITY
/* Factory function for creating IEEE interchange format contexts */
static PyObject *
ieee_context(PyObject *dummy, PyObject *v)
{
PyObject *context;
mpd_ssize_t bits;
mpd_context_t ctx;
bits = PyLong_AsSsize_t(v);
if (bits == -1 && PyErr_Occurred()) {
return NULL;
}
if (bits <= 0 || bits > INT_MAX) {
goto error;
}
if (mpd_ieee_context(&ctx, (int)bits) < 0) {
goto error;
}
context = PyObject_CallObject((PyObject *)&PyDecContext_Type, NULL);
if (context == NULL) {
return NULL;
}
*CTX(context) = ctx;
return context;
error:
PyErr_Format(PyExc_ValueError,
"argument must be a multiple of 32, with a maximum of %d",
MPD_IEEE_CONTEXT_MAX_BITS);
return NULL;
}
#endif
static PyObject *
context_copy(PyObject *self, PyObject *args)
{
PyObject *copy;
copy = PyObject_CallObject((PyObject *)&PyDecContext_Type, NULL);
if (copy == NULL) {
return NULL;
}
*CTX(copy) = *CTX(self);
CTX(copy)->newtrap = 0;
CtxCaps(copy) = CtxCaps(self);
return copy;
}
static PyObject *
context_reduce(PyObject *self, PyObject *args)
{
PyObject *flags;
PyObject *traps;
PyObject *ret;
mpd_context_t *ctx;
ctx = CTX(self);
flags = signals_as_list(ctx->status);
if (flags == NULL) {
return NULL;
}
traps = signals_as_list(ctx->traps);
if (traps == NULL) {
Py_DECREF(flags);
return NULL;
}
ret = Py_BuildValue(
"O(nsnniiOO)",
Py_TYPE(self),
ctx->prec, mpd_round_string[ctx->round], ctx->emin, ctx->emax,
CtxCaps(self), ctx->clamp, flags, traps
);
Py_DECREF(flags);
Py_DECREF(traps);
return ret;
}
static PyGetSetDef context_getsets [] =
{
{ "prec", (getter)context_getprec, (setter)context_setprec, NULL, NULL},
{ "Emax", (getter)context_getemax, (setter)context_setemax, NULL, NULL},
{ "Emin", (getter)context_getemin, (setter)context_setemin, NULL, NULL},
{ "rounding", (getter)context_getround, (setter)context_setround, NULL, NULL},
{ "capitals", (getter)context_getcapitals, (setter)context_setcapitals, NULL, NULL},
{ "clamp", (getter)context_getclamp, (setter)context_setclamp, NULL, NULL},
#ifdef EXTRA_FUNCTIONALITY
{ "_allcr", (getter)context_getallcr, (setter)context_setallcr, NULL, NULL},
{ "_traps", (getter)context_gettraps, (setter)context_settraps, NULL, NULL},
{ "_flags", (getter)context_getstatus, (setter)context_setstatus, NULL, NULL},
#endif
{NULL}
};
#define CONTEXT_CHECK(obj) \
if (!PyDecContext_Check(obj)) { \
PyErr_SetString(PyExc_TypeError, \
"argument must be a context"); \
return NULL; \
}
#define CONTEXT_CHECK_VA(obj) \
if (obj == Py_None) { \
CURRENT_CONTEXT(obj); \
} \
else if (!PyDecContext_Check(obj)) { \
PyErr_SetString(PyExc_TypeError, \
"optional argument must be a context"); \
return NULL; \
}
/******************************************************************************/
/* Global, thread local and temporary contexts */
/******************************************************************************/
#ifdef WITHOUT_THREADS
/* Return borrowed reference to the current context. When compiled
* without threads, this is always the module context. */
static int module_context_set = 0;
static PyObject *
current_context(void)
{
/* In decimal.py, the module context is automatically initialized
* from the DefaultContext when it is first accessed. This
* complicates the code and has a speed penalty of 1-2%. */
if (module_context_set) {
return module_context;
}
*CTX(module_context) = *CTX(default_context_template);
CTX(module_context)->status = 0;
CTX(module_context)->newtrap = 0;
CtxCaps(module_context) = CtxCaps(default_context_template);
module_context_set = 1;
return module_context;
}
/* ctxobj := borrowed reference to the current context */
#define CURRENT_CONTEXT(ctxobj) \
ctxobj = current_context()
/* ctx := pointer to the mpd_context_t struct of the current context */
#define CURRENT_CONTEXT_ADDR(ctx) \
ctx = CTX(current_context())
/* Return a new reference to the current context */
static PyObject *
PyDec_GetCurrentContext(PyObject *self, PyObject *args)
{
PyObject *context;
CURRENT_CONTEXT(context);
Py_INCREF(context);
return context;
}
/* Set the module context to a new context, decrement old reference */
static PyObject *
PyDec_SetCurrentContext(PyObject *self, PyObject *v)
{
CONTEXT_CHECK(v);
/* If the new context is one of the templates, make a copy.
* This is the current behavior of decimal.py. */
if (v == default_context_template ||
v == basic_context_template ||
v == extended_context_template) {
v = context_copy(v, NULL);
if (v == NULL) {
return NULL;
}
CTX(v)->status = 0;
}
else {
Py_INCREF(v);
}
Py_XDECREF(module_context);
module_context = v;
module_context_set = 1;
Py_RETURN_NONE;
}
#else
/*
* Thread local storage currently has a speed penalty of about 4%.
* All functions that map Python's arithmetic operators to mpdecimal
* functions have to look up the current context for each and every
* operation.
*/
/* Get the context from the thread state dictionary. */
static PyObject *
current_context_from_dict(void)
{
PyObject *dict;
PyObject *tl_context;
PyThreadState *tstate;
dict = PyThreadState_GetDict();
if (dict == NULL) {
PyErr_SetString(PyExc_RuntimeError,
"cannot get thread state");
return NULL;
}
tl_context = PyDict_GetItemWithError(dict, tls_context_key);
if (tl_context != NULL) {
/* We already have a thread local context. */
CONTEXT_CHECK(tl_context);
}
else {
if (PyErr_Occurred()) {
return NULL;
}
/* Set up a new thread local context. */
tl_context = context_copy(default_context_template, NULL);
if (tl_context == NULL) {
return NULL;
}
CTX(tl_context)->status = 0;
if (PyDict_SetItem(dict, tls_context_key, tl_context) < 0) {
Py_DECREF(tl_context);
return NULL;
}
Py_DECREF(tl_context);
}
/* Cache the context of the current thread, assuming that it
* will be accessed several times before a thread switch. */
tstate = PyThreadState_GET();
if (tstate) {
cached_context = (PyDecContextObject *)tl_context;
cached_context->tstate = tstate;
}
/* Borrowed reference with refcount==1 */
return tl_context;
}
/* Return borrowed reference to thread local context. */
static PyObject *
current_context(void)
{
PyThreadState *tstate;
tstate = PyThreadState_GET();
if (cached_context && cached_context->tstate == tstate) {
return (PyObject *)cached_context;
}
return current_context_from_dict();
}
/* ctxobj := borrowed reference to the current context */
#define CURRENT_CONTEXT(ctxobj) \
ctxobj = current_context(); \
if (ctxobj == NULL) { \
return NULL; \
}
/* ctx := pointer to the mpd_context_t struct of the current context */
#define CURRENT_CONTEXT_ADDR(ctx) { \
PyObject *_c_t_x_o_b_j = current_context(); \
if (_c_t_x_o_b_j == NULL) { \
return NULL; \
} \
ctx = CTX(_c_t_x_o_b_j); \
}
/* Return a new reference to the current context */
static PyObject *
PyDec_GetCurrentContext(PyObject *self, PyObject *args)
{
PyObject *context;
context = current_context();
if (context == NULL) {
return NULL;
}
Py_INCREF(context);
return context;
}
/* Set the thread local context to a new context, decrement old reference */
static PyObject *
PyDec_SetCurrentContext(PyObject *self, PyObject *v)
{
PyObject *dict;
CONTEXT_CHECK(v);
dict = PyThreadState_GetDict();
if (dict == NULL) {
PyErr_SetString(PyExc_RuntimeError,
"cannot get thread state");
return NULL;
}
/* If the new context is one of the templates, make a copy.
* This is the current behavior of decimal.py. */
if (v == default_context_template ||
v == basic_context_template ||
v == extended_context_template) {
v = context_copy(v, NULL);
if (v == NULL) {
return NULL;
}
CTX(v)->status = 0;
}
else {
Py_INCREF(v);
}
cached_context = NULL;
if (PyDict_SetItem(dict, tls_context_key, v) < 0) {
Py_DECREF(v);
return NULL;
}
Py_DECREF(v);
Py_RETURN_NONE;
}
#endif
/* Context manager object for the 'with' statement. The manager
* owns one reference to the global (outer) context and one
* to the local (inner) context. */
static PyObject *
ctxmanager_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
static char *kwlist[] = {"ctx", NULL};
PyDecContextManagerObject *self;
PyObject *local = Py_None;
PyObject *global;
CURRENT_CONTEXT(global);
if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O", kwlist, &local)) {
return NULL;
}
if (local == Py_None) {
local = global;
}
else if (!PyDecContext_Check(local)) {
PyErr_SetString(PyExc_TypeError,
"optional argument must be a context");
return NULL;
}
self = PyObject_New(PyDecContextManagerObject,
&PyDecContextManager_Type);
if (self == NULL) {
return NULL;
}
self->local = context_copy(local, NULL);
if (self->local == NULL) {
self->global = NULL;
Py_DECREF(self);
return NULL;
}
self->global = global;
Py_INCREF(self->global);
return (PyObject *)self;
}
static void
ctxmanager_dealloc(PyDecContextManagerObject *self)
{
Py_XDECREF(self->local);
Py_XDECREF(self->global);
PyObject_Del(self);
}
static PyObject *
ctxmanager_set_local(PyDecContextManagerObject *self, PyObject *args)
{
PyObject *ret;
ret = PyDec_SetCurrentContext(NULL, self->local);
if (ret == NULL) {
return NULL;
}
Py_DECREF(ret);
Py_INCREF(self->local);
return self->local;
}
static PyObject *
ctxmanager_restore_global(PyDecContextManagerObject *self,
PyObject *args)
{
PyObject *ret;
ret = PyDec_SetCurrentContext(NULL, self->global);
if (ret == NULL) {
return NULL;
}
Py_DECREF(ret);
Py_RETURN_NONE;
}
static PyMethodDef ctxmanager_methods[] = {
{"__enter__", (PyCFunction)ctxmanager_set_local, METH_NOARGS, NULL},
{"__exit__", (PyCFunction)ctxmanager_restore_global, METH_VARARGS, NULL},
{NULL, NULL}
};
static PyTypeObject PyDecContextManager_Type =
{
PyVarObject_HEAD_INIT(NULL, 0)
"decimal.ContextManager", /* tp_name */
sizeof(PyDecContextManagerObject), /* tp_basicsize */
0, /* tp_itemsize */
(destructor) ctxmanager_dealloc, /* tp_dealloc */
0, /* tp_print */
(getattrfunc) 0, /* tp_getattr */
(setattrfunc) 0, /* tp_setattr */
0, /* tp_reserved */
(reprfunc) 0, /* tp_repr */
0, /* tp_as_number */
0, /* tp_as_sequence */
0, /* tp_as_mapping */
0, /* tp_hash */
0, /* tp_call */
0, /* tp_str */
(getattrofunc) PyObject_GenericGetAttr, /* tp_getattro */
(setattrofunc) 0, /* tp_setattro */
(PyBufferProcs *) 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 */
ctxmanager_methods, /* tp_methods */
};
/******************************************************************************/
/* New Decimal Object */
/******************************************************************************/
static PyObject *
PyDecType_New(PyTypeObject *type)
{
PyDecObject *dec;
if (type == &PyDec_Type) {
dec = PyObject_New(PyDecObject, &PyDec_Type);
}
else {
dec = (PyDecObject *)type->tp_alloc(type, 0);
}
if (dec == NULL) {
return NULL;
}
dec->hash = -1;
MPD(dec)->flags = MPD_STATIC|MPD_STATIC_DATA;
MPD(dec)->exp = 0;
MPD(dec)->digits = 0;
MPD(dec)->len = 0;
MPD(dec)->alloc = _Py_DEC_MINALLOC;
MPD(dec)->data = dec->data;
return (PyObject *)dec;
}
#define dec_alloc() PyDecType_New(&PyDec_Type)
static void
dec_dealloc(PyObject *dec)
{
mpd_del(MPD(dec));
Py_TYPE(dec)->tp_free(dec);
}
/******************************************************************************/
/* Conversions to Decimal */
/******************************************************************************/
Py_LOCAL_INLINE(int)
is_space(enum PyUnicode_Kind kind, void *data, Py_ssize_t pos)
{
Py_UCS4 ch = PyUnicode_READ(kind, data, pos);
return Py_UNICODE_ISSPACE(ch);
}
/* Return the ASCII representation of a numeric Unicode string. The numeric
string may contain ascii characters in the range [1, 127], any Unicode
space and any unicode digit. If strip_ws is true, leading and trailing
whitespace is stripped. If ignore_underscores is true, underscores are
ignored.
Return NULL if malloc fails and an empty string if invalid characters
are found. */
static char *
numeric_as_ascii(const PyObject *u, int strip_ws, int ignore_underscores)
{
enum PyUnicode_Kind kind;
void *data;
Py_UCS4 ch;
char *res, *cp;
Py_ssize_t j, len;
int d;
if (PyUnicode_READY(u) == -1) {
return NULL;
}
kind = PyUnicode_KIND(u);
data = PyUnicode_DATA(u);
len = PyUnicode_GET_LENGTH(u);
cp = res = PyMem_Malloc(len+1);
if (res == NULL) {
PyErr_NoMemory();
return NULL;
}
j = 0;
if (strip_ws) {
while (len > 0 && is_space(kind, data, len-1)) {
len--;
}
while (j < len && is_space(kind, data, j)) {
j++;
}
}
for (; j < len; j++) {
ch = PyUnicode_READ(kind, data, j);
if (ignore_underscores && ch == '_') {
continue;
}
if (0 < ch && ch <= 127) {
*cp++ = ch;
continue;
}
if (Py_UNICODE_ISSPACE(ch)) {
*cp++ = ' ';
continue;
}
d = Py_UNICODE_TODECIMAL(ch);
if (d < 0) {
/* empty string triggers ConversionSyntax */
*res = '\0';
return res;
}
*cp++ = '0' + d;
}
*cp = '\0';
return res;
}
/* Return a new PyDecObject or a subtype from a C string. Use the context
during conversion. */
static PyObject *
PyDecType_FromCString(PyTypeObject *type, const char *s,
PyObject *context)
{
PyObject *dec;
uint32_t status = 0;
dec = PyDecType_New(type);
if (dec == NULL) {
return NULL;
}
mpd_qset_string(MPD(dec), s, CTX(context), &status);
if (dec_addstatus(context, status)) {
Py_DECREF(dec);
return NULL;
}
return dec;
}
/* Return a new PyDecObject or a subtype from a C string. Attempt exact
conversion. If the operand cannot be converted exactly, set
InvalidOperation. */
static PyObject *
PyDecType_FromCStringExact(PyTypeObject *type, const char *s,
PyObject *context)
{
PyObject *dec;
uint32_t status = 0;
mpd_context_t maxctx;
dec = PyDecType_New(type);
if (dec == NULL) {
return NULL;
}
mpd_maxcontext(&maxctx);
mpd_qset_string(MPD(dec), s, &maxctx, &status);
if (status & (MPD_Inexact|MPD_Rounded|MPD_Clamped)) {
/* we want exact results */
mpd_seterror(MPD(dec), MPD_Invalid_operation, &status);
}
status &= MPD_Errors;
if (dec_addstatus(context, status)) {
Py_DECREF(dec);
return NULL;
}
return dec;
}
/* Return a new PyDecObject or a subtype from a PyUnicodeObject. */
static PyObject *
PyDecType_FromUnicode(PyTypeObject *type, const PyObject *u,
PyObject *context)
{
PyObject *dec;
char *s;
s = numeric_as_ascii(u, 0, 0);
if (s == NULL) {
return NULL;
}
dec = PyDecType_FromCString(type, s, context);
PyMem_Free(s);
return dec;
}
/* Return a new PyDecObject or a subtype from a PyUnicodeObject. Attempt exact
* conversion. If the conversion is not exact, fail with InvalidOperation.
* Allow leading and trailing whitespace in the input operand. */
static PyObject *
PyDecType_FromUnicodeExactWS(PyTypeObject *type, const PyObject *u,
PyObject *context)
{
PyObject *dec;
char *s;
s = numeric_as_ascii(u, 1, 1);
if (s == NULL) {
return NULL;
}
dec = PyDecType_FromCStringExact(type, s, context);
PyMem_Free(s);
return dec;
}
/* Set PyDecObject from triple without any error checking. */
Py_LOCAL_INLINE(void)
_dec_settriple(PyObject *dec, uint8_t sign, uint32_t v, mpd_ssize_t exp)
{
MPD(dec)->data[0] = v;
MPD(dec)->len = 1;
mpd_set_flags(MPD(dec), sign);
MPD(dec)->exp = exp;
mpd_setdigits(MPD(dec));
}
/* Return a new PyDecObject from an mpd_ssize_t. */
static PyObject *
PyDecType_FromSsize(PyTypeObject *type, mpd_ssize_t v, PyObject *context)
{
PyObject *dec;
uint32_t status = 0;
dec = PyDecType_New(type);
if (dec == NULL) {
return NULL;
}
mpd_qset_ssize(MPD(dec), v, CTX(context), &status);
if (dec_addstatus(context, status)) {
Py_DECREF(dec);
return NULL;
}
return dec;
}
/* Return a new PyDecObject from an mpd_ssize_t. Conversion is exact. */
static PyObject *
PyDecType_FromSsizeExact(PyTypeObject *type, mpd_ssize_t v, PyObject *context)
{
PyObject *dec;
uint32_t status = 0;
mpd_context_t maxctx;
dec = PyDecType_New(type);
if (dec == NULL) {
return NULL;
}
mpd_maxcontext(&maxctx);
mpd_qset_ssize(MPD(dec), v, &maxctx, &status);
if (dec_addstatus(context, status)) {
Py_DECREF(dec);
return NULL;
}
return dec;
}
/* Convert from a PyLongObject. The context is not modified; flags set
during conversion are accumulated in the status parameter. */
static PyObject *
dec_from_long(PyTypeObject *type, const PyObject *v,
const mpd_context_t *ctx, uint32_t *status)
{
PyObject *dec;
PyLongObject *l = (PyLongObject *)v;
Py_ssize_t ob_size;
size_t len;
uint8_t sign;
dec = PyDecType_New(type);
if (dec == NULL) {
return NULL;
}
ob_size = Py_SIZE(l);
if (ob_size == 0) {
_dec_settriple(dec, MPD_POS, 0, 0);
return dec;
}
if (ob_size < 0) {
len = -ob_size;
sign = MPD_NEG;
}
else {
len = ob_size;
sign = MPD_POS;
}
if (len == 1) {
_dec_settriple(dec, sign, *l->ob_digit, 0);
mpd_qfinalize(MPD(dec), ctx, status);
return dec;
}
#if PYLONG_BITS_IN_DIGIT == 30
mpd_qimport_u32(MPD(dec), l->ob_digit, len, sign, PyLong_BASE,
ctx, status);
#elif PYLONG_BITS_IN_DIGIT == 15
mpd_qimport_u16(MPD(dec), l->ob_digit, len, sign, PyLong_BASE,
ctx, status);
#else
#error "PYLONG_BITS_IN_DIGIT should be 15 or 30"
#endif
return dec;
}
/* Return a new PyDecObject from a PyLongObject. Use the context for
conversion. */
static PyObject *
PyDecType_FromLong(PyTypeObject *type, const PyObject *v, PyObject *context)
{
PyObject *dec;
uint32_t status = 0;
if (!PyLong_Check(v)) {
PyErr_SetString(PyExc_TypeError, "argument must be an integer");
return NULL;
}
dec = dec_from_long(type, v, CTX(context), &status);
if (dec == NULL) {
return NULL;
}
if (dec_addstatus(context, status)) {
Py_DECREF(dec);
return NULL;
}
return dec;
}
/* Return a new PyDecObject from a PyLongObject. Use a maximum context
for conversion. If the conversion is not exact, set InvalidOperation. */
static PyObject *
PyDecType_FromLongExact(PyTypeObject *type, const PyObject *v,
PyObject *context)
{
PyObject *dec;
uint32_t status = 0;
mpd_context_t maxctx;
if (!PyLong_Check(v)) {
PyErr_SetString(PyExc_TypeError, "argument must be an integer");
return NULL;
}
mpd_maxcontext(&maxctx);
dec = dec_from_long(type, v, &maxctx, &status);
if (dec == NULL) {
return NULL;
}
if (status & (MPD_Inexact|MPD_Rounded|MPD_Clamped)) {
/* we want exact results */
mpd_seterror(MPD(dec), MPD_Invalid_operation, &status);
}
status &= MPD_Errors;
if (dec_addstatus(context, status)) {
Py_DECREF(dec);
return NULL;
}
return dec;
}
/* External C-API functions */
static binaryfunc _py_long_multiply;
static binaryfunc _py_long_floor_divide;
static ternaryfunc _py_long_power;
static unaryfunc _py_float_abs;
static PyCFunction _py_long_bit_length;
static PyCFunction _py_float_as_integer_ratio;
/* Return a PyDecObject or a subtype from a PyFloatObject.
Conversion is exact. */
static PyObject *
PyDecType_FromFloatExact(PyTypeObject *type, PyObject *v,
PyObject *context)
{
PyObject *dec, *tmp;
PyObject *n, *d, *n_d;
mpd_ssize_t k;
double x;
int sign;
mpd_t *d1, *d2;
uint32_t status = 0;
mpd_context_t maxctx;
assert(PyType_IsSubtype(type, &PyDec_Type));
if (PyLong_Check(v)) {
return PyDecType_FromLongExact(type, v, context);
}
if (!PyFloat_Check(v)) {
PyErr_SetString(PyExc_TypeError,
"argument must be int of float");
return NULL;
}
x = PyFloat_AsDouble(v);
if (x == -1.0 && PyErr_Occurred()) {
return NULL;
}
sign = (copysign(1.0, x) == 1.0) ? 0 : 1;
if (Py_IS_NAN(x) || Py_IS_INFINITY(x)) {
dec = PyDecType_New(type);
if (dec == NULL) {
return NULL;
}
if (Py_IS_NAN(x)) {
/* decimal.py calls repr(float(+-nan)),
* which always gives a positive result. */
mpd_setspecial(MPD(dec), MPD_POS, MPD_NAN);
}
else {
mpd_setspecial(MPD(dec), sign, MPD_INF);
}
return dec;
}
/* absolute value of the float */
tmp = _py_float_abs(v);
if (tmp == NULL) {
return NULL;
}
/* float as integer ratio: numerator/denominator */
n_d = _py_float_as_integer_ratio(tmp, NULL);
Py_DECREF(tmp);
if (n_d == NULL) {
return NULL;
}
n = PyTuple_GET_ITEM(n_d, 0);
d = PyTuple_GET_ITEM(n_d, 1);
tmp = _py_long_bit_length(d, NULL);
if (tmp == NULL) {
Py_DECREF(n_d);
return NULL;
}
k = PyLong_AsSsize_t(tmp);
Py_DECREF(tmp);
if (k == -1 && PyErr_Occurred()) {
Py_DECREF(n_d);
return NULL;
}
k--;
dec = PyDecType_FromLongExact(type, n, context);
Py_DECREF(n_d);
if (dec == NULL) {
return NULL;
}
d1 = mpd_qnew();
if (d1 == NULL) {
Py_DECREF(dec);
PyErr_NoMemory();
return NULL;
}
d2 = mpd_qnew();
if (d2 == NULL) {
mpd_del(d1);
Py_DECREF(dec);
PyErr_NoMemory();
return NULL;
}
mpd_maxcontext(&maxctx);
mpd_qset_uint(d1, 5, &maxctx, &status);
mpd_qset_ssize(d2, k, &maxctx, &status);
mpd_qpow(d1, d1, d2, &maxctx, &status);
if (dec_addstatus(context, status)) {
mpd_del(d1);
mpd_del(d2);
Py_DECREF(dec);
return NULL;
}
/* result = n * 5**k */
mpd_qmul(MPD(dec), MPD(dec), d1, &maxctx, &status);
mpd_del(d1);
mpd_del(d2);
if (dec_addstatus(context, status)) {
Py_DECREF(dec);
return NULL;
}
/* result = +- n * 5**k * 10**-k */
mpd_set_sign(MPD(dec), sign);
MPD(dec)->exp = -k;
return dec;
}
static PyObject *
PyDecType_FromFloat(PyTypeObject *type, PyObject *v,
PyObject *context)
{
PyObject *dec;
uint32_t status = 0;
dec = PyDecType_FromFloatExact(type, v, context);
if (dec == NULL) {
return NULL;
}
mpd_qfinalize(MPD(dec), CTX(context), &status);
if (dec_addstatus(context, status)) {
Py_DECREF(dec);
return NULL;
}
return dec;
}
/* Return a new PyDecObject or a subtype from a Decimal. */
static PyObject *
PyDecType_FromDecimalExact(PyTypeObject *type, PyObject *v, PyObject *context)
{
PyObject *dec;
uint32_t status = 0;
if (type == &PyDec_Type && PyDec_CheckExact(v)) {
Py_INCREF(v);
return v;
}
dec = PyDecType_New(type);
if (dec == NULL) {
return NULL;
}
mpd_qcopy(MPD(dec), MPD(v), &status);
if (dec_addstatus(context, status)) {
Py_DECREF(dec);
return NULL;
}
return dec;
}
static PyObject *
sequence_as_tuple(PyObject *v, PyObject *ex, const char *mesg)
{
if (PyTuple_Check(v)) {
Py_INCREF(v);
return v;
}
if (PyList_Check(v)) {
return PyList_AsTuple(v);
}
PyErr_SetString(ex, mesg);
return NULL;
}
/* Return a new C string representation of a DecimalTuple. */
static char *
dectuple_as_str(PyObject *dectuple)
{
PyObject *digits = NULL, *tmp;
char *decstring = NULL;
char sign_special[6];
char *cp;
long sign, l;
mpd_ssize_t exp = 0;
Py_ssize_t i, mem, tsize;
int is_infinite = 0;
int n;
assert(PyTuple_Check(dectuple));
if (PyTuple_Size(dectuple) != 3) {
PyErr_SetString(PyExc_ValueError,
"argument must be a sequence of length 3");
goto error;
}
/* sign */
tmp = PyTuple_GET_ITEM(dectuple, 0);
if (!PyLong_Check(tmp)) {
PyErr_SetString(PyExc_ValueError,
"sign must be an integer with the value 0 or 1");
goto error;
}
sign = PyLong_AsLong(tmp);
if (sign == -1 && PyErr_Occurred()) {
goto error;
}
if (sign != 0 && sign != 1) {
PyErr_SetString(PyExc_ValueError,
"sign must be an integer with the value 0 or 1");
goto error;
}
sign_special[0] = sign ? '-' : '+';
sign_special[1] = '\0';
/* exponent or encoding for a special number */
tmp = PyTuple_GET_ITEM(dectuple, 2);
if (PyUnicode_Check(tmp)) {
/* special */
if (PyUnicode_CompareWithASCIIString(tmp, "F") == 0) {
strcat(sign_special, "Inf");
is_infinite = 1;
}
else if (PyUnicode_CompareWithASCIIString(tmp, "n") == 0) {
strcat(sign_special, "NaN");
}
else if (PyUnicode_CompareWithASCIIString(tmp, "N") == 0) {
strcat(sign_special, "sNaN");
}
else {
PyErr_SetString(PyExc_ValueError,
"string argument in the third position "
"must be 'F', 'n' or 'N'");
goto error;
}
}
else {
/* exponent */
if (!PyLong_Check(tmp)) {
PyErr_SetString(PyExc_ValueError,
"exponent must be an integer");
goto error;
}
exp = PyLong_AsSsize_t(tmp);
if (exp == -1 && PyErr_Occurred()) {
goto error;
}
}
/* coefficient */
digits = sequence_as_tuple(PyTuple_GET_ITEM(dectuple, 1), PyExc_ValueError,
"coefficient must be a tuple of digits");
if (digits == NULL) {
goto error;
}
tsize = PyTuple_Size(digits);
/* [sign][coeffdigits+1][E][-][expdigits+1]['\0'] */
mem = 1 + tsize + 3 + MPD_EXPDIGITS + 2;
cp = decstring = PyMem_Malloc(mem);
if (decstring == NULL) {
PyErr_NoMemory();
goto error;
}
n = snprintf(cp, mem, "%s", sign_special);
if (n < 0 || n >= mem) {
PyErr_SetString(PyExc_RuntimeError,
"internal error in dec_sequence_as_str");
goto error;
}
cp += n;
if (tsize == 0 && sign_special[1] == '\0') {
/* empty tuple: zero coefficient, except for special numbers */
*cp++ = '0';
}
for (i = 0; i < tsize; i++) {
tmp = PyTuple_GET_ITEM(digits, i);
if (!PyLong_Check(tmp)) {
PyErr_SetString(PyExc_ValueError,
"coefficient must be a tuple of digits");
goto error;
}
l = PyLong_AsLong(tmp);
if (l == -1 && PyErr_Occurred()) {
goto error;
}
if (l < 0 || l > 9) {
PyErr_SetString(PyExc_ValueError,
"coefficient must be a tuple of digits");
goto error;
}
if (is_infinite) {
/* accept but ignore any well-formed coefficient for compatibility
with decimal.py */
continue;
}
*cp++ = (char)l + '0';
}
*cp = '\0';
if (sign_special[1] == '\0') {
/* not a special number */
*cp++ = 'E';
n = snprintf(cp, MPD_EXPDIGITS+2, "%" PRI_mpd_ssize_t, exp);
if (n < 0 || n >= MPD_EXPDIGITS+2) {
PyErr_SetString(PyExc_RuntimeError,
"internal error in dec_sequence_as_str");
goto error;
}
}
Py_XDECREF(digits);
return decstring;
error:
Py_XDECREF(digits);
if (decstring) PyMem_Free(decstring);
return NULL;
}
/* Currently accepts tuples and lists. */
static PyObject *
PyDecType_FromSequence(PyTypeObject *type, PyObject *v,
PyObject *context)
{
PyObject *dectuple;
PyObject *dec;
char *s;
dectuple = sequence_as_tuple(v, PyExc_TypeError,
"argument must be a tuple or list");
if (dectuple == NULL) {
return NULL;
}
s = dectuple_as_str(dectuple);
Py_DECREF(dectuple);
if (s == NULL) {
return NULL;
}
dec = PyDecType_FromCString(type, s, context);
PyMem_Free(s);
return dec;
}
/* Currently accepts tuples and lists. */
static PyObject *
PyDecType_FromSequenceExact(PyTypeObject *type, PyObject *v,
PyObject *context)
{
PyObject *dectuple;
PyObject *dec;
char *s;
dectuple = sequence_as_tuple(v, PyExc_TypeError,
"argument must be a tuple or list");
if (dectuple == NULL) {
return NULL;
}
s = dectuple_as_str(dectuple);
Py_DECREF(dectuple);
if (s == NULL) {
return NULL;
}
dec = PyDecType_FromCStringExact(type, s, context);
PyMem_Free(s);
return dec;
}
#define PyDec_FromCString(str, context) \
PyDecType_FromCString(&PyDec_Type, str, context)
#define PyDec_FromCStringExact(str, context) \
PyDecType_FromCStringExact(&PyDec_Type, str, context)
#define PyDec_FromUnicode(unicode, context) \
PyDecType_FromUnicode(&PyDec_Type, unicode, context)
#define PyDec_FromUnicodeExact(unicode, context) \
PyDecType_FromUnicodeExact(&PyDec_Type, unicode, context)
#define PyDec_FromUnicodeExactWS(unicode, context) \
PyDecType_FromUnicodeExactWS(&PyDec_Type, unicode, context)
#define PyDec_FromSsize(v, context) \
PyDecType_FromSsize(&PyDec_Type, v, context)
#define PyDec_FromSsizeExact(v, context) \
PyDecType_FromSsizeExact(&PyDec_Type, v, context)
#define PyDec_FromLong(pylong, context) \
PyDecType_FromLong(&PyDec_Type, pylong, context)
#define PyDec_FromLongExact(pylong, context) \
PyDecType_FromLongExact(&PyDec_Type, pylong, context)
#define PyDec_FromFloat(pyfloat, context) \
PyDecType_FromFloat(&PyDec_Type, pyfloat, context)
#define PyDec_FromFloatExact(pyfloat, context) \
PyDecType_FromFloatExact(&PyDec_Type, pyfloat, context)
#define PyDec_FromSequence(sequence, context) \
PyDecType_FromSequence(&PyDec_Type, sequence, context)
#define PyDec_FromSequenceExact(sequence, context) \
PyDecType_FromSequenceExact(&PyDec_Type, sequence, context)
/* class method */
static PyObject *
dec_from_float(PyObject *type, PyObject *pyfloat)
{
PyObject *context;
PyObject *result;
CURRENT_CONTEXT(context);
result = PyDecType_FromFloatExact(&PyDec_Type, pyfloat, context);
if (type != (PyObject *)&PyDec_Type && result != NULL) {
Py_SETREF(result, PyObject_CallFunctionObjArgs(type, result, NULL));
}
return result;
}
/* create_decimal_from_float */
static PyObject *
ctx_from_float(PyObject *context, PyObject *v)
{
return PyDec_FromFloat(v, context);
}
/* Apply the context to the input operand. Return a new PyDecObject. */
static PyObject *
dec_apply(PyObject *v, PyObject *context)
{
PyObject *result;
uint32_t status = 0;
result = dec_alloc();
if (result == NULL) {
return NULL;
}
mpd_qcopy(MPD(result), MPD(v), &status);
if (dec_addstatus(context, status)) {
Py_DECREF(result);
return NULL;
}
mpd_qfinalize(MPD(result), CTX(context), &status);
if (dec_addstatus(context, status)) {
Py_DECREF(result);
return NULL;
}
return result;
}
/* 'v' can have any type accepted by the Decimal constructor. Attempt
an exact conversion. If the result does not meet the restrictions
for an mpd_t, fail with InvalidOperation. */
static PyObject *
PyDecType_FromObjectExact(PyTypeObject *type, PyObject *v, PyObject *context)
{
if (v == NULL) {
return PyDecType_FromSsizeExact(type, 0, context);
}
else if (PyDec_Check(v)) {
return PyDecType_FromDecimalExact(type, v, context);
}
else if (PyUnicode_Check(v)) {
return PyDecType_FromUnicodeExactWS(type, v, context);
}
else if (PyLong_Check(v)) {
return PyDecType_FromLongExact(type, v, context);
}
else if (PyTuple_Check(v) || PyList_Check(v)) {
return PyDecType_FromSequenceExact(type, v, context);
}
else if (PyFloat_Check(v)) {
if (dec_addstatus(context, MPD_Float_operation)) {
return NULL;
}
return PyDecType_FromFloatExact(type, v, context);
}
else {
PyErr_Format(PyExc_TypeError,
"conversion from %s to Decimal is not supported",
v->ob_type->tp_name);
return NULL;
}
}
/* The context is used during conversion. This function is the
equivalent of context.create_decimal(). */
static PyObject *
PyDec_FromObject(PyObject *v, PyObject *context)
{
if (v == NULL) {
return PyDec_FromSsize(0, context);
}
else if (PyDec_Check(v)) {
mpd_context_t *ctx = CTX(context);
if (mpd_isnan(MPD(v)) &&
MPD(v)->digits > ctx->prec - ctx->clamp) {
/* Special case: too many NaN payload digits */
PyObject *result;
if (dec_addstatus(context, MPD_Conversion_syntax)) {
return NULL;
}
result = dec_alloc();
if (result == NULL) {
return NULL;
}
mpd_setspecial(MPD(result), MPD_POS, MPD_NAN);
return result;
}
return dec_apply(v, context);
}
else if (PyUnicode_Check(v)) {
return PyDec_FromUnicode(v, context);
}
else if (PyLong_Check(v)) {
return PyDec_FromLong(v, context);
}
else if (PyTuple_Check(v) || PyList_Check(v)) {
return PyDec_FromSequence(v, context);
}
else if (PyFloat_Check(v)) {
if (dec_addstatus(context, MPD_Float_operation)) {
return NULL;
}
return PyDec_FromFloat(v, context);
}
else {
PyErr_Format(PyExc_TypeError,
"conversion from %s to Decimal is not supported",
v->ob_type->tp_name);
return NULL;
}
}
static PyObject *
dec_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
static char *kwlist[] = {"value", "context", NULL};
PyObject *v = NULL;
PyObject *context = Py_None;
if (!PyArg_ParseTupleAndKeywords(args, kwds, "|OO", kwlist,
&v, &context)) {
return NULL;
}
CONTEXT_CHECK_VA(context);
return PyDecType_FromObjectExact(type, v, context);
}
static PyObject *
ctx_create_decimal(PyObject *context, PyObject *args)
{
PyObject *v = NULL;
if (!PyArg_ParseTuple(args, "|O", &v)) {
return NULL;
}
return PyDec_FromObject(v, context);
}
/******************************************************************************/
/* Implicit conversions to Decimal */
/******************************************************************************/
/* Try to convert PyObject v to a new PyDecObject conv. If the conversion
fails, set conv to NULL (exception is set). If the conversion is not
implemented, set conv to Py_NotImplemented. */
#define NOT_IMPL 0
#define TYPE_ERR 1
Py_LOCAL_INLINE(int)
convert_op(int type_err, PyObject **conv, PyObject *v, PyObject *context)
{
if (PyDec_Check(v)) {
*conv = v;
Py_INCREF(v);
return 1;
}
if (PyLong_Check(v)) {
*conv = PyDec_FromLongExact(v, context);
if (*conv == NULL) {
return 0;
}
return 1;
}
if (type_err) {
PyErr_Format(PyExc_TypeError,
"conversion from %s to Decimal is not supported",
v->ob_type->tp_name);
}
else {
Py_INCREF(Py_NotImplemented);
*conv = Py_NotImplemented;
}
return 0;
}
/* Return NotImplemented for unsupported types. */
#define CONVERT_OP(a, v, context) \
if (!convert_op(NOT_IMPL, a, v, context)) { \
return *(a); \
}
#define CONVERT_BINOP(a, b, v, w, context) \
if (!convert_op(NOT_IMPL, a, v, context)) { \
return *(a); \
} \
if (!convert_op(NOT_IMPL, b, w, context)) { \
Py_DECREF(*(a)); \
return *(b); \
}
#define CONVERT_TERNOP(a, b, c, v, w, x, context) \
if (!convert_op(NOT_IMPL, a, v, context)) { \
return *(a); \
} \
if (!convert_op(NOT_IMPL, b, w, context)) { \
Py_DECREF(*(a)); \
return *(b); \
} \
if (!convert_op(NOT_IMPL, c, x, context)) { \
Py_DECREF(*(a)); \
Py_DECREF(*(b)); \
return *(c); \
}
/* Raise TypeError for unsupported types. */
#define CONVERT_OP_RAISE(a, v, context) \
if (!convert_op(TYPE_ERR, a, v, context)) { \
return NULL; \
}
#define CONVERT_BINOP_RAISE(a, b, v, w, context) \
if (!convert_op(TYPE_ERR, a, v, context)) { \
return NULL; \
} \
if (!convert_op(TYPE_ERR, b, w, context)) { \
Py_DECREF(*(a)); \
return NULL; \
}
#define CONVERT_TERNOP_RAISE(a, b, c, v, w, x, context) \
if (!convert_op(TYPE_ERR, a, v, context)) { \
return NULL; \
} \
if (!convert_op(TYPE_ERR, b, w, context)) { \
Py_DECREF(*(a)); \
return NULL; \
} \
if (!convert_op(TYPE_ERR, c, x, context)) { \
Py_DECREF(*(a)); \
Py_DECREF(*(b)); \
return NULL; \
}
/******************************************************************************/
/* Implicit conversions to Decimal for comparison */
/******************************************************************************/
/* Convert rationals for comparison */
static PyObject *Rational = NULL;
static PyObject *
multiply_by_denominator(PyObject *v, PyObject *r, PyObject *context)
{
PyObject *result;
PyObject *tmp = NULL;
PyObject *denom = NULL;
uint32_t status = 0;
mpd_context_t maxctx;
mpd_ssize_t exp;
mpd_t *vv;
/* v is not special, r is a rational */
tmp = PyObject_GetAttrString(r, "denominator");
if (tmp == NULL) {
return NULL;
}
denom = PyDec_FromLongExact(tmp, context);
Py_DECREF(tmp);
if (denom == NULL) {
return NULL;
}
vv = mpd_qncopy(MPD(v));
if (vv == NULL) {
Py_DECREF(denom);
PyErr_NoMemory();
return NULL;
}
result = dec_alloc();
if (result == NULL) {
Py_DECREF(denom);
mpd_del(vv);
return NULL;
}
mpd_maxcontext(&maxctx);
/* Prevent Overflow in the following multiplication. The result of
the multiplication is only used in mpd_qcmp, which can handle
values that are technically out of bounds, like (for 32-bit)
99999999999999999999...99999999e+425000000. */
exp = vv->exp;
vv->exp = 0;
mpd_qmul(MPD(result), vv, MPD(denom), &maxctx, &status);
MPD(result)->exp = exp;
Py_DECREF(denom);
mpd_del(vv);
/* If any status has been accumulated during the multiplication,
the result is invalid. This is very unlikely, since even the
32-bit version supports 425000000 digits. */
if (status) {
PyErr_SetString(PyExc_ValueError,
"exact conversion for comparison failed");
Py_DECREF(result);
return NULL;
}
return result;
}
static PyObject *
numerator_as_decimal(PyObject *r, PyObject *context)
{
PyObject *tmp, *num;
tmp = PyObject_GetAttrString(r, "numerator");
if (tmp == NULL) {
return NULL;
}
num = PyDec_FromLongExact(tmp, context);
Py_DECREF(tmp);
return num;
}
/* Convert v and w for comparison. v is a Decimal. If w is a Rational, both
v and w have to be transformed. Return 1 for success, with new references
to the converted objects in vcmp and wcmp. Return 0 for failure. In that
case wcmp is either NULL or Py_NotImplemented (new reference) and vcmp
is undefined. */
static int
convert_op_cmp(PyObject **vcmp, PyObject **wcmp, PyObject *v, PyObject *w,
int op, PyObject *context)
{
mpd_context_t *ctx = CTX(context);
*vcmp = v;
if (PyDec_Check(w)) {
Py_INCREF(w);
*wcmp = w;
}
else if (PyLong_Check(w)) {
*wcmp = PyDec_FromLongExact(w, context);
}
else if (PyFloat_Check(w)) {
if (op != Py_EQ && op != Py_NE &&
dec_addstatus(context, MPD_Float_operation)) {
*wcmp = NULL;
}
else {
ctx->status |= MPD_Float_operation;
*wcmp = PyDec_FromFloatExact(w, context);
}
}
else if (PyComplex_Check(w) && (op == Py_EQ || op == Py_NE)) {
Py_complex c = PyComplex_AsCComplex(w);
if (c.real == -1.0 && PyErr_Occurred()) {
*wcmp = NULL;
}
else if (c.imag == 0.0) {
PyObject *tmp = PyFloat_FromDouble(c.real);
if (tmp == NULL) {
*wcmp = NULL;
}
else {
ctx->status |= MPD_Float_operation;
*wcmp = PyDec_FromFloatExact(tmp, context);
Py_DECREF(tmp);
}
}
else {
Py_INCREF(Py_NotImplemented);
*wcmp = Py_NotImplemented;
}
}
else {
int is_rational = PyObject_IsInstance(w, Rational);
if (is_rational < 0) {
*wcmp = NULL;
}
else if (is_rational > 0) {
*wcmp = numerator_as_decimal(w, context);
if (*wcmp && !mpd_isspecial(MPD(v))) {
*vcmp = multiply_by_denominator(v, w, context);
if (*vcmp == NULL) {
Py_CLEAR(*wcmp);
}
}
}
else {
Py_INCREF(Py_NotImplemented);
*wcmp = Py_NotImplemented;
}
}
if (*wcmp == NULL || *wcmp == Py_NotImplemented) {
return 0;
}
if (*vcmp == v) {
Py_INCREF(v);
}
return 1;
}
#define CONVERT_BINOP_CMP(vcmp, wcmp, v, w, op, ctx) \
if (!convert_op_cmp(vcmp, wcmp, v, w, op, ctx)) { \
return *(wcmp); \
} \
/******************************************************************************/
/* Conversions from decimal */
/******************************************************************************/
static PyObject *
unicode_fromascii(const char *s, Py_ssize_t size)
{
PyObject *res;
res = PyUnicode_New(size, 127);
if (res == NULL) {
return NULL;
}
memcpy(PyUnicode_1BYTE_DATA(res), s, size);
return res;
}
/* PyDecObject as a string. The default module context is only used for
the value of 'capitals'. */
static PyObject *
dec_str(PyObject *dec)
{
PyObject *res, *context;
mpd_ssize_t size;
char *cp;
CURRENT_CONTEXT(context);
size = mpd_to_sci_size(&cp, MPD(dec), CtxCaps(context));
if (size < 0) {
PyErr_NoMemory();
return NULL;
}
res = unicode_fromascii(cp, size);
mpd_free(cp);
return res;
}
/* Representation of a PyDecObject. */
static PyObject *
dec_repr(PyObject *dec)
{
PyObject *res, *context;
char *cp;
CURRENT_CONTEXT(context);
cp = mpd_to_sci(MPD(dec), CtxCaps(context));
if (cp == NULL) {
PyErr_NoMemory();
return NULL;
}
res = PyUnicode_FromFormat("Decimal('%s')", cp);
mpd_free(cp);
return res;
}
/* Return a duplicate of src, copy embedded null characters. */
static char *
dec_strdup(const char *src, Py_ssize_t size)
{
char *dest = PyMem_Malloc(size+1);
if (dest == NULL) {
PyErr_NoMemory();
return NULL;
}
memcpy(dest, src, size);
dest[size] = '\0';
return dest;
}
static void
dec_replace_fillchar(char *dest)
{
while (*dest != '\0') {
if (*dest == '\xff') *dest = '\0';
dest++;
}
}
/* Convert decimal_point or thousands_sep, which may be multibyte or in
the range [128, 255], to a UTF8 string. */
static PyObject *
dotsep_as_utf8(const char *s)
{
PyObject *utf8;
PyObject *tmp;
wchar_t buf[2];
size_t n;
n = mbstowcs(buf, s, 2);
if (n != 1) { /* Issue #7442 */
PyErr_SetString(PyExc_ValueError,
"invalid decimal point or unsupported "
"combination of LC_CTYPE and LC_NUMERIC");
return NULL;
}
tmp = PyUnicode_FromWideChar(buf, n);
if (tmp == NULL) {
return NULL;
}
utf8 = PyUnicode_AsUTF8String(tmp);
Py_DECREF(tmp);
return utf8;
}
/* Formatted representation of a PyDecObject. */
static PyObject *
dec_format(PyObject *dec, PyObject *args)
{
PyObject *result = NULL;
PyObject *override = NULL;
PyObject *dot = NULL;
PyObject *sep = NULL;
PyObject *grouping = NULL;
PyObject *fmtarg;
PyObject *context;
mpd_spec_t spec;
char *fmt;
char *decstring = NULL;
uint32_t status = 0;
int replace_fillchar = 0;
Py_ssize_t size;
CURRENT_CONTEXT(context);
if (!PyArg_ParseTuple(args, "O|O", &fmtarg, &override)) {
return NULL;
}
if (PyUnicode_Check(fmtarg)) {
fmt = PyUnicode_AsUTF8AndSize(fmtarg, &size);
if (fmt == NULL) {
return NULL;
}
if (size > 0 && fmt[0] == '\0') {
/* NUL fill character: must be replaced with a valid UTF-8 char
before calling mpd_parse_fmt_str(). */
replace_fillchar = 1;
fmt = dec_strdup(fmt, size);
if (fmt == NULL) {
return NULL;
}
fmt[0] = '_';
}
}
else {
PyErr_SetString(PyExc_TypeError,
"format arg must be str");
return NULL;
}
if (!mpd_parse_fmt_str(&spec, fmt, CtxCaps(context))) {
PyErr_SetString(PyExc_ValueError,
"invalid format string");
goto finish;
}
if (replace_fillchar) {
/* In order to avoid clobbering parts of UTF-8 thousands separators or
decimal points when the substitution is reversed later, the actual
placeholder must be an invalid UTF-8 byte. */
spec.fill[0] = '\xff';
spec.fill[1] = '\0';
}
if (override) {
/* Values for decimal_point, thousands_sep and grouping can
be explicitly specified in the override dict. These values
take precedence over the values obtained from localeconv()
in mpd_parse_fmt_str(). The feature is not documented and
is only used in test_decimal. */
if (!PyDict_Check(override)) {
PyErr_SetString(PyExc_TypeError,
"optional argument must be a dict");
goto finish;
}
if ((dot = PyDict_GetItemString(override, "decimal_point"))) {
if ((dot = PyUnicode_AsUTF8String(dot)) == NULL) {
goto finish;
}
spec.dot = PyBytes_AS_STRING(dot);
}
if ((sep = PyDict_GetItemString(override, "thousands_sep"))) {
if ((sep = PyUnicode_AsUTF8String(sep)) == NULL) {
goto finish;
}
spec.sep = PyBytes_AS_STRING(sep);
}
if ((grouping = PyDict_GetItemString(override, "grouping"))) {
if ((grouping = PyUnicode_AsUTF8String(grouping)) == NULL) {
goto finish;
}
spec.grouping = PyBytes_AS_STRING(grouping);
}
if (mpd_validate_lconv(&spec) < 0) {
PyErr_SetString(PyExc_ValueError,
"invalid override dict");
goto finish;
}
}
else {
size_t n = strlen(spec.dot);
if (n > 1 || (n == 1 && !isascii((uchar)spec.dot[0]))) {
/* fix locale dependent non-ascii characters */
dot = dotsep_as_utf8(spec.dot);
if (dot == NULL) {
goto finish;
}
spec.dot = PyBytes_AS_STRING(dot);
}
n = strlen(spec.sep);
if (n > 1 || (n == 1 && !isascii((uchar)spec.sep[0]))) {
/* fix locale dependent non-ascii characters */
sep = dotsep_as_utf8(spec.sep);
if (sep == NULL) {
goto finish;
}
spec.sep = PyBytes_AS_STRING(sep);
}
}
decstring = mpd_qformat_spec(MPD(dec), &spec, CTX(context), &status);
if (decstring == NULL) {
if (status & MPD_Malloc_error) {
PyErr_NoMemory();
}
else {
PyErr_SetString(PyExc_ValueError,
"format specification exceeds internal limits of _decimal");
}
goto finish;
}
size = strlen(decstring);
if (replace_fillchar) {
dec_replace_fillchar(decstring);
}
result = PyUnicode_DecodeUTF8(decstring, size, NULL);
finish:
Py_XDECREF(grouping);
Py_XDECREF(sep);
Py_XDECREF(dot);
if (replace_fillchar) PyMem_Free(fmt);
if (decstring) mpd_free(decstring);
return result;
}
/* Return a PyLongObject from a PyDecObject, using the specified rounding
* mode. The context precision is not observed. */
static PyObject *
dec_as_long(PyObject *dec, PyObject *context, int round)
{
PyLongObject *pylong;
digit *ob_digit;
size_t n;
Py_ssize_t i;
mpd_t *x;
mpd_context_t workctx;
uint32_t status = 0;
if (mpd_isspecial(MPD(dec))) {
if (mpd_isnan(MPD(dec))) {
PyErr_SetString(PyExc_ValueError,
"cannot convert NaN to integer");
}
else {
PyErr_SetString(PyExc_OverflowError,
"cannot convert Infinity to integer");
}
return NULL;
}
x = mpd_qnew();
if (x == NULL) {
PyErr_NoMemory();
return NULL;
}
workctx = *CTX(context);
workctx.round = round;
mpd_qround_to_int(x, MPD(dec), &workctx, &status);
if (dec_addstatus(context, status)) {
mpd_del(x);
return NULL;
}
status = 0;
ob_digit = NULL;
#if PYLONG_BITS_IN_DIGIT == 30
n = mpd_qexport_u32(&ob_digit, 0, PyLong_BASE, x, &status);
#elif PYLONG_BITS_IN_DIGIT == 15
n = mpd_qexport_u16(&ob_digit, 0, PyLong_BASE, x, &status);
#else
#error "PYLONG_BITS_IN_DIGIT should be 15 or 30"
#endif
if (n == SIZE_MAX) {
PyErr_NoMemory();
mpd_del(x);
return NULL;
}
assert(n > 0);
pylong = _PyLong_New(n);
if (pylong == NULL) {
mpd_free(ob_digit);
mpd_del(x);
return NULL;
}
memcpy(pylong->ob_digit, ob_digit, n * sizeof(digit));
mpd_free(ob_digit);
i = n;
while ((i > 0) && (pylong->ob_digit[i-1] == 0)) {
i--;
}
Py_SIZE(pylong) = i;
if (mpd_isnegative(x) && !mpd_iszero(x)) {
Py_SIZE(pylong) = -i;
}
mpd_del(x);
return (PyObject *) pylong;
}
/* Convert a Decimal to its exact integer ratio representation. */
static PyObject *
dec_as_integer_ratio(PyObject *self, PyObject *args)
{
PyObject *numerator = NULL;
PyObject *denominator = NULL;
PyObject *exponent = NULL;
PyObject *result = NULL;
PyObject *tmp;
mpd_ssize_t exp;
PyObject *context;
uint32_t status = 0;
if (mpd_isspecial(MPD(self))) {
if (mpd_isnan(MPD(self))) {
PyErr_SetString(PyExc_ValueError,
"cannot convert NaN to integer ratio");
}
else {
PyErr_SetString(PyExc_OverflowError,
"cannot convert Infinity to integer ratio");
}
return NULL;
}
CURRENT_CONTEXT(context);
tmp = dec_alloc();
if (tmp == NULL) {
return NULL;
}
if (!mpd_qcopy(MPD(tmp), MPD(self), &status)) {
Py_DECREF(tmp);
PyErr_NoMemory();
return NULL;
}
exp = mpd_iszero(MPD(tmp)) ? 0 : MPD(tmp)->exp;
MPD(tmp)->exp = 0;
/* context and rounding are unused here: the conversion is exact */
numerator = dec_as_long(tmp, context, MPD_ROUND_FLOOR);
Py_DECREF(tmp);
if (numerator == NULL) {
goto error;
}
exponent = PyLong_FromSsize_t(exp < 0 ? -exp : exp);
if (exponent == NULL) {
goto error;
}
tmp = PyLong_FromLong(10);
if (tmp == NULL) {
goto error;
}
Py_SETREF(exponent, _py_long_power(tmp, exponent, Py_None));
Py_DECREF(tmp);
if (exponent == NULL) {
goto error;
}
if (exp >= 0) {
Py_SETREF(numerator, _py_long_multiply(numerator, exponent));
if (numerator == NULL) {
goto error;
}
denominator = PyLong_FromLong(1);
if (denominator == NULL) {
goto error;
}
}
else {
denominator = exponent;
exponent = NULL;
tmp = _PyLong_GCD(numerator, denominator);
if (tmp == NULL) {
goto error;
}
Py_SETREF(numerator, _py_long_floor_divide(numerator, tmp));
Py_SETREF(denominator, _py_long_floor_divide(denominator, tmp));
Py_DECREF(tmp);
if (numerator == NULL || denominator == NULL) {
goto error;
}
}
result = PyTuple_Pack(2, numerator, denominator);
error:
Py_XDECREF(exponent);
Py_XDECREF(denominator);
Py_XDECREF(numerator);
return result;
}
static PyObject *
PyDec_ToIntegralValue(PyObject *dec, PyObject *args, PyObject *kwds)
{
static char *kwlist[] = {"rounding", "context", NULL};
PyObject *result;
PyObject *rounding = Py_None;
PyObject *context = Py_None;
uint32_t status = 0;
mpd_context_t workctx;
if (!PyArg_ParseTupleAndKeywords(args, kwds, "|OO", kwlist,
&rounding, &context)) {
return NULL;
}
CONTEXT_CHECK_VA(context);
workctx = *CTX(context);
if (rounding != Py_None) {
int round = getround(rounding);
if (round < 0) {
return NULL;
}
if (!mpd_qsetround(&workctx, round)) {
INTERNAL_ERROR_PTR("PyDec_ToIntegralValue"); /* GCOV_NOT_REACHED */
}
}
result = dec_alloc();
if (result == NULL) {
return NULL;
}
mpd_qround_to_int(MPD(result), MPD(dec), &workctx, &status);
if (dec_addstatus(context, status)) {
Py_DECREF(result);
return NULL;
}
return result;
}
static PyObject *
PyDec_ToIntegralExact(PyObject *dec, PyObject *args, PyObject *kwds)
{
static char *kwlist[] = {"rounding", "context", NULL};
PyObject *result;
PyObject *rounding = Py_None;
PyObject *context = Py_None;
uint32_t status = 0;
mpd_context_t workctx;
if (!PyArg_ParseTupleAndKeywords(args, kwds, "|OO", kwlist,
&rounding, &context)) {
return NULL;
}
CONTEXT_CHECK_VA(context);
workctx = *CTX(context);
if (rounding != Py_None) {
int round = getround(rounding);
if (round < 0) {
return NULL;
}
if (!mpd_qsetround(&workctx, round)) {
INTERNAL_ERROR_PTR("PyDec_ToIntegralExact"); /* GCOV_NOT_REACHED */
}
}
result = dec_alloc();
if (result == NULL) {
return NULL;
}
mpd_qround_to_intx(MPD(result), MPD(dec), &workctx, &status);
if (dec_addstatus(context, status)) {
Py_DECREF(result);
return NULL;
}
return result;
}
static PyObject *
PyDec_AsFloat(PyObject *dec)
{
PyObject *f, *s;
if (mpd_isnan(MPD(dec))) {
if (mpd_issnan(MPD(dec))) {
PyErr_SetString(PyExc_ValueError,
"cannot convert signaling NaN to float");
return NULL;
}
if (mpd_isnegative(MPD(dec))) {
s = PyUnicode_FromString("-nan");
}
else {
s = PyUnicode_FromString("nan");
}
}
else {
s = dec_str(dec);
}
if (s == NULL) {
return NULL;
}
f = PyFloat_FromString(s);
Py_DECREF(s);
return f;
}
static PyObject *
PyDec_Round(PyObject *dec, PyObject *args)
{
PyObject *result;
PyObject *x = NULL;
uint32_t status = 0;
PyObject *context;
CURRENT_CONTEXT(context);
if (!PyArg_ParseTuple(args, "|O", &x)) {
return NULL;
}
if (x) {
mpd_uint_t dq[1] = {1};
mpd_t q = {MPD_STATIC|MPD_CONST_DATA,0,1,1,1,dq};
mpd_ssize_t y;
if (!PyLong_Check(x)) {
PyErr_SetString(PyExc_TypeError,
"optional arg must be an integer");
return NULL;
}
y = PyLong_AsSsize_t(x);
if (y == -1 && PyErr_Occurred()) {
return NULL;
}
result = dec_alloc();
if (result == NULL) {
return NULL;
}
q.exp = (y == MPD_SSIZE_MIN) ? MPD_SSIZE_MAX : -y;
mpd_qquantize(MPD(result), MPD(dec), &q, CTX(context), &status);
if (dec_addstatus(context, status)) {
Py_DECREF(result);
return NULL;
}
return result;
}
else {
return dec_as_long(dec, context, MPD_ROUND_HALF_EVEN);
}
}
static PyTypeObject *DecimalTuple = NULL;
/* Return the DecimalTuple representation of a PyDecObject. */
static PyObject *
PyDec_AsTuple(PyObject *dec, PyObject *dummy)
{
PyObject *result = NULL;
PyObject *sign = NULL;
PyObject *coeff = NULL;
PyObject *expt = NULL;
PyObject *tmp = NULL;
mpd_t *x = NULL;
char *intstring = NULL;
Py_ssize_t intlen, i;
x = mpd_qncopy(MPD(dec));
if (x == NULL) {
PyErr_NoMemory();
goto out;
}
sign = PyLong_FromUnsignedLong(mpd_sign(MPD(dec)));
if (sign == NULL) {
goto out;
}
if (mpd_isinfinite(x)) {
expt = PyUnicode_FromString("F");
if (expt == NULL) {
goto out;
}
/* decimal.py has non-compliant infinity payloads. */
coeff = Py_BuildValue("(i)", 0);
if (coeff == NULL) {
goto out;
}
}
else {
if (mpd_isnan(x)) {
expt = PyUnicode_FromString(mpd_isqnan(x)?"n":"N");
}
else {
expt = PyLong_FromSsize_t(MPD(dec)->exp);
}
if (expt == NULL) {
goto out;
}
/* coefficient is defined */
if (x->len > 0) {
/* make an integer */
x->exp = 0;
/* clear NaN and sign */
mpd_clear_flags(x);
intstring = mpd_to_sci(x, 1);
if (intstring == NULL) {
PyErr_NoMemory();
goto out;
}
intlen = strlen(intstring);
coeff = PyTuple_New(intlen);
if (coeff == NULL) {
goto out;
}
for (i = 0; i < intlen; i++) {
tmp = PyLong_FromLong(intstring[i]-'0');
if (tmp == NULL) {
goto out;
}
PyTuple_SET_ITEM(coeff, i, tmp);
}
}
else {
coeff = PyTuple_New(0);
if (coeff == NULL) {
goto out;
}
}
}
result = PyObject_CallFunctionObjArgs((PyObject *)DecimalTuple,
sign, coeff, expt, NULL);
out:
if (x) mpd_del(x);
if (intstring) mpd_free(intstring);
Py_XDECREF(sign);
Py_XDECREF(coeff);
Py_XDECREF(expt);
return result;
}
/******************************************************************************/
/* Macros for converting mpdecimal functions to Decimal methods */
/******************************************************************************/
static PyObject *
_Dec_UnaryNumberMethod(PyObject *self,
void mpdfunc(mpd_t *, const mpd_t *,
const mpd_context_t *,
uint32_t *))
{
PyObject *result;
PyObject *context;
uint32_t status = 0;
CURRENT_CONTEXT(context);
if ((result = dec_alloc()) == NULL) {
return NULL;
}
mpdfunc(MPD(result), MPD(self), CTX(context), &status);
if (dec_addstatus(context, status)) {
Py_DECREF(result);
return NULL;
}
return result;
}
/* Unary number method that uses the default module context. */
#define Dec_UnaryNumberMethod(MPDFUNC) \
static PyObject * \
nm_##MPDFUNC(PyObject *self) \
{ \
return _Dec_UnaryNumberMethod(self, MPDFUNC); \
}
static PyObject *
_Dec_BinaryNumberMethod(PyObject *self, PyObject *other,
void mpdfunc(mpd_t *, const mpd_t *, const mpd_t *,
const mpd_context_t *, uint32_t *))
{
PyObject *a, *b;
PyObject *result;
PyObject *context;
uint32_t status = 0;
CURRENT_CONTEXT(context) ;
CONVERT_BINOP(&a, &b, self, other, context);
if ((result = dec_alloc()) == NULL) {
Py_DECREF(a);
Py_DECREF(b);
return NULL;
}
mpdfunc(MPD(result), MPD(a), MPD(b), CTX(context), &status);
Py_DECREF(a);
Py_DECREF(b);
if (dec_addstatus(context, status)) {
Py_DECREF(result);
return NULL;
}
return result;
}
/* Binary number method that uses default module context. */
#define Dec_BinaryNumberMethod(MPDFUNC) \
static PyObject * \
nm_##MPDFUNC(PyObject *self, PyObject *other) \
{ \
return _Dec_BinaryNumberMethod(self, other, MPDFUNC); \
}
/* Boolean function without a context arg. */
#define Dec_BoolFunc(MPDFUNC) \
static PyObject * \
dec_##MPDFUNC(PyObject *self, PyObject *dummy) \
{ \
return MPDFUNC(MPD(self)) ? incr_true() : incr_false(); \
}
/* Boolean function with an optional context arg. */
#define Dec_BoolFuncVA(MPDFUNC) \
static PyObject * \
dec_##MPDFUNC(PyObject *self, PyObject *args, PyObject *kwds) \
{ \
static char *kwlist[] = {"context", NULL}; \
PyObject *context = Py_None; \
\
if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O", kwlist, \
&context)) { \
return NULL; \
} \
CONTEXT_CHECK_VA(context); \
\
return MPDFUNC(MPD(self), CTX(context)) ? incr_true() : incr_false(); \
}
static PyObject *
_Dec_UnaryFuncVA(PyObject *self, PyObject *args, PyObject *kwds,
void mpdfunc(mpd_t *, const mpd_t *, const mpd_context_t *,
uint32_t *))
{
static char *kwlist[] = {"context", NULL};
PyObject *result;
PyObject *context = Py_None;
uint32_t status = 0;
if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O", kwlist,
&context)) {
return NULL;
}
CONTEXT_CHECK_VA(context);
if ((result = dec_alloc()) == NULL) {
return NULL;
}
mpdfunc(MPD(result), MPD(self), CTX(context), &status);
if (dec_addstatus(context, status)) {
Py_DECREF(result);
return NULL;
}
return result;
}
/* Unary function with an optional context arg. */
#define Dec_UnaryFuncVA(MPDFUNC) \
static PyObject * \
dec_##MPDFUNC(PyObject *self, PyObject *args, PyObject *kwds) \
{ \
return _Dec_UnaryFuncVA(self, args, kwds, MPDFUNC); \
}
static PyObject *
_Dec_BinaryFuncVA(PyObject *self, PyObject *args, PyObject *kwds,
void mpdfunc(mpd_t *, const mpd_t *, const mpd_t *,
const mpd_context_t *, uint32_t *))
{
static char *kwlist[] = {"other", "context", NULL};
PyObject *other;
PyObject *a, *b;
PyObject *result;
PyObject *context = Py_None;
uint32_t status = 0;
if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O", kwlist,
&other, &context)) {
return NULL;
}
CONTEXT_CHECK_VA(context);
CONVERT_BINOP_RAISE(&a, &b, self, other, context);
if ((result = dec_alloc()) == NULL) {
Py_DECREF(a);
Py_DECREF(b);
return NULL;
}
mpdfunc(MPD(result), MPD(a), MPD(b), CTX(context), &status);
Py_DECREF(a);
Py_DECREF(b);
if (dec_addstatus(context, status)) {
Py_DECREF(result);
return NULL;
}
return result;
}
/* Binary function with an optional context arg. */
#define Dec_BinaryFuncVA(MPDFUNC) \
static PyObject * \
dec_##MPDFUNC(PyObject *self, PyObject *args, PyObject *kwds) \
{ \
return _Dec_BinaryFuncVA(self, args, kwds, (void *)MPDFUNC); \
}
static PyObject *
_Dec_BinaryFuncVA_NO_CTX(PyObject *self, PyObject *args, PyObject *kwds,
int mpdfunc(mpd_t *, const mpd_t *, const mpd_t *))
{
static char *kwlist[] = {"other", "context", NULL};
PyObject *context = Py_None;
PyObject *other;
PyObject *a, *b;
PyObject *result;
if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O", kwlist,
&other, &context)) {
return NULL;
}
CONTEXT_CHECK_VA(context);
CONVERT_BINOP_RAISE(&a, &b, self, other, context);
if ((result = dec_alloc()) == NULL) {
Py_DECREF(a);
Py_DECREF(b);
return NULL;
}
mpdfunc(MPD(result), MPD(a), MPD(b));
Py_DECREF(a);
Py_DECREF(b);
return result;
}
/* Binary function with an optional context arg. Actual MPDFUNC does
NOT take a context. The context is used to record InvalidOperation
if the second operand cannot be converted exactly. */
#define Dec_BinaryFuncVA_NO_CTX(MPDFUNC) \
static PyObject * \
dec_##MPDFUNC(PyObject *self, PyObject *args, PyObject *kwds) \
{ \
return _Dec_BinaryFuncVA_NO_CTX(self, args, kwds, MPDFUNC); \
}
/* Ternary function with an optional context arg. */
#define Dec_TernaryFuncVA(MPDFUNC) \
static PyObject * \
dec_##MPDFUNC(PyObject *self, PyObject *args, PyObject *kwds) \
{ \
static char *kwlist[] = {"other", "third", "context", NULL}; \
PyObject *other, *third; \
PyObject *a, *b, *c; \
PyObject *result; \
PyObject *context = Py_None; \
uint32_t status = 0; \
\
if (!PyArg_ParseTupleAndKeywords(args, kwds, "OO|O", kwlist, \
&other, &third, &context)) { \
return NULL; \
} \
CONTEXT_CHECK_VA(context); \
CONVERT_TERNOP_RAISE(&a, &b, &c, self, other, third, context); \
\
if ((result = dec_alloc()) == NULL) { \
Py_DECREF(a); \
Py_DECREF(b); \
Py_DECREF(c); \
return NULL; \
} \
\
MPDFUNC(MPD(result), MPD(a), MPD(b), MPD(c), CTX(context), &status); \
Py_DECREF(a); \
Py_DECREF(b); \
Py_DECREF(c); \
if (dec_addstatus(context, status)) { \
Py_DECREF(result); \
return NULL; \
} \
\
return result; \
}
/**********************************************/
/* Number methods */
/**********************************************/
Dec_UnaryNumberMethod(mpd_qminus)
Dec_UnaryNumberMethod(mpd_qplus)
Dec_UnaryNumberMethod(mpd_qabs)
Dec_BinaryNumberMethod(mpd_qadd)
Dec_BinaryNumberMethod(mpd_qsub)
Dec_BinaryNumberMethod(mpd_qmul)
Dec_BinaryNumberMethod(mpd_qdiv)
Dec_BinaryNumberMethod(mpd_qrem)
Dec_BinaryNumberMethod(mpd_qdivint)
static PyObject *
nm_dec_as_long(PyObject *dec)
{
PyObject *context;
CURRENT_CONTEXT(context);
return dec_as_long(dec, context, MPD_ROUND_DOWN);
}
static int
nm_nonzero(PyObject *v)
{
return !mpd_iszero(MPD(v));
}
static PyObject *
nm_mpd_qdivmod(PyObject *v, PyObject *w)
{
PyObject *a, *b;
PyObject *q, *r;
PyObject *context;
uint32_t status = 0;
PyObject *ret;
CURRENT_CONTEXT(context);
CONVERT_BINOP(&a, &b, v, w, context);
q = dec_alloc();
if (q == NULL) {
Py_DECREF(a);
Py_DECREF(b);
return NULL;
}
r = dec_alloc();
if (r == NULL) {
Py_DECREF(a);
Py_DECREF(b);
Py_DECREF(q);
return NULL;
}
mpd_qdivmod(MPD(q), MPD(r), MPD(a), MPD(b), CTX(context), &status);
Py_DECREF(a);
Py_DECREF(b);
if (dec_addstatus(context, status)) {
Py_DECREF(r);
Py_DECREF(q);
return NULL;
}
ret = Py_BuildValue("(OO)", q, r);
Py_DECREF(r);
Py_DECREF(q);
return ret;
}
static PyObject *
nm_mpd_qpow(PyObject *base, PyObject *exp, PyObject *mod)
{
PyObject *a, *b, *c = NULL;
PyObject *result;
PyObject *context;
uint32_t status = 0;
CURRENT_CONTEXT(context);
CONVERT_BINOP(&a, &b, base, exp, context);
if (mod != Py_None) {
if (!convert_op(NOT_IMPL, &c, mod, context)) {
Py_DECREF(a);
Py_DECREF(b);
return c;
}
}
result = dec_alloc();
if (result == NULL) {
Py_DECREF(a);
Py_DECREF(b);
Py_XDECREF(c);
return NULL;
}
if (c == NULL) {
mpd_qpow(MPD(result), MPD(a), MPD(b),
CTX(context), &status);
}
else {
mpd_qpowmod(MPD(result), MPD(a), MPD(b), MPD(c),
CTX(context), &status);
Py_DECREF(c);
}
Py_DECREF(a);
Py_DECREF(b);
if (dec_addstatus(context, status)) {
Py_DECREF(result);
return NULL;
}
return result;
}
/******************************************************************************/
/* Decimal Methods */
/******************************************************************************/
/* Unary arithmetic functions, optional context arg */
Dec_UnaryFuncVA(mpd_qexp)
Dec_UnaryFuncVA(mpd_qln)
Dec_UnaryFuncVA(mpd_qlog10)
Dec_UnaryFuncVA(mpd_qnext_minus)
Dec_UnaryFuncVA(mpd_qnext_plus)
Dec_UnaryFuncVA(mpd_qreduce)
Dec_UnaryFuncVA(mpd_qsqrt)
/* Binary arithmetic functions, optional context arg */
Dec_BinaryFuncVA(mpd_qcompare)
Dec_BinaryFuncVA(mpd_qcompare_signal)
Dec_BinaryFuncVA(mpd_qmax)
Dec_BinaryFuncVA(mpd_qmax_mag)
Dec_BinaryFuncVA(mpd_qmin)
Dec_BinaryFuncVA(mpd_qmin_mag)
Dec_BinaryFuncVA(mpd_qnext_toward)
Dec_BinaryFuncVA(mpd_qrem_near)
/* Ternary arithmetic functions, optional context arg */
Dec_TernaryFuncVA(mpd_qfma)
/* Boolean functions, no context arg */
Dec_BoolFunc(mpd_iscanonical)
Dec_BoolFunc(mpd_isfinite)
Dec_BoolFunc(mpd_isinfinite)
Dec_BoolFunc(mpd_isnan)
Dec_BoolFunc(mpd_isqnan)
Dec_BoolFunc(mpd_issnan)
Dec_BoolFunc(mpd_issigned)
Dec_BoolFunc(mpd_iszero)
/* Boolean functions, optional context arg */
Dec_BoolFuncVA(mpd_isnormal)
Dec_BoolFuncVA(mpd_issubnormal)
/* Unary functions, no context arg */
static PyObject *
dec_mpd_adjexp(PyObject *self, PyObject *dummy)
{
mpd_ssize_t retval;
if (mpd_isspecial(MPD(self))) {
retval = 0;
}
else {
retval = mpd_adjexp(MPD(self));
}
return PyLong_FromSsize_t(retval);
}
static PyObject *
dec_canonical(PyObject *self, PyObject *dummy)
{
Py_INCREF(self);
return self;
}
static PyObject *
dec_conjugate(PyObject *self, PyObject *dummy)
{
Py_INCREF(self);
return self;
}
static PyObject *
dec_mpd_radix(PyObject *self, PyObject *dummy)
{
PyObject *result;
result = dec_alloc();
if (result == NULL) {
return NULL;
}
_dec_settriple(result, MPD_POS, 10, 0);
return result;
}
static PyObject *
dec_mpd_qcopy_abs(PyObject *self, PyObject *dummy)
{
PyObject *result;
uint32_t status = 0;
if ((result = dec_alloc()) == NULL) {
return NULL;
}
mpd_qcopy_abs(MPD(result), MPD(self), &status);
if (status & MPD_Malloc_error) {
Py_DECREF(result);
PyErr_NoMemory();
return NULL;
}
return result;
}
static PyObject *
dec_mpd_qcopy_negate(PyObject *self, PyObject *dummy)
{
PyObject *result;
uint32_t status = 0;
if ((result = dec_alloc()) == NULL) {
return NULL;
}
mpd_qcopy_negate(MPD(result), MPD(self), &status);
if (status & MPD_Malloc_error) {
Py_DECREF(result);
PyErr_NoMemory();
return NULL;
}
return result;
}
/* Unary functions, optional context arg */
Dec_UnaryFuncVA(mpd_qinvert)
Dec_UnaryFuncVA(mpd_qlogb)
static PyObject *
dec_mpd_class(PyObject *self, PyObject *args, PyObject *kwds)
{
static char *kwlist[] = {"context", NULL};
PyObject *context = Py_None;
const char *cp;
if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O", kwlist,
&context)) {
return NULL;
}
CONTEXT_CHECK_VA(context);
cp = mpd_class(MPD(self), CTX(context));
return PyUnicode_FromString(cp);
}
static PyObject *
dec_mpd_to_eng(PyObject *self, PyObject *args, PyObject *kwds)
{
static char *kwlist[] = {"context", NULL};
PyObject *result;
PyObject *context = Py_None;
mpd_ssize_t size;
char *s;
if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O", kwlist,
&context)) {
return NULL;
}
CONTEXT_CHECK_VA(context);
size = mpd_to_eng_size(&s, MPD(self), CtxCaps(context));
if (size < 0) {
PyErr_NoMemory();
return NULL;
}
result = unicode_fromascii(s, size);
mpd_free(s);
return result;
}
/* Binary functions, optional context arg for conversion errors */
Dec_BinaryFuncVA_NO_CTX(mpd_compare_total)
Dec_BinaryFuncVA_NO_CTX(mpd_compare_total_mag)
static PyObject *
dec_mpd_qcopy_sign(PyObject *self, PyObject *args, PyObject *kwds)
{
static char *kwlist[] = {"other", "context", NULL};
PyObject *other;
PyObject *a, *b;
PyObject *result;
PyObject *context = Py_None;
uint32_t status = 0;
if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O", kwlist,
&other, &context)) {
return NULL;
}
CONTEXT_CHECK_VA(context);
CONVERT_BINOP_RAISE(&a, &b, self, other, context);
result = dec_alloc();
if (result == NULL) {
Py_DECREF(a);
Py_DECREF(b);
return NULL;
}
mpd_qcopy_sign(MPD(result), MPD(a), MPD(b), &status);
Py_DECREF(a);
Py_DECREF(b);
if (dec_addstatus(context, status)) {
Py_DECREF(result);
return NULL;
}
return result;
}
static PyObject *
dec_mpd_same_quantum(PyObject *self, PyObject *args, PyObject *kwds)
{
static char *kwlist[] = {"other", "context", NULL};
PyObject *other;
PyObject *a, *b;
PyObject *result;
PyObject *context = Py_None;
if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O", kwlist,
&other, &context)) {
return NULL;
}
CONTEXT_CHECK_VA(context);
CONVERT_BINOP_RAISE(&a, &b, self, other, context);
result = mpd_same_quantum(MPD(a), MPD(b)) ? incr_true() : incr_false();
Py_DECREF(a);
Py_DECREF(b);
return result;
}
/* Binary functions, optional context arg */
Dec_BinaryFuncVA(mpd_qand)
Dec_BinaryFuncVA(mpd_qor)
Dec_BinaryFuncVA(mpd_qxor)
Dec_BinaryFuncVA(mpd_qrotate)
Dec_BinaryFuncVA(mpd_qscaleb)
Dec_BinaryFuncVA(mpd_qshift)
static PyObject *
dec_mpd_qquantize(PyObject *v, PyObject *args, PyObject *kwds)
{
static char *kwlist[] = {"exp", "rounding", "context", NULL};
PyObject *rounding = Py_None;
PyObject *context = Py_None;
PyObject *w, *a, *b;
PyObject *result;
uint32_t status = 0;
mpd_context_t workctx;
if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|OO", kwlist,
&w, &rounding, &context)) {
return NULL;
}
CONTEXT_CHECK_VA(context);
workctx = *CTX(context);
if (rounding != Py_None) {
int round = getround(rounding);
if (round < 0) {
return NULL;
}
if (!mpd_qsetround(&workctx, round)) {
INTERNAL_ERROR_PTR("dec_mpd_qquantize"); /* GCOV_NOT_REACHED */
}
}
CONVERT_BINOP_RAISE(&a, &b, v, w, context);
result = dec_alloc();
if (result == NULL) {
Py_DECREF(a);
Py_DECREF(b);
return NULL;
}
mpd_qquantize(MPD(result), MPD(a), MPD(b), &workctx, &status);
Py_DECREF(a);
Py_DECREF(b);
if (dec_addstatus(context, status)) {
Py_DECREF(result);
return NULL;
}
return result;
}
/* Special methods */
static PyObject *
dec_richcompare(PyObject *v, PyObject *w, int op)
{
PyObject *a;
PyObject *b;
PyObject *context;
uint32_t status = 0;
int a_issnan, b_issnan;
int r;
assert(PyDec_Check(v));
CURRENT_CONTEXT(context);
CONVERT_BINOP_CMP(&a, &b, v, w, op, context);
a_issnan = mpd_issnan(MPD(a));
b_issnan = mpd_issnan(MPD(b));
r = mpd_qcmp(MPD(a), MPD(b), &status);
Py_DECREF(a);
Py_DECREF(b);
if (r == INT_MAX) {
/* sNaNs or op={le,ge,lt,gt} always signal. */
if (a_issnan || b_issnan || (op != Py_EQ && op != Py_NE)) {
if (dec_addstatus(context, status)) {
return NULL;
}
}
/* qNaN comparison with op={eq,ne} or comparison
* with InvalidOperation disabled. */
return (op == Py_NE) ? incr_true() : incr_false();
}
switch (op) {
case Py_EQ:
r = (r == 0);
break;
case Py_NE:
r = (r != 0);
break;
case Py_LE:
r = (r <= 0);
break;
case Py_GE:
r = (r >= 0);
break;
case Py_LT:
r = (r == -1);
break;
case Py_GT:
r = (r == 1);
break;
}
return PyBool_FromLong(r);
}
/* __ceil__ */
static PyObject *
dec_ceil(PyObject *self, PyObject *dummy)
{
PyObject *context;
CURRENT_CONTEXT(context);
return dec_as_long(self, context, MPD_ROUND_CEILING);
}
/* __complex__ */
static PyObject *
dec_complex(PyObject *self, PyObject *dummy)
{
PyObject *f;
double x;
f = PyDec_AsFloat(self);
if (f == NULL) {
return NULL;
}
x = PyFloat_AsDouble(f);
Py_DECREF(f);
if (x == -1.0 && PyErr_Occurred()) {
return NULL;
}
return PyComplex_FromDoubles(x, 0);
}
/* __copy__ and __deepcopy__ */
static PyObject *
dec_copy(PyObject *self, PyObject *dummy)
{
Py_INCREF(self);
return self;
}
/* __floor__ */
static PyObject *
dec_floor(PyObject *self, PyObject *dummy)
{
PyObject *context;
CURRENT_CONTEXT(context);
return dec_as_long(self, context, MPD_ROUND_FLOOR);
}
/* Always uses the module context */
static Py_hash_t
_dec_hash(PyDecObject *v)
{
/* 2**61 - 1 */
mpd_uint_t p_data[1] = {2305843009213693951ULL};
mpd_t p = {MPD_POS|MPD_STATIC|MPD_CONST_DATA, 0, 19, 1, 1, p_data};
/* Inverse of 10 modulo p */
mpd_uint_t inv10_p_data[1] = {2075258708292324556ULL};
mpd_t inv10_p = {MPD_POS|MPD_STATIC|MPD_CONST_DATA,
0, 19, 1, 1, inv10_p_data};
const Py_hash_t py_hash_inf = 314159;
const Py_hash_t py_hash_nan = 0;
mpd_uint_t ten_data[1] = {10};
mpd_t ten = {MPD_POS|MPD_STATIC|MPD_CONST_DATA,
0, 2, 1, 1, ten_data};
Py_hash_t result;
mpd_t *exp_hash = NULL;
mpd_t *tmp = NULL;
mpd_ssize_t exp;
uint32_t status = 0;
mpd_context_t maxctx;
PyObject *context;
context = current_context();
if (context == NULL) {
return -1;
}
if (mpd_isspecial(MPD(v))) {
if (mpd_issnan(MPD(v))) {
PyErr_SetString(PyExc_TypeError,
"Cannot hash a signaling NaN value");
return -1;
}
else if (mpd_isnan(MPD(v))) {
return py_hash_nan;
}
else {
return py_hash_inf * mpd_arith_sign(MPD(v));
}
}
mpd_maxcontext(&maxctx);
exp_hash = mpd_qnew();
if (exp_hash == NULL) {
goto malloc_error;
}
tmp = mpd_qnew();
if (tmp == NULL) {
goto malloc_error;
}
/*
* exp(v): exponent of v
* int(v): coefficient of v
*/
exp = MPD(v)->exp;
if (exp >= 0) {
/* 10**exp(v) % p */
mpd_qsset_ssize(tmp, exp, &maxctx, &status);
mpd_qpowmod(exp_hash, &ten, tmp, &p, &maxctx, &status);
}
else {
/* inv10_p**(-exp(v)) % p */
mpd_qsset_ssize(tmp, -exp, &maxctx, &status);
mpd_qpowmod(exp_hash, &inv10_p, tmp, &p, &maxctx, &status);
}
/* hash = (int(v) * exp_hash) % p */
if (!mpd_qcopy(tmp, MPD(v), &status)) {
goto malloc_error;
}
tmp->exp = 0;
mpd_set_positive(tmp);
maxctx.prec = MPD_MAX_PREC + 21;
maxctx.emax = MPD_MAX_EMAX + 21;
maxctx.emin = MPD_MIN_EMIN - 21;
mpd_qmul(tmp, tmp, exp_hash, &maxctx, &status);
mpd_qrem(tmp, tmp, &p, &maxctx, &status);
result = mpd_qget_ssize(tmp, &status);
result = mpd_ispositive(MPD(v)) ? result : -result;
result = (result == -1) ? -2 : result;
if (status != 0) {
if (status & MPD_Malloc_error) {
goto malloc_error;
}
else {
PyErr_SetString(PyExc_RuntimeError, /* GCOV_NOT_REACHED */
"dec_hash: internal error: please report"); /* GCOV_NOT_REACHED */
}
result = -1; /* GCOV_NOT_REACHED */
}
finish:
if (exp_hash) mpd_del(exp_hash);
if (tmp) mpd_del(tmp);
return result;
malloc_error:
PyErr_NoMemory();
result = -1;
goto finish;
}
static Py_hash_t
dec_hash(PyDecObject *self)
{
if (self->hash == -1) {
self->hash = _dec_hash(self);
}
return self->hash;
}
/* __reduce__ */
static PyObject *
dec_reduce(PyObject *self, PyObject *dummy)
{
PyObject *result, *str;
str = dec_str(self);
if (str == NULL) {
return NULL;
}
result = Py_BuildValue("O(O)", Py_TYPE(self), str);
Py_DECREF(str);
return result;
}
/* __sizeof__ */
static PyObject *
dec_sizeof(PyObject *v, PyObject *dummy)
{
Py_ssize_t res;
res = _PyObject_SIZE(Py_TYPE(v));
if (mpd_isdynamic_data(MPD(v))) {
res += MPD(v)->alloc * sizeof(mpd_uint_t);
}
return PyLong_FromSsize_t(res);
}
/* __trunc__ */
static PyObject *
dec_trunc(PyObject *self, PyObject *dummy)
{
PyObject *context;
CURRENT_CONTEXT(context);
return dec_as_long(self, context, MPD_ROUND_DOWN);
}
/* real and imag */
static PyObject *
dec_real(PyObject *self, void *closure)
{
Py_INCREF(self);
return self;
}
static PyObject *
dec_imag(PyObject *self, void *closure)
{
PyObject *result;
result = dec_alloc();
if (result == NULL) {
return NULL;
}
_dec_settriple(result, MPD_POS, 0, 0);
return result;
}
static PyGetSetDef dec_getsets [] =
{
{ "real", (getter)dec_real, NULL, NULL, NULL},
{ "imag", (getter)dec_imag, NULL, NULL, NULL},
{NULL}
};
static PyNumberMethods dec_number_methods =
{
(binaryfunc) nm_mpd_qadd,
(binaryfunc) nm_mpd_qsub,
(binaryfunc) nm_mpd_qmul,
(binaryfunc) nm_mpd_qrem,
(binaryfunc) nm_mpd_qdivmod,
(ternaryfunc) nm_mpd_qpow,
(unaryfunc) nm_mpd_qminus,
(unaryfunc) nm_mpd_qplus,
(unaryfunc) nm_mpd_qabs,
(inquiry) nm_nonzero,
(unaryfunc) 0, /* no bit-complement */
(binaryfunc) 0, /* no shiftl */
(binaryfunc) 0, /* no shiftr */
(binaryfunc) 0, /* no bit-and */
(binaryfunc) 0, /* no bit-xor */
(binaryfunc) 0, /* no bit-ior */
(unaryfunc) nm_dec_as_long,
0, /* nb_reserved */
(unaryfunc) PyDec_AsFloat,
0, /* binaryfunc nb_inplace_add; */
0, /* binaryfunc nb_inplace_subtract; */
0, /* binaryfunc nb_inplace_multiply; */
0, /* binaryfunc nb_inplace_remainder; */
0, /* ternaryfunc nb_inplace_power; */
0, /* binaryfunc nb_inplace_lshift; */
0, /* binaryfunc nb_inplace_rshift; */
0, /* binaryfunc nb_inplace_and; */
0, /* binaryfunc nb_inplace_xor; */
0, /* binaryfunc nb_inplace_or; */
(binaryfunc) nm_mpd_qdivint, /* binaryfunc nb_floor_divide; */
(binaryfunc) nm_mpd_qdiv, /* binaryfunc nb_true_divide; */
0, /* binaryfunc nb_inplace_floor_divide; */
0, /* binaryfunc nb_inplace_true_divide; */
};
static PyMethodDef dec_methods [] =
{
/* Unary arithmetic functions, optional context arg */
{ "exp", (PyCFunction)dec_mpd_qexp, METH_VARARGS|METH_KEYWORDS, doc_exp },
{ "ln", (PyCFunction)dec_mpd_qln, METH_VARARGS|METH_KEYWORDS, doc_ln },
{ "log10", (PyCFunction)dec_mpd_qlog10, METH_VARARGS|METH_KEYWORDS, doc_log10 },
{ "next_minus", (PyCFunction)dec_mpd_qnext_minus, METH_VARARGS|METH_KEYWORDS, doc_next_minus },
{ "next_plus", (PyCFunction)dec_mpd_qnext_plus, METH_VARARGS|METH_KEYWORDS, doc_next_plus },
{ "normalize", (PyCFunction)dec_mpd_qreduce, METH_VARARGS|METH_KEYWORDS, doc_normalize },
{ "to_integral", (PyCFunction)PyDec_ToIntegralValue, METH_VARARGS|METH_KEYWORDS, doc_to_integral },
{ "to_integral_exact", (PyCFunction)PyDec_ToIntegralExact, METH_VARARGS|METH_KEYWORDS, doc_to_integral_exact },
{ "to_integral_value", (PyCFunction)PyDec_ToIntegralValue, METH_VARARGS|METH_KEYWORDS, doc_to_integral_value },
{ "sqrt", (PyCFunction)dec_mpd_qsqrt, METH_VARARGS|METH_KEYWORDS, doc_sqrt },
/* Binary arithmetic functions, optional context arg */
{ "compare", (PyCFunction)dec_mpd_qcompare, METH_VARARGS|METH_KEYWORDS, doc_compare },
{ "compare_signal", (PyCFunction)dec_mpd_qcompare_signal, METH_VARARGS|METH_KEYWORDS, doc_compare_signal },
{ "max", (PyCFunction)dec_mpd_qmax, METH_VARARGS|METH_KEYWORDS, doc_max },
{ "max_mag", (PyCFunction)dec_mpd_qmax_mag, METH_VARARGS|METH_KEYWORDS, doc_max_mag },
{ "min", (PyCFunction)dec_mpd_qmin, METH_VARARGS|METH_KEYWORDS, doc_min },
{ "min_mag", (PyCFunction)dec_mpd_qmin_mag, METH_VARARGS|METH_KEYWORDS, doc_min_mag },
{ "next_toward", (PyCFunction)dec_mpd_qnext_toward, METH_VARARGS|METH_KEYWORDS, doc_next_toward },
{ "quantize", (PyCFunction)dec_mpd_qquantize, METH_VARARGS|METH_KEYWORDS, doc_quantize },
{ "remainder_near", (PyCFunction)dec_mpd_qrem_near, METH_VARARGS|METH_KEYWORDS, doc_remainder_near },
/* Ternary arithmetic functions, optional context arg */
{ "fma", (PyCFunction)dec_mpd_qfma, METH_VARARGS|METH_KEYWORDS, doc_fma },
/* Boolean functions, no context arg */
{ "is_canonical", dec_mpd_iscanonical, METH_NOARGS, doc_is_canonical },
{ "is_finite", dec_mpd_isfinite, METH_NOARGS, doc_is_finite },
{ "is_infinite", dec_mpd_isinfinite, METH_NOARGS, doc_is_infinite },
{ "is_nan", dec_mpd_isnan, METH_NOARGS, doc_is_nan },
{ "is_qnan", dec_mpd_isqnan, METH_NOARGS, doc_is_qnan },
{ "is_snan", dec_mpd_issnan, METH_NOARGS, doc_is_snan },
{ "is_signed", dec_mpd_issigned, METH_NOARGS, doc_is_signed },
{ "is_zero", dec_mpd_iszero, METH_NOARGS, doc_is_zero },
/* Boolean functions, optional context arg */
{ "is_normal", (PyCFunction)dec_mpd_isnormal, METH_VARARGS|METH_KEYWORDS, doc_is_normal },
{ "is_subnormal", (PyCFunction)dec_mpd_issubnormal, METH_VARARGS|METH_KEYWORDS, doc_is_subnormal },
/* Unary functions, no context arg */
{ "adjusted", dec_mpd_adjexp, METH_NOARGS, doc_adjusted },
{ "canonical", dec_canonical, METH_NOARGS, doc_canonical },
{ "conjugate", dec_conjugate, METH_NOARGS, doc_conjugate },
{ "radix", dec_mpd_radix, METH_NOARGS, doc_radix },
/* Unary functions, optional context arg for conversion errors */
{ "copy_abs", dec_mpd_qcopy_abs, METH_NOARGS, doc_copy_abs },
{ "copy_negate", dec_mpd_qcopy_negate, METH_NOARGS, doc_copy_negate },
/* Unary functions, optional context arg */
{ "logb", (PyCFunction)dec_mpd_qlogb, METH_VARARGS|METH_KEYWORDS, doc_logb },
{ "logical_invert", (PyCFunction)dec_mpd_qinvert, METH_VARARGS|METH_KEYWORDS, doc_logical_invert },
{ "number_class", (PyCFunction)dec_mpd_class, METH_VARARGS|METH_KEYWORDS, doc_number_class },
{ "to_eng_string", (PyCFunction)dec_mpd_to_eng, METH_VARARGS|METH_KEYWORDS, doc_to_eng_string },
/* Binary functions, optional context arg for conversion errors */
{ "compare_total", (PyCFunction)dec_mpd_compare_total, METH_VARARGS|METH_KEYWORDS, doc_compare_total },
{ "compare_total_mag", (PyCFunction)dec_mpd_compare_total_mag, METH_VARARGS|METH_KEYWORDS, doc_compare_total_mag },
{ "copy_sign", (PyCFunction)dec_mpd_qcopy_sign, METH_VARARGS|METH_KEYWORDS, doc_copy_sign },
{ "same_quantum", (PyCFunction)dec_mpd_same_quantum, METH_VARARGS|METH_KEYWORDS, doc_same_quantum },
/* Binary functions, optional context arg */
{ "logical_and", (PyCFunction)dec_mpd_qand, METH_VARARGS|METH_KEYWORDS, doc_logical_and },
{ "logical_or", (PyCFunction)dec_mpd_qor, METH_VARARGS|METH_KEYWORDS, doc_logical_or },
{ "logical_xor", (PyCFunction)dec_mpd_qxor, METH_VARARGS|METH_KEYWORDS, doc_logical_xor },
{ "rotate", (PyCFunction)dec_mpd_qrotate, METH_VARARGS|METH_KEYWORDS, doc_rotate },
{ "scaleb", (PyCFunction)dec_mpd_qscaleb, METH_VARARGS|METH_KEYWORDS, doc_scaleb },
{ "shift", (PyCFunction)dec_mpd_qshift, METH_VARARGS|METH_KEYWORDS, doc_shift },
/* Miscellaneous */
{ "from_float", dec_from_float, METH_O|METH_CLASS, doc_from_float },
{ "as_tuple", PyDec_AsTuple, METH_NOARGS, doc_as_tuple },
{ "as_integer_ratio", dec_as_integer_ratio, METH_NOARGS, doc_as_integer_ratio },
/* Special methods */
{ "__copy__", dec_copy, METH_NOARGS, NULL },
{ "__deepcopy__", dec_copy, METH_O, NULL },
{ "__format__", dec_format, METH_VARARGS, NULL },
{ "__reduce__", dec_reduce, METH_NOARGS, NULL },
{ "__round__", PyDec_Round, METH_VARARGS, NULL },
{ "__ceil__", dec_ceil, METH_NOARGS, NULL },
{ "__floor__", dec_floor, METH_NOARGS, NULL },
{ "__trunc__", dec_trunc, METH_NOARGS, NULL },
{ "__complex__", dec_complex, METH_NOARGS, NULL },
{ "__sizeof__", dec_sizeof, METH_NOARGS, NULL },
{ NULL, NULL, 1 }
};
static PyTypeObject PyDec_Type =
{
PyVarObject_HEAD_INIT(NULL, 0)
"decimal.Decimal", /* tp_name */
sizeof(PyDecObject), /* tp_basicsize */
0, /* tp_itemsize */
(destructor) dec_dealloc, /* tp_dealloc */
0, /* tp_print */
(getattrfunc) 0, /* tp_getattr */
(setattrfunc) 0, /* tp_setattr */
0, /* tp_reserved */
(reprfunc) dec_repr, /* tp_repr */
&dec_number_methods, /* tp_as_number */
0, /* tp_as_sequence */
0, /* tp_as_mapping */
(hashfunc) dec_hash, /* tp_hash */
0, /* tp_call */
(reprfunc) dec_str, /* tp_str */
(getattrofunc) PyObject_GenericGetAttr, /* tp_getattro */
(setattrofunc) 0, /* tp_setattro */
(PyBufferProcs *) 0, /* tp_as_buffer */
(Py_TPFLAGS_DEFAULT|
Py_TPFLAGS_BASETYPE), /* tp_flags */
doc_decimal, /* tp_doc */
0, /* tp_traverse */
0, /* tp_clear */
dec_richcompare, /* tp_richcompare */
0, /* tp_weaklistoffset */
0, /* tp_iter */
0, /* tp_iternext */
dec_methods, /* tp_methods */
0, /* tp_members */
dec_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 */
dec_new, /* tp_new */
PyObject_Del, /* tp_free */
};
/******************************************************************************/
/* Context Object, Part 2 */
/******************************************************************************/
/************************************************************************/
/* Macros for converting mpdecimal functions to Context methods */
/************************************************************************/
/* Boolean context method. */
#define DecCtx_BoolFunc(MPDFUNC) \
static PyObject * \
ctx_##MPDFUNC(PyObject *context, PyObject *v) \
{ \
PyObject *ret; \
PyObject *a; \
CONVERT_OP_RAISE(&a, v, context); \
ret = MPDFUNC(MPD(a), CTX(context)) ? incr_true() : incr_false(); \
Py_DECREF(a); \
return ret; \
}
static PyObject *
_DecCtx_BoolFunc_NO_CTX(PyObject *context, PyObject *v,
int mpdfunc(const mpd_t *))
{
PyObject *ret;
PyObject *a;
CONVERT_OP_RAISE(&a, v, context);
ret = mpdfunc(MPD(a)) ? incr_true() : incr_false();
Py_DECREF(a);
return ret;
}
/* Boolean context method. MPDFUNC does NOT use a context. */
#define DecCtx_BoolFunc_NO_CTX(MPDFUNC) \
static PyObject * \
ctx_##MPDFUNC(PyObject *context, PyObject *v) \
{ \
return _DecCtx_BoolFunc_NO_CTX(context, v, MPDFUNC); \
}
static PyObject *
_DecCtx_UnaryFunc(PyObject *context, PyObject *v,
void mpdfunc(mpd_t *, const mpd_t *, const mpd_context_t *,
uint32_t *))
{
PyObject *result, *a;
uint32_t status = 0;
CONVERT_OP_RAISE(&a, v, context);
if ((result = dec_alloc()) == NULL) {
Py_DECREF(a);
return NULL;
}
mpdfunc(MPD(result), MPD(a), CTX(context), &status);
Py_DECREF(a);
if (dec_addstatus(context, status)) {
Py_DECREF(result);
return NULL;
}
return result;
}
/* Unary context method. */
#define DecCtx_UnaryFunc(MPDFUNC) \
static PyObject * \
ctx_##MPDFUNC(PyObject *context, PyObject *v) \
{ \
return _DecCtx_UnaryFunc(context, v, MPDFUNC); \
}
static PyObject *
_DecCtx_BinaryFunc(PyObject *context, PyObject *args,
void mpdfunc(mpd_t *, const mpd_t *, const mpd_t *,
const mpd_context_t *, uint32_t *))
{
PyObject *v, *w;
PyObject *a, *b;
PyObject *result;
uint32_t status = 0;
if (!PyArg_ParseTuple(args, "OO", &v, &w)) {
return NULL;
}
CONVERT_BINOP_RAISE(&a, &b, v, w, context);
if ((result = dec_alloc()) == NULL) {
Py_DECREF(a);
Py_DECREF(b);
return NULL;
}
mpdfunc(MPD(result), MPD(a), MPD(b), CTX(context), &status);
Py_DECREF(a);
Py_DECREF(b);
if (dec_addstatus(context, status)) {
Py_DECREF(result);
return NULL;
}
return result;
}
/* Binary context method. */
#define DecCtx_BinaryFunc(MPDFUNC) \
static PyObject * \
ctx_##MPDFUNC(PyObject *context, PyObject *args) \
{ \
return _DecCtx_BinaryFunc(context, args, (void *)MPDFUNC); \
}
/*
* Binary context method. The context is only used for conversion.
* The actual MPDFUNC does NOT take a context arg.
*/
#define DecCtx_BinaryFunc_NO_CTX(MPDFUNC) \
static PyObject * \
ctx_##MPDFUNC(PyObject *context, PyObject *args) \
{ \
PyObject *v, *w; \
PyObject *a, *b; \
PyObject *result; \
\
if (!PyArg_ParseTuple(args, "OO", &v, &w)) { \
return NULL; \
} \
\
CONVERT_BINOP_RAISE(&a, &b, v, w, context); \
\
if ((result = dec_alloc()) == NULL) { \
Py_DECREF(a); \
Py_DECREF(b); \
return NULL; \
} \
\
MPDFUNC(MPD(result), MPD(a), MPD(b)); \
Py_DECREF(a); \
Py_DECREF(b); \
\
return result; \
}
/* Ternary context method. */
#define DecCtx_TernaryFunc(MPDFUNC) \
static PyObject * \
ctx_##MPDFUNC(PyObject *context, PyObject *args) \
{ \
PyObject *v, *w, *x; \
PyObject *a, *b, *c; \
PyObject *result; \
uint32_t status = 0; \
\
if (!PyArg_ParseTuple(args, "OOO", &v, &w, &x)) { \
return NULL; \
} \
\
CONVERT_TERNOP_RAISE(&a, &b, &c, v, w, x, context); \
\
if ((result = dec_alloc()) == NULL) { \
Py_DECREF(a); \
Py_DECREF(b); \
Py_DECREF(c); \
return NULL; \
} \
\
MPDFUNC(MPD(result), MPD(a), MPD(b), MPD(c), CTX(context), &status); \
Py_DECREF(a); \
Py_DECREF(b); \
Py_DECREF(c); \
if (dec_addstatus(context, status)) { \
Py_DECREF(result); \
return NULL; \
} \
\
return result; \
}
/* Unary arithmetic functions */
DecCtx_UnaryFunc(mpd_qabs)
DecCtx_UnaryFunc(mpd_qexp)
DecCtx_UnaryFunc(mpd_qln)
DecCtx_UnaryFunc(mpd_qlog10)
DecCtx_UnaryFunc(mpd_qminus)
DecCtx_UnaryFunc(mpd_qnext_minus)
DecCtx_UnaryFunc(mpd_qnext_plus)
DecCtx_UnaryFunc(mpd_qplus)
DecCtx_UnaryFunc(mpd_qreduce)
DecCtx_UnaryFunc(mpd_qround_to_int)
DecCtx_UnaryFunc(mpd_qround_to_intx)
DecCtx_UnaryFunc(mpd_qsqrt)
/* Binary arithmetic functions */
DecCtx_BinaryFunc(mpd_qadd)
DecCtx_BinaryFunc(mpd_qcompare)
DecCtx_BinaryFunc(mpd_qcompare_signal)
DecCtx_BinaryFunc(mpd_qdiv)
DecCtx_BinaryFunc(mpd_qdivint)
DecCtx_BinaryFunc(mpd_qmax)
DecCtx_BinaryFunc(mpd_qmax_mag)
DecCtx_BinaryFunc(mpd_qmin)
DecCtx_BinaryFunc(mpd_qmin_mag)
DecCtx_BinaryFunc(mpd_qmul)
DecCtx_BinaryFunc(mpd_qnext_toward)
DecCtx_BinaryFunc(mpd_qquantize)
DecCtx_BinaryFunc(mpd_qrem)
DecCtx_BinaryFunc(mpd_qrem_near)
DecCtx_BinaryFunc(mpd_qsub)
static PyObject *
ctx_mpd_qdivmod(PyObject *context, PyObject *args)
{
PyObject *v, *w;
PyObject *a, *b;
PyObject *q, *r;
uint32_t status = 0;
PyObject *ret;
if (!PyArg_ParseTuple(args, "OO", &v, &w)) {
return NULL;
}
CONVERT_BINOP_RAISE(&a, &b, v, w, context);
q = dec_alloc();
if (q == NULL) {
Py_DECREF(a);
Py_DECREF(b);
return NULL;
}
r = dec_alloc();
if (r == NULL) {
Py_DECREF(a);
Py_DECREF(b);
Py_DECREF(q);
return NULL;
}
mpd_qdivmod(MPD(q), MPD(r), MPD(a), MPD(b), CTX(context), &status);
Py_DECREF(a);
Py_DECREF(b);
if (dec_addstatus(context, status)) {
Py_DECREF(r);
Py_DECREF(q);
return NULL;
}
ret = Py_BuildValue("(OO)", q, r);
Py_DECREF(r);
Py_DECREF(q);
return ret;
}
/* Binary or ternary arithmetic functions */
static PyObject *
ctx_mpd_qpow(PyObject *context, PyObject *args, PyObject *kwds)
{
static char *kwlist[] = {"a", "b", "modulo", NULL};
PyObject *base, *exp, *mod = Py_None;
PyObject *a, *b, *c = NULL;
PyObject *result;
uint32_t status = 0;
if (!PyArg_ParseTupleAndKeywords(args, kwds, "OO|O", kwlist,
&base, &exp, &mod)) {
return NULL;
}
CONVERT_BINOP_RAISE(&a, &b, base, exp, context);
if (mod != Py_None) {
if (!convert_op(TYPE_ERR, &c, mod, context)) {
Py_DECREF(a);
Py_DECREF(b);
return c;
}
}
result = dec_alloc();
if (result == NULL) {
Py_DECREF(a);
Py_DECREF(b);
Py_XDECREF(c);
return NULL;
}
if (c == NULL) {
mpd_qpow(MPD(result), MPD(a), MPD(b),
CTX(context), &status);
}
else {
mpd_qpowmod(MPD(result), MPD(a), MPD(b), MPD(c),
CTX(context), &status);
Py_DECREF(c);
}
Py_DECREF(a);
Py_DECREF(b);
if (dec_addstatus(context, status)) {
Py_DECREF(result);
return NULL;
}
return result;
}
/* Ternary arithmetic functions */
DecCtx_TernaryFunc(mpd_qfma)
/* No argument */
static PyObject *
ctx_mpd_radix(PyObject *context, PyObject *dummy)
{
return dec_mpd_radix(context, dummy);
}
/* Boolean functions: single decimal argument */
DecCtx_BoolFunc(mpd_isnormal)
DecCtx_BoolFunc(mpd_issubnormal)
DecCtx_BoolFunc_NO_CTX(mpd_isfinite)
DecCtx_BoolFunc_NO_CTX(mpd_isinfinite)
DecCtx_BoolFunc_NO_CTX(mpd_isnan)
DecCtx_BoolFunc_NO_CTX(mpd_isqnan)
DecCtx_BoolFunc_NO_CTX(mpd_issigned)
DecCtx_BoolFunc_NO_CTX(mpd_issnan)
DecCtx_BoolFunc_NO_CTX(mpd_iszero)
static PyObject *
ctx_iscanonical(PyObject *context, PyObject *v)
{
if (!PyDec_Check(v)) {
PyErr_SetString(PyExc_TypeError,
"argument must be a Decimal");
return NULL;
}
return mpd_iscanonical(MPD(v)) ? incr_true() : incr_false();
}
/* Functions with a single decimal argument */
static PyObject *
PyDecContext_Apply(PyObject *context, PyObject *v)
{
PyObject *result, *a;
CONVERT_OP_RAISE(&a, v, context);
result = dec_apply(a, context);
Py_DECREF(a);
return result;
}
static PyObject *
ctx_canonical(PyObject *context, PyObject *v)
{
if (!PyDec_Check(v)) {
PyErr_SetString(PyExc_TypeError,
"argument must be a Decimal");
return NULL;
}
Py_INCREF(v);
return v;
}
static PyObject *
ctx_mpd_qcopy_abs(PyObject *context, PyObject *v)
{
PyObject *result, *a;
uint32_t status = 0;
CONVERT_OP_RAISE(&a, v, context);
result = dec_alloc();
if (result == NULL) {
Py_DECREF(a);
return NULL;
}
mpd_qcopy_abs(MPD(result), MPD(a), &status);
Py_DECREF(a);
if (dec_addstatus(context, status)) {
Py_DECREF(result);
return NULL;
}
return result;
}
static PyObject *
ctx_copy_decimal(PyObject *context, PyObject *v)
{
PyObject *result;
CONVERT_OP_RAISE(&result, v, context);
return result;
}
static PyObject *
ctx_mpd_qcopy_negate(PyObject *context, PyObject *v)
{
PyObject *result, *a;
uint32_t status = 0;
CONVERT_OP_RAISE(&a, v, context);
result = dec_alloc();
if (result == NULL) {
Py_DECREF(a);
return NULL;
}
mpd_qcopy_negate(MPD(result), MPD(a), &status);
Py_DECREF(a);
if (dec_addstatus(context, status)) {
Py_DECREF(result);
return NULL;
}
return result;
}
DecCtx_UnaryFunc(mpd_qlogb)
DecCtx_UnaryFunc(mpd_qinvert)
static PyObject *
ctx_mpd_class(PyObject *context, PyObject *v)
{
PyObject *a;
const char *cp;
CONVERT_OP_RAISE(&a, v, context);
cp = mpd_class(MPD(a), CTX(context));
Py_DECREF(a);
return PyUnicode_FromString(cp);
}
static PyObject *
ctx_mpd_to_sci(PyObject *context, PyObject *v)
{
PyObject *result;
PyObject *a;
mpd_ssize_t size;
char *s;
CONVERT_OP_RAISE(&a, v, context);
size = mpd_to_sci_size(&s, MPD(a), CtxCaps(context));
Py_DECREF(a);
if (size < 0) {
PyErr_NoMemory();
return NULL;
}
result = unicode_fromascii(s, size);
mpd_free(s);
return result;
}
static PyObject *
ctx_mpd_to_eng(PyObject *context, PyObject *v)
{
PyObject *result;
PyObject *a;
mpd_ssize_t size;
char *s;
CONVERT_OP_RAISE(&a, v, context);
size = mpd_to_eng_size(&s, MPD(a), CtxCaps(context));
Py_DECREF(a);
if (size < 0) {
PyErr_NoMemory();
return NULL;
}
result = unicode_fromascii(s, size);
mpd_free(s);
return result;
}
/* Functions with two decimal arguments */
DecCtx_BinaryFunc_NO_CTX(mpd_compare_total)
DecCtx_BinaryFunc_NO_CTX(mpd_compare_total_mag)
static PyObject *
ctx_mpd_qcopy_sign(PyObject *context, PyObject *args)
{
PyObject *v, *w;
PyObject *a, *b;
PyObject *result;
uint32_t status = 0;
if (!PyArg_ParseTuple(args, "OO", &v, &w)) {
return NULL;
}
CONVERT_BINOP_RAISE(&a, &b, v, w, context);
result = dec_alloc();
if (result == NULL) {
Py_DECREF(a);
Py_DECREF(b);
return NULL;
}
mpd_qcopy_sign(MPD(result), MPD(a), MPD(b), &status);
Py_DECREF(a);
Py_DECREF(b);
if (dec_addstatus(context, status)) {
Py_DECREF(result);
return NULL;
}
return result;
}
DecCtx_BinaryFunc(mpd_qand)
DecCtx_BinaryFunc(mpd_qor)
DecCtx_BinaryFunc(mpd_qxor)
DecCtx_BinaryFunc(mpd_qrotate)
DecCtx_BinaryFunc(mpd_qscaleb)
DecCtx_BinaryFunc(mpd_qshift)
static PyObject *
ctx_mpd_same_quantum(PyObject *context, PyObject *args)
{
PyObject *v, *w;
PyObject *a, *b;
PyObject *result;
if (!PyArg_ParseTuple(args, "OO", &v, &w)) {
return NULL;
}
CONVERT_BINOP_RAISE(&a, &b, v, w, context);
result = mpd_same_quantum(MPD(a), MPD(b)) ? incr_true() : incr_false();
Py_DECREF(a);
Py_DECREF(b);
return result;
}
static PyMethodDef context_methods [] =
{
/* Unary arithmetic functions */
{ "abs", ctx_mpd_qabs, METH_O, doc_ctx_abs },
{ "exp", ctx_mpd_qexp, METH_O, doc_ctx_exp },
{ "ln", ctx_mpd_qln, METH_O, doc_ctx_ln },
{ "log10", ctx_mpd_qlog10, METH_O, doc_ctx_log10 },
{ "minus", ctx_mpd_qminus, METH_O, doc_ctx_minus },
{ "next_minus", ctx_mpd_qnext_minus, METH_O, doc_ctx_next_minus },
{ "next_plus", ctx_mpd_qnext_plus, METH_O, doc_ctx_next_plus },
{ "normalize", ctx_mpd_qreduce, METH_O, doc_ctx_normalize },
{ "plus", ctx_mpd_qplus, METH_O, doc_ctx_plus },
{ "to_integral", ctx_mpd_qround_to_int, METH_O, doc_ctx_to_integral },
{ "to_integral_exact", ctx_mpd_qround_to_intx, METH_O, doc_ctx_to_integral_exact },
{ "to_integral_value", ctx_mpd_qround_to_int, METH_O, doc_ctx_to_integral_value },
{ "sqrt", ctx_mpd_qsqrt, METH_O, doc_ctx_sqrt },
/* Binary arithmetic functions */
{ "add", ctx_mpd_qadd, METH_VARARGS, doc_ctx_add },
{ "compare", ctx_mpd_qcompare, METH_VARARGS, doc_ctx_compare },
{ "compare_signal", ctx_mpd_qcompare_signal, METH_VARARGS, doc_ctx_compare_signal },
{ "divide", ctx_mpd_qdiv, METH_VARARGS, doc_ctx_divide },
{ "divide_int", ctx_mpd_qdivint, METH_VARARGS, doc_ctx_divide_int },
{ "divmod", ctx_mpd_qdivmod, METH_VARARGS, doc_ctx_divmod },
{ "max", ctx_mpd_qmax, METH_VARARGS, doc_ctx_max },
{ "max_mag", ctx_mpd_qmax_mag, METH_VARARGS, doc_ctx_max_mag },
{ "min", ctx_mpd_qmin, METH_VARARGS, doc_ctx_min },
{ "min_mag", ctx_mpd_qmin_mag, METH_VARARGS, doc_ctx_min_mag },
{ "multiply", ctx_mpd_qmul, METH_VARARGS, doc_ctx_multiply },
{ "next_toward", ctx_mpd_qnext_toward, METH_VARARGS, doc_ctx_next_toward },
{ "quantize", ctx_mpd_qquantize, METH_VARARGS, doc_ctx_quantize },
{ "remainder", ctx_mpd_qrem, METH_VARARGS, doc_ctx_remainder },
{ "remainder_near", ctx_mpd_qrem_near, METH_VARARGS, doc_ctx_remainder_near },
{ "subtract", ctx_mpd_qsub, METH_VARARGS, doc_ctx_subtract },
/* Binary or ternary arithmetic functions */
{ "power", (PyCFunction)ctx_mpd_qpow, METH_VARARGS|METH_KEYWORDS, doc_ctx_power },
/* Ternary arithmetic functions */
{ "fma", ctx_mpd_qfma, METH_VARARGS, doc_ctx_fma },
/* No argument */
{ "Etiny", context_getetiny, METH_NOARGS, doc_ctx_Etiny },
{ "Etop", context_getetop, METH_NOARGS, doc_ctx_Etop },
{ "radix", ctx_mpd_radix, METH_NOARGS, doc_ctx_radix },
/* Boolean functions */
{ "is_canonical", ctx_iscanonical, METH_O, doc_ctx_is_canonical },
{ "is_finite", ctx_mpd_isfinite, METH_O, doc_ctx_is_finite },
{ "is_infinite", ctx_mpd_isinfinite, METH_O, doc_ctx_is_infinite },
{ "is_nan", ctx_mpd_isnan, METH_O, doc_ctx_is_nan },
{ "is_normal", ctx_mpd_isnormal, METH_O, doc_ctx_is_normal },
{ "is_qnan", ctx_mpd_isqnan, METH_O, doc_ctx_is_qnan },
{ "is_signed", ctx_mpd_issigned, METH_O, doc_ctx_is_signed },
{ "is_snan", ctx_mpd_issnan, METH_O, doc_ctx_is_snan },
{ "is_subnormal", ctx_mpd_issubnormal, METH_O, doc_ctx_is_subnormal },
{ "is_zero", ctx_mpd_iszero, METH_O, doc_ctx_is_zero },
/* Functions with a single decimal argument */
{ "_apply", PyDecContext_Apply, METH_O, NULL }, /* alias for apply */
#ifdef EXTRA_FUNCTIONALITY
{ "apply", PyDecContext_Apply, METH_O, doc_ctx_apply },
#endif
{ "canonical", ctx_canonical, METH_O, doc_ctx_canonical },
{ "copy_abs", ctx_mpd_qcopy_abs, METH_O, doc_ctx_copy_abs },
{ "copy_decimal", ctx_copy_decimal, METH_O, doc_ctx_copy_decimal },
{ "copy_negate", ctx_mpd_qcopy_negate, METH_O, doc_ctx_copy_negate },
{ "logb", ctx_mpd_qlogb, METH_O, doc_ctx_logb },
{ "logical_invert", ctx_mpd_qinvert, METH_O, doc_ctx_logical_invert },
{ "number_class", ctx_mpd_class, METH_O, doc_ctx_number_class },
{ "to_sci_string", ctx_mpd_to_sci, METH_O, doc_ctx_to_sci_string },
{ "to_eng_string", ctx_mpd_to_eng, METH_O, doc_ctx_to_eng_string },
/* Functions with two decimal arguments */
{ "compare_total", ctx_mpd_compare_total, METH_VARARGS, doc_ctx_compare_total },
{ "compare_total_mag", ctx_mpd_compare_total_mag, METH_VARARGS, doc_ctx_compare_total_mag },
{ "copy_sign", ctx_mpd_qcopy_sign, METH_VARARGS, doc_ctx_copy_sign },
{ "logical_and", ctx_mpd_qand, METH_VARARGS, doc_ctx_logical_and },
{ "logical_or", ctx_mpd_qor, METH_VARARGS, doc_ctx_logical_or },
{ "logical_xor", ctx_mpd_qxor, METH_VARARGS, doc_ctx_logical_xor },
{ "rotate", ctx_mpd_qrotate, METH_VARARGS, doc_ctx_rotate },
{ "same_quantum", ctx_mpd_same_quantum, METH_VARARGS, doc_ctx_same_quantum },
{ "scaleb", ctx_mpd_qscaleb, METH_VARARGS, doc_ctx_scaleb },
{ "shift", ctx_mpd_qshift, METH_VARARGS, doc_ctx_shift },
/* Set context values */
{ "clear_flags", context_clear_flags, METH_NOARGS, doc_ctx_clear_flags },
{ "clear_traps", context_clear_traps, METH_NOARGS, doc_ctx_clear_traps },
/* Miscellaneous */
{ "__copy__", (PyCFunction)context_copy, METH_NOARGS, NULL },
{ "__reduce__", context_reduce, METH_NOARGS, NULL },
{ "copy", (PyCFunction)context_copy, METH_NOARGS, doc_ctx_copy },
{ "create_decimal", ctx_create_decimal, METH_VARARGS, doc_ctx_create_decimal },
{ "create_decimal_from_float", ctx_from_float, METH_O, doc_ctx_create_decimal_from_float },
{ NULL, NULL, 1 }
};
static PyTypeObject PyDecContext_Type =
{
PyVarObject_HEAD_INIT(NULL, 0)
"decimal.Context", /* tp_name */
sizeof(PyDecContextObject), /* tp_basicsize */
0, /* tp_itemsize */
(destructor) context_dealloc, /* tp_dealloc */
0, /* tp_print */
(getattrfunc) 0, /* tp_getattr */
(setattrfunc) 0, /* tp_setattr */
0, /* tp_reserved */
(reprfunc) context_repr, /* tp_repr */
0, /* tp_as_number */
0, /* tp_as_sequence */
0, /* tp_as_mapping */
(hashfunc) 0, /* tp_hash */
0, /* tp_call */
(reprfunc) context_repr, /* tp_str */
(getattrofunc) context_getattr, /* tp_getattro */
(setattrofunc) context_setattr, /* tp_setattro */
(PyBufferProcs *) 0, /* tp_as_buffer */
Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE, /* tp_flags */
doc_context, /* tp_doc */
0, /* tp_traverse */
0, /* tp_clear */
0, /* tp_richcompare */
0, /* tp_weaklistoffset */
0, /* tp_iter */
0, /* tp_iternext */
context_methods, /* tp_methods */
0, /* tp_members */
context_getsets, /* tp_getset */
0, /* tp_base */
0, /* tp_dict */
0, /* tp_descr_get */
0, /* tp_descr_set */
0, /* tp_dictoffset */
context_init, /* tp_init */
0, /* tp_alloc */
context_new, /* tp_new */
PyObject_Del, /* tp_free */
};
static PyMethodDef _decimal_methods [] =
{
{ "getcontext", (PyCFunction)PyDec_GetCurrentContext, METH_NOARGS, doc_getcontext},
{ "setcontext", (PyCFunction)PyDec_SetCurrentContext, METH_O, doc_setcontext},
{ "localcontext", (PyCFunction)ctxmanager_new, METH_VARARGS|METH_KEYWORDS, doc_localcontext},
#ifdef EXTRA_FUNCTIONALITY
{ "IEEEContext", (PyCFunction)ieee_context, METH_O, doc_ieee_context},
#endif
{ NULL, NULL, 1, NULL }
};
static struct PyModuleDef _decimal_module = {
PyModuleDef_HEAD_INIT,
"decimal",
doc__decimal,
-1,
_decimal_methods,
NULL,
NULL,
NULL,
NULL
};
struct ssize_constmap { const char *name; mpd_ssize_t val; };
static struct ssize_constmap ssize_constants [] = {
{"MAX_PREC", MPD_MAX_PREC},
{"MAX_EMAX", MPD_MAX_EMAX},
{"MIN_EMIN", MPD_MIN_EMIN},
{"MIN_ETINY", MPD_MIN_ETINY},
{NULL}
};
struct int_constmap { const char *name; int val; };
static struct int_constmap int_constants [] = {
/* int constants */
#ifdef EXTRA_FUNCTIONALITY
{"DECIMAL32", MPD_DECIMAL32},
{"DECIMAL64", MPD_DECIMAL64},
{"DECIMAL128", MPD_DECIMAL128},
{"IEEE_CONTEXT_MAX_BITS", MPD_IEEE_CONTEXT_MAX_BITS},
/* int condition flags */
{"DecClamped", MPD_Clamped},
{"DecConversionSyntax", MPD_Conversion_syntax},
{"DecDivisionByZero", MPD_Division_by_zero},
{"DecDivisionImpossible", MPD_Division_impossible},
{"DecDivisionUndefined", MPD_Division_undefined},
{"DecFpuError", MPD_Fpu_error},
{"DecInexact", MPD_Inexact},
{"DecInvalidContext", MPD_Invalid_context},
{"DecInvalidOperation", MPD_Invalid_operation},
{"DecIEEEInvalidOperation", MPD_IEEE_Invalid_operation},
{"DecMallocError", MPD_Malloc_error},
{"DecFloatOperation", MPD_Float_operation},
{"DecOverflow", MPD_Overflow},
{"DecRounded", MPD_Rounded},
{"DecSubnormal", MPD_Subnormal},
{"DecUnderflow", MPD_Underflow},
{"DecErrors", MPD_Errors},
{"DecTraps", MPD_Traps},
#endif
{NULL}
};
#define CHECK_INT(expr) \
do { if ((expr) < 0) goto error; } while (0)
#define ASSIGN_PTR(result, expr) \
do { result = (expr); if (result == NULL) goto error; } while (0)
#define CHECK_PTR(expr) \
do { if ((expr) == NULL) goto error; } while (0)
static PyCFunction
cfunc_noargs(PyTypeObject *t, const char *name)
{
struct PyMethodDef *m;
if (t->tp_methods == NULL) {
goto error;
}
for (m = t->tp_methods; m->ml_name != NULL; m++) {
if (strcmp(name, m->ml_name) == 0) {
if (!(m->ml_flags & METH_NOARGS)) {
goto error;
}
return m->ml_meth;
}
}
error:
PyErr_Format(PyExc_RuntimeError,
"internal error: could not find method %s", name);
return NULL;
}
PyMODINIT_FUNC
PyInit__decimal(void)
{
PyObject *m = NULL;
PyObject *numbers = NULL;
PyObject *Number = NULL;
PyObject *collections = NULL;
PyObject *MutableMapping = NULL;
PyObject *obj = NULL;
DecCondMap *cm;
struct ssize_constmap *ssize_cm;
struct int_constmap *int_cm;
int i;
/* Init libmpdec */
mpd_traphandler = dec_traphandler;
mpd_mallocfunc = PyMem_Malloc;
mpd_reallocfunc = PyMem_Realloc;
mpd_callocfunc = mpd_callocfunc_em;
mpd_free = PyMem_Free;
mpd_setminalloc(_Py_DEC_MINALLOC);
/* Init external C-API functions */
_py_long_multiply = PyLong_Type.tp_as_number->nb_multiply;
_py_long_floor_divide = PyLong_Type.tp_as_number->nb_floor_divide;
_py_long_power = PyLong_Type.tp_as_number->nb_power;
_py_float_abs = PyFloat_Type.tp_as_number->nb_absolute;
ASSIGN_PTR(_py_float_as_integer_ratio, cfunc_noargs(&PyFloat_Type,
"as_integer_ratio"));
ASSIGN_PTR(_py_long_bit_length, cfunc_noargs(&PyLong_Type, "bit_length"));
/* Init types */
PyDec_Type.tp_base = &PyBaseObject_Type;
PyDecContext_Type.tp_base = &PyBaseObject_Type;
PyDecContextManager_Type.tp_base = &PyBaseObject_Type;
PyDecSignalDictMixin_Type.tp_base = &PyBaseObject_Type;
CHECK_INT(PyType_Ready(&PyDec_Type));
CHECK_INT(PyType_Ready(&PyDecContext_Type));
CHECK_INT(PyType_Ready(&PyDecSignalDictMixin_Type));
CHECK_INT(PyType_Ready(&PyDecContextManager_Type));
ASSIGN_PTR(obj, PyUnicode_FromString("decimal"));
CHECK_INT(PyDict_SetItemString(PyDec_Type.tp_dict, "__module__", obj));
CHECK_INT(PyDict_SetItemString(PyDecContext_Type.tp_dict,
"__module__", obj));
Py_CLEAR(obj);
/* Numeric abstract base classes */
ASSIGN_PTR(numbers, PyImport_ImportModule("numbers"));
ASSIGN_PTR(Number, PyObject_GetAttrString(numbers, "Number"));
/* Register Decimal with the Number abstract base class */
ASSIGN_PTR(obj, PyObject_CallMethod(Number, "register", "(O)",
(PyObject *)&PyDec_Type));
Py_CLEAR(obj);
/* Rational is a global variable used for fraction comparisons. */
ASSIGN_PTR(Rational, PyObject_GetAttrString(numbers, "Rational"));
/* Done with numbers, Number */
Py_CLEAR(numbers);
Py_CLEAR(Number);
/* DecimalTuple */
ASSIGN_PTR(collections, PyImport_ImportModule("collections"));
ASSIGN_PTR(DecimalTuple, (PyTypeObject *)PyObject_CallMethod(collections,
"namedtuple", "(ss)", "DecimalTuple",
"sign digits exponent"));
ASSIGN_PTR(obj, PyUnicode_FromString("decimal"));
CHECK_INT(PyDict_SetItemString(DecimalTuple->tp_dict, "__module__", obj));
Py_CLEAR(obj);
/* MutableMapping */
ASSIGN_PTR(MutableMapping, PyObject_GetAttrString(collections,
"MutableMapping"));
/* Create SignalDict type */
ASSIGN_PTR(PyDecSignalDict_Type,
(PyTypeObject *)PyObject_CallFunction(
(PyObject *)&PyType_Type, "s(OO){}",
"SignalDict", &PyDecSignalDictMixin_Type,
MutableMapping));
/* Done with collections, MutableMapping */
Py_CLEAR(collections);
Py_CLEAR(MutableMapping);
/* Create the module */
ASSIGN_PTR(m, PyModule_Create(&_decimal_module));
/* Add types to the module */
Py_INCREF(&PyDec_Type);
CHECK_INT(PyModule_AddObject(m, "Decimal", (PyObject *)&PyDec_Type));
Py_INCREF(&PyDecContext_Type);
CHECK_INT(PyModule_AddObject(m, "Context",
(PyObject *)&PyDecContext_Type));
Py_INCREF(DecimalTuple);
CHECK_INT(PyModule_AddObject(m, "DecimalTuple", (PyObject *)DecimalTuple));
/* Create top level exception */
ASSIGN_PTR(DecimalException, PyErr_NewException(
"decimal.DecimalException",
PyExc_ArithmeticError, NULL));
Py_INCREF(DecimalException);
CHECK_INT(PyModule_AddObject(m, "DecimalException", DecimalException));
/* Create signal tuple */
ASSIGN_PTR(SignalTuple, PyTuple_New(SIGNAL_MAP_LEN));
/* Add exceptions that correspond to IEEE signals */
for (i = SIGNAL_MAP_LEN-1; i >= 0; i--) {
PyObject *base;
cm = signal_map + i;
switch (cm->flag) {
case MPD_Float_operation:
base = PyTuple_Pack(2, DecimalException, PyExc_TypeError);
break;
case MPD_Division_by_zero:
base = PyTuple_Pack(2, DecimalException, PyExc_ZeroDivisionError);
break;
case MPD_Overflow:
base = PyTuple_Pack(2, signal_map[INEXACT].ex,
signal_map[ROUNDED].ex);
break;
case MPD_Underflow:
base = PyTuple_Pack(3, signal_map[INEXACT].ex,
signal_map[ROUNDED].ex,
signal_map[SUBNORMAL].ex);
break;
default:
base = PyTuple_Pack(1, DecimalException);
break;
}
if (base == NULL) {
goto error; /* GCOV_NOT_REACHED */
}
ASSIGN_PTR(cm->ex, PyErr_NewException(cm->fqname, base, NULL));
Py_DECREF(base);
/* add to module */
Py_INCREF(cm->ex);
CHECK_INT(PyModule_AddObject(m, cm->name, cm->ex));
/* add to signal tuple */
Py_INCREF(cm->ex);
PyTuple_SET_ITEM(SignalTuple, i, cm->ex);
}
/*
* Unfortunately, InvalidOperation is a signal that comprises
* several conditions, including InvalidOperation! Naming the
* signal IEEEInvalidOperation would prevent the confusion.
*/
cond_map[0].ex = signal_map[0].ex;
/* Add remaining exceptions, inherit from InvalidOperation */
for (cm = cond_map+1; cm->name != NULL; cm++) {
PyObject *base;
if (cm->flag == MPD_Division_undefined) {
base = PyTuple_Pack(2, signal_map[0].ex, PyExc_ZeroDivisionError);
}
else {
base = PyTuple_Pack(1, signal_map[0].ex);
}
if (base == NULL) {
goto error; /* GCOV_NOT_REACHED */
}
ASSIGN_PTR(cm->ex, PyErr_NewException(cm->fqname, base, NULL));
Py_DECREF(base);
Py_INCREF(cm->ex);
CHECK_INT(PyModule_AddObject(m, cm->name, cm->ex));
}
/* Init default context template first */
ASSIGN_PTR(default_context_template,
PyObject_CallObject((PyObject *)&PyDecContext_Type, NULL));
Py_INCREF(default_context_template);
CHECK_INT(PyModule_AddObject(m, "DefaultContext",
default_context_template));
#ifdef WITHOUT_THREADS
/* Init module context */
ASSIGN_PTR(module_context,
PyObject_CallObject((PyObject *)&PyDecContext_Type, NULL));
Py_INCREF(Py_False);
CHECK_INT(PyModule_AddObject(m, "HAVE_THREADS", Py_False));
#else
ASSIGN_PTR(tls_context_key, PyUnicode_FromString("___DECIMAL_CTX__"));
Py_INCREF(Py_True);
CHECK_INT(PyModule_AddObject(m, "HAVE_THREADS", Py_True));
#endif
/* Init basic context template */
ASSIGN_PTR(basic_context_template,
PyObject_CallObject((PyObject *)&PyDecContext_Type, NULL));
init_basic_context(basic_context_template);
Py_INCREF(basic_context_template);
CHECK_INT(PyModule_AddObject(m, "BasicContext",
basic_context_template));
/* Init extended context template */
ASSIGN_PTR(extended_context_template,
PyObject_CallObject((PyObject *)&PyDecContext_Type, NULL));
init_extended_context(extended_context_template);
Py_INCREF(extended_context_template);
CHECK_INT(PyModule_AddObject(m, "ExtendedContext",
extended_context_template));
/* Init mpd_ssize_t constants */
for (ssize_cm = ssize_constants; ssize_cm->name != NULL; ssize_cm++) {
ASSIGN_PTR(obj, PyLong_FromSsize_t(ssize_cm->val));
CHECK_INT(PyModule_AddObject(m, ssize_cm->name, obj));
obj = NULL;
}
/* Init int constants */
for (int_cm = int_constants; int_cm->name != NULL; int_cm++) {
CHECK_INT(PyModule_AddIntConstant(m, int_cm->name,
int_cm->val));
}
/* Init string constants */
for (i = 0; i < _PY_DEC_ROUND_GUARD; i++) {
ASSIGN_PTR(round_map[i], PyUnicode_InternFromString(mpd_round_string[i]));
Py_INCREF(round_map[i]);
CHECK_INT(PyModule_AddObject(m, mpd_round_string[i], round_map[i]));
}
/* Add specification version number */
CHECK_INT(PyModule_AddStringConstant(m, "__version__", "1.70"));
CHECK_INT(PyModule_AddStringConstant(m, "__libmpdec_version__", mpd_version()));
return m;
error:
Py_CLEAR(obj); /* GCOV_NOT_REACHED */
Py_CLEAR(numbers); /* GCOV_NOT_REACHED */
Py_CLEAR(Number); /* GCOV_NOT_REACHED */
Py_CLEAR(Rational); /* GCOV_NOT_REACHED */
Py_CLEAR(collections); /* GCOV_NOT_REACHED */
Py_CLEAR(MutableMapping); /* GCOV_NOT_REACHED */
Py_CLEAR(SignalTuple); /* GCOV_NOT_REACHED */
Py_CLEAR(DecimalTuple); /* GCOV_NOT_REACHED */
#ifdef WITHOUT_THREADS
Py_CLEAR(module_context); /* GCOV_NOT_REACHED */
#else
Py_CLEAR(default_context_template); /* GCOV_NOT_REACHED */
Py_CLEAR(tls_context_key); /* GCOV_NOT_REACHED */
#endif
Py_CLEAR(basic_context_template); /* GCOV_NOT_REACHED */
Py_CLEAR(extended_context_template); /* GCOV_NOT_REACHED */
Py_CLEAR(m); /* GCOV_NOT_REACHED */
return NULL; /* GCOV_NOT_REACHED */
}
_Section(".rodata.pytab.1") const struct _inittab _PyImport_Inittab__decimal = {
"_decimal",
PyInit__decimal,
};
| 173,190 | 5,955 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Modules/_decimal/libmpdec/sixstep.h | #ifndef SIX_STEP_H
#define SIX_STEP_H
#include "third_party/python/Modules/_decimal/libmpdec/mpdecimal.h"
/* clang-format off */
/* Internal header file: all symbols have local scope in the DSO */
int six_step_fnt(mpd_uint_t *a, mpd_size_t n, int modnum);
int inv_six_step_fnt(mpd_uint_t *a, mpd_size_t n, int modnum);
#endif
| 330 | 13 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Modules/_decimal/libmpdec/README.txt |
libmpdec
========
libmpdec is a fast C/C++ library for correctly-rounded arbitrary precision
decimal floating point arithmetic. It is a complete implementation of
Mike Cowlishaw/IBM's General Decimal Arithmetic Specification.
Files required for the Python _decimal module
=============================================
Core files for small and medium precision arithmetic
----------------------------------------------------
basearith.{c,h} -> Core arithmetic in base 10**9 or 10**19.
bits.h -> Portable detection of least/most significant one-bit.
constants.{c,h} -> Constants that are used in multiple files.
context.c -> Context functions.
io.{c,h} -> Conversions between mpd_t and ASCII strings,
mpd_t formatting (allows UTF-8 fill character).
memory.{c,h} -> Allocation handlers with overflow detection
and functions for switching between static
and dynamic mpd_t.
mpdecimal.{c,h} -> All (quiet) functions of the specification.
typearith.h -> Fast primitives for double word multiplication,
division etc.
Visual Studio only:
~~~~~~~~~~~~~~~~~~~
vccompat.h -> snprintf <==> sprintf_s and similar things.
vcstdint.h -> stdint.h (included in VS 2010 but not in VS 2008).
vcdiv64.asm -> Double word division used in typearith.h. VS 2008 does
not allow inline asm for x64. Also, it does not provide
an intrinsic for double word division.
Files for bignum arithmetic:
----------------------------
The following files implement the Fast Number Theoretic Transform
used for multiplying coefficients with more than 1024 words (see
mpdecimal.c: _mpd_fntmul()).
umodarith.h -> Fast low level routines for unsigned modular arithmetic.
numbertheory.{c,h} -> Routines for setting up the Number Theoretic Transform.
difradix2.{c,h} -> Decimation in frequency transform, used as the
"base case" by the following three files:
fnt.{c,h} -> Transform arrays up to 4096 words.
sixstep.{c,h} -> Transform larger arrays of length 2**n.
fourstep.{c,h} -> Transform larger arrays of length 3 * 2**n.
convolute.{c,h} -> Fast convolution using one of the three transform
functions.
transpose.{c,h} -> Transpositions needed for the sixstep algorithm.
crt.{c,h} -> Chinese Remainder Theorem: use information from three
transforms modulo three different primes to get the
final result.
Pointers to literature, proofs and more
=======================================
literature/
-----------
REFERENCES.txt -> List of relevant papers.
bignum.txt -> Explanation of the Fast Number Theoretic Transform (FNT).
fnt.py -> Verify constants used in the FNT; Python demo for the
O(N**2) discrete transform.
matrix-transform.txt -> Proof for the Matrix Fourier Transform used in
fourstep.c.
six-step.txt -> Show that the algorithm used in sixstep.c is
a variant of the Matrix Fourier Transform.
mulmod-64.txt -> Proof for the mulmod64 algorithm from
umodarith.h.
mulmod-ppro.txt -> Proof for the x87 FPU modular multiplication
from umodarith.h.
umodarith.lisp -> ACL2 proofs for many functions from umodarith.h.
Library Author
==============
Stefan Krah <[email protected]>
| 3,785 | 91 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Modules/_decimal/libmpdec/sixstep.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:8;coding:utf-8 -*-â
âvi: set net ft=c ts=4 sts=4 sw=4 fenc=utf-8 :viâ
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ¡
â Copyright (c) 2008-2016 Stefan Krah. All rights reserved. â
â â
â Redistribution and use in source and binary forms, with or without â
â modification, are permitted provided that the following conditions â
â are met: â
â â
â 1. Redistributions of source code must retain the above copyright â
â notice, this list of conditions and the following disclaimer. â
â â
â 2. Redistributions in binary form must reproduce the above copyright â
â notice, this list of conditions and the following disclaimer in â
â the documentation and/or other materials provided with the â
â distribution. â
â â
â THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS "AS IS" AND â
â ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE â
â IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR â
â PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS â
â BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, â
â OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT â
â OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR â
â BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, â
â WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE â
â OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, â
â EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
#include "third_party/python/Modules/_decimal/libmpdec/bits.h"
#include "third_party/python/Modules/_decimal/libmpdec/difradix2.h"
#include "third_party/python/Modules/_decimal/libmpdec/mpdecimal.h"
#include "third_party/python/Modules/_decimal/libmpdec/numbertheory.h"
#include "third_party/python/Modules/_decimal/libmpdec/sixstep.h"
#include "third_party/python/Modules/_decimal/libmpdec/transpose.h"
#include "third_party/python/Modules/_decimal/libmpdec/umodarith.h"
/* clang-format off */
asm(".ident\t\"\\n\\n\
libmpdec (BSD-2)\\n\
Copyright 2008-2016 Stefan Krah\"");
asm(".include \"libc/disclaimer.inc\"");
/*
Cache Efficient Matrix Fourier Transform
for arrays of form 2â¿
The Six Step Transform
ââââââââââââââââââââââ
In libmpdec, the six-step transform is the Matrix Fourier Transform in
disguise. It is called six-step transform after a variant that appears
in [1]. The algorithm requires that the input array can be viewed as an
RÃC matrix.
Algorithm six-step (forward transform)
ââââââââââââââââââââââââââââââââââââââ
1a) Transpose the matrix.
1b) Apply a length R FNT to each row.
1c) Transpose the matrix.
2) Multiply each matrix element (addressed by jÃC+m) by r**(jÃm).
3) Apply a length C FNT to each row.
4) Transpose the matrix.
Note that steps 1a) - 1c) are exactly equivalent to step 1) of the Matrix
Fourier Transform. For large R, it is faster to transpose twice and do
a transform on the rows than to perform a column transpose directly.
Algorithm six-step (inverse transform)
ââââââââââââââââââââââââââââââââââââââ
0) View the matrix as a CÃR matrix.
1) Transpose the matrix, producing an RÃC matrix.
2) Apply a length C FNT to each row.
3) Multiply each matrix element (addressed by iÃC+n) by r**(iÃn).
4a) Transpose the matrix.
4b) Apply a length R FNT to each row.
4c) Transpose the matrix.
Again, steps 4a) - 4c) are equivalent to step 4) of the Matrix Fourier
Transform.
ââ
[1] David H. Bailey: FFTs in External or Hierarchical Memory
http://crd.lbl.gov/~dhbailey/dhbpapers/
*/
/* forward transform with sign = -1 */
int
six_step_fnt(mpd_uint_t *a, mpd_size_t n, int modnum)
{
struct fnt_params *tparams;
mpd_size_t log2n, C, R;
mpd_uint_t kernel;
mpd_uint_t umod;
mpd_uint_t *x, w0, w1, wstep;
mpd_size_t i, k;
assert(ispower2(n));
assert(n >= 16);
assert(n <= MPD_MAXTRANSFORM_2N);
log2n = mpd_bsr(n);
C = ((mpd_size_t)1) << (log2n / 2); /* number of columns */
R = ((mpd_size_t)1) << (log2n - (log2n / 2)); /* number of rows */
/* Transpose the matrix. */
if (!transpose_pow2(a, R, C)) {
return 0;
}
/* Length R transform on the rows. */
if ((tparams = _mpd_init_fnt_params(R, -1, modnum)) == NULL) {
return 0;
}
for (x = a; x < a+n; x += R) {
fnt_dif2(x, R, tparams);
}
/* Transpose the matrix. */
if (!transpose_pow2(a, C, R)) {
mpd_free(tparams);
return 0;
}
/* Multiply each matrix element (addressed by i*C+k) by r**(i*k). */
SETMODULUS(modnum);
kernel = _mpd_getkernel(n, -1, modnum);
for (i = 1; i < R; i++) {
w0 = 1; /* r**(i*0): initial value for k=0 */
w1 = POWMOD(kernel, i); /* r**(i*1): initial value for k=1 */
wstep = MULMOD(w1, w1); /* r**(2*i) */
for (k = 0; k < C; k += 2) {
mpd_uint_t x0 = a[i*C+k];
mpd_uint_t x1 = a[i*C+k+1];
MULMOD2(&x0, w0, &x1, w1);
MULMOD2C(&w0, &w1, wstep); /* r**(i*(k+2)) = r**(i*k) * r**(2*i) */
a[i*C+k] = x0;
a[i*C+k+1] = x1;
}
}
/* Length C transform on the rows. */
if (C != R) {
mpd_free(tparams);
if ((tparams = _mpd_init_fnt_params(C, -1, modnum)) == NULL) {
return 0;
}
}
for (x = a; x < a+n; x += C) {
fnt_dif2(x, C, tparams);
}
mpd_free(tparams);
#if 0
/* An unordered transform is sufficient for convolution. */
/* Transpose the matrix. */
if (!transpose_pow2(a, R, C)) {
return 0;
}
#endif
return 1;
}
/* reverse transform, sign = 1 */
int
inv_six_step_fnt(mpd_uint_t *a, mpd_size_t n, int modnum)
{
struct fnt_params *tparams;
mpd_size_t log2n, C, R;
mpd_uint_t kernel;
mpd_uint_t umod;
mpd_uint_t *x, w0, w1, wstep;
mpd_size_t i, k;
assert(ispower2(n));
assert(n >= 16);
assert(n <= MPD_MAXTRANSFORM_2N);
log2n = mpd_bsr(n);
C = ((mpd_size_t)1) << (log2n / 2); /* number of columns */
R = ((mpd_size_t)1) << (log2n - (log2n / 2)); /* number of rows */
#if 0
/* An unordered transform is sufficient for convolution. */
/* Transpose the matrix, producing an R*C matrix. */
if (!transpose_pow2(a, C, R)) {
return 0;
}
#endif
/* Length C transform on the rows. */
if ((tparams = _mpd_init_fnt_params(C, 1, modnum)) == NULL) {
return 0;
}
for (x = a; x < a+n; x += C) {
fnt_dif2(x, C, tparams);
}
/* Multiply each matrix element (addressed by i*C+k) by r**(i*k). */
SETMODULUS(modnum);
kernel = _mpd_getkernel(n, 1, modnum);
for (i = 1; i < R; i++) {
w0 = 1;
w1 = POWMOD(kernel, i);
wstep = MULMOD(w1, w1);
for (k = 0; k < C; k += 2) {
mpd_uint_t x0 = a[i*C+k];
mpd_uint_t x1 = a[i*C+k+1];
MULMOD2(&x0, w0, &x1, w1);
MULMOD2C(&w0, &w1, wstep);
a[i*C+k] = x0;
a[i*C+k+1] = x1;
}
}
/* Transpose the matrix. */
if (!transpose_pow2(a, R, C)) {
mpd_free(tparams);
return 0;
}
/* Length R transform on the rows. */
if (R != C) {
mpd_free(tparams);
if ((tparams = _mpd_init_fnt_params(R, 1, modnum)) == NULL) {
return 0;
}
}
for (x = a; x < a+n; x += R) {
fnt_dif2(x, R, tparams);
}
mpd_free(tparams);
/* Transpose the matrix. */
if (!transpose_pow2(a, C, R)) {
return 0;
}
return 1;
}
| 9,096 | 242 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Modules/_decimal/libmpdec/fourstep.h | #ifndef FOUR_STEP_H
#define FOUR_STEP_H
#include "third_party/python/Modules/_decimal/libmpdec/mpdecimal.h"
int four_step_fnt(mpd_uint_t *, mpd_size_t, int);
int inv_four_step_fnt(mpd_uint_t *, mpd_size_t, int);
#endif
| 221 | 9 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Modules/_decimal/libmpdec/memory.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:8;coding:utf-8 -*-â
âvi: set net ft=c ts=4 sts=4 sw=4 fenc=utf-8 :viâ
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ¡
â Copyright (c) 2008-2016 Stefan Krah. All rights reserved. â
â â
â Redistribution and use in source and binary forms, with or without â
â modification, are permitted provided that the following conditions â
â are met: â
â â
â 1. Redistributions of source code must retain the above copyright â
â notice, this list of conditions and the following disclaimer. â
â â
â 2. Redistributions in binary form must reproduce the above copyright â
â notice, this list of conditions and the following disclaimer in â
â the documentation and/or other materials provided with the â
â distribution. â
â â
â THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS "AS IS" AND â
â ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE â
â IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR â
â PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS â
â BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, â
â OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT â
â OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR â
â BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, â
â WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE â
â OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, â
â EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
#include "libc/mem/mem.h"
#include "third_party/python/Modules/_decimal/libmpdec/mpalloc.h"
#include "third_party/python/Modules/_decimal/libmpdec/mpdecimal.h"
#include "third_party/python/Modules/_decimal/libmpdec/typearith.h"
/* clang-format off */
asm(".ident\t\"\\n\\n\
libmpdec (BSD-2)\\n\
Copyright 2008-2016 Stefan Krah\"");
asm(".include \"libc/disclaimer.inc\"");
/* Guaranteed minimum allocation for a coefficient. May be changed once
at program start using mpd_setminalloc(). */
mpd_ssize_t MPD_MINALLOC = MPD_MINALLOC_MIN;
/* Custom allocation and free functions */
void *(* mpd_mallocfunc)(size_t size) = malloc;
void *(* mpd_reallocfunc)(void *ptr, size_t size) = realloc;
void *(* mpd_callocfunc)(size_t nmemb, size_t size) = calloc;
void (* mpd_free)(void *ptr) = free;
/* emulate calloc if it is not available */
void *
mpd_callocfunc_em(size_t nmemb, size_t size)
{
void *ptr;
size_t req;
mpd_size_t overflow;
#if MPD_SIZE_MAX < SIZE_MAX
/* full_coverage test only */
if (nmemb > MPD_SIZE_MAX || size > MPD_SIZE_MAX) {
return NULL;
}
#endif
req = mul_size_t_overflow((mpd_size_t)nmemb, (mpd_size_t)size,
&overflow);
if (overflow) {
return NULL;
}
ptr = mpd_mallocfunc(req);
if (ptr == NULL) {
return NULL;
}
/* used on uint32_t or uint64_t */
bzero(ptr, req);
return ptr;
}
/* malloc with overflow checking */
void *
mpd_alloc(mpd_size_t nmemb, mpd_size_t size)
{
mpd_size_t req, overflow;
req = mul_size_t_overflow(nmemb, size, &overflow);
if (overflow) {
return NULL;
}
return mpd_mallocfunc(req);
}
/* calloc with overflow checking */
void *
mpd_calloc(mpd_size_t nmemb, mpd_size_t size)
{
mpd_size_t overflow;
(void)mul_size_t_overflow(nmemb, size, &overflow);
if (overflow) {
return NULL;
}
return mpd_callocfunc(nmemb, size);
}
/* realloc with overflow checking */
void *
mpd_realloc(void *ptr, mpd_size_t nmemb, mpd_size_t size, uint8_t *err)
{
void *new;
mpd_size_t req, overflow;
req = mul_size_t_overflow(nmemb, size, &overflow);
if (overflow) {
*err = 1;
return ptr;
}
new = mpd_reallocfunc(ptr, req);
if (new == NULL) {
*err = 1;
return ptr;
}
return new;
}
/* struct hack malloc with overflow checking */
void *
mpd_sh_alloc(mpd_size_t struct_size, mpd_size_t nmemb, mpd_size_t size)
{
mpd_size_t req, overflow;
req = mul_size_t_overflow(nmemb, size, &overflow);
if (overflow) {
return NULL;
}
req = add_size_t_overflow(req, struct_size, &overflow);
if (overflow) {
return NULL;
}
return mpd_mallocfunc(req);
}
/* Allocate a new decimal with a coefficient of length 'nwords'. In case
of an error the return value is NULL. */
mpd_t *
mpd_qnew_size(mpd_ssize_t nwords)
{
mpd_t *result;
nwords = (nwords < MPD_MINALLOC) ? MPD_MINALLOC : nwords;
result = mpd_alloc(1, sizeof *result);
if (result == NULL) {
return NULL;
}
result->data = mpd_alloc(nwords, sizeof *result->data);
if (result->data == NULL) {
mpd_free(result);
return NULL;
}
result->flags = 0;
result->exp = 0;
result->digits = 0;
result->len = 0;
result->alloc = nwords;
return result;
}
/* Allocate a new decimal with a coefficient of length MPD_MINALLOC.
In case of an error the return value is NULL. */
mpd_t *
mpd_qnew(void)
{
return mpd_qnew_size(MPD_MINALLOC);
}
/* Allocate new decimal. Caller can check for NULL or MPD_Malloc_error.
Raises on error. */
mpd_t *
mpd_new(mpd_context_t *ctx)
{
mpd_t *result;
result = mpd_qnew();
if (result == NULL) {
mpd_addstatus_raise(ctx, MPD_Malloc_error);
}
return result;
}
/*
* Input: 'result' is a static mpd_t with a static coefficient.
* Assumption: 'nwords' >= result->alloc.
*
* Resize the static coefficient to a larger dynamic one and copy the
* existing data. If successful, the value of 'result' is unchanged.
* Otherwise, set 'result' to NaN and update 'status' with MPD_Malloc_error.
*/
int
mpd_switch_to_dyn(mpd_t *result, mpd_ssize_t nwords, uint32_t *status)
{
mpd_uint_t *p = result->data;
assert(nwords >= result->alloc);
result->data = mpd_alloc(nwords, sizeof *result->data);
if (result->data == NULL) {
result->data = p;
mpd_set_qnan(result);
mpd_set_positive(result);
result->exp = result->digits = result->len = 0;
*status |= MPD_Malloc_error;
return 0;
}
memcpy(result->data, p, result->alloc * (sizeof *result->data));
result->alloc = nwords;
mpd_set_dynamic_data(result);
return 1;
}
/*
* Input: 'result' is a static mpd_t with a static coefficient.
*
* Convert the coefficient to a dynamic one that is initialized to zero. If
* malloc fails, set 'result' to NaN and update 'status' with MPD_Malloc_error.
*/
int
mpd_switch_to_dyn_zero(mpd_t *result, mpd_ssize_t nwords, uint32_t *status)
{
mpd_uint_t *p = result->data;
result->data = mpd_calloc(nwords, sizeof *result->data);
if (result->data == NULL) {
result->data = p;
mpd_set_qnan(result);
mpd_set_positive(result);
result->exp = result->digits = result->len = 0;
*status |= MPD_Malloc_error;
return 0;
}
result->alloc = nwords;
mpd_set_dynamic_data(result);
return 1;
}
/*
* Input: 'result' is a static or a dynamic mpd_t with a dynamic coefficient.
* Resize the coefficient to length 'nwords':
* Case nwords > result->alloc:
* If realloc is successful:
* 'result' has a larger coefficient but the same value. Return 1.
* Otherwise:
* Set 'result' to NaN, update status with MPD_Malloc_error and return 0.
* Case nwords < result->alloc:
* If realloc is successful:
* 'result' has a smaller coefficient. result->len is undefined. Return 1.
* Otherwise (unlikely):
* 'result' is unchanged. Reuse the now oversized coefficient. Return 1.
*/
int
mpd_realloc_dyn(mpd_t *result, mpd_ssize_t nwords, uint32_t *status)
{
uint8_t err = 0;
result->data = mpd_realloc(result->data, nwords, sizeof *result->data, &err);
if (!err) {
result->alloc = nwords;
}
else if (nwords > result->alloc) {
mpd_set_qnan(result);
mpd_set_positive(result);
result->exp = result->digits = result->len = 0;
*status |= MPD_Malloc_error;
return 0;
}
return 1;
}
| 9,381 | 296 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Modules/_decimal/libmpdec/basearith.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:8;coding:utf-8 -*-â
âvi: set net ft=c ts=4 sts=4 sw=4 fenc=utf-8 :viâ
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ¡
â Copyright (c) 2008-2016 Stefan Krah. All rights reserved. â
â â
â Redistribution and use in source and binary forms, with or without â
â modification, are permitted provided that the following conditions â
â are met: â
â â
â 1. Redistributions of source code must retain the above copyright â
â notice, this list of conditions and the following disclaimer. â
â â
â 2. Redistributions in binary form must reproduce the above copyright â
â notice, this list of conditions and the following disclaimer in â
â the documentation and/or other materials provided with the â
â distribution. â
â â
â THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS "AS IS" AND â
â ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE â
â IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR â
â PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS â
â BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, â
â OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT â
â OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR â
â BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, â
â WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE â
â OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, â
â EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
#include "third_party/python/Modules/_decimal/libmpdec/basearith.h"
#include "third_party/python/Modules/_decimal/libmpdec/constants.h"
#include "third_party/python/Modules/_decimal/libmpdec/mpdecimal.h"
#include "third_party/python/Modules/_decimal/libmpdec/typearith.h"
/* clang-format off */
asm(".ident\t\"\\n\\n\
libmpdec (BSD-2)\\n\
Copyright 2008-2016 Stefan Krah\"");
asm(".include \"libc/disclaimer.inc\"");
/*********************************************************************/
/* Calculations in base MPD_RADIX */
/*********************************************************************/
/*
* Knuth, TAOCP, Volume 2, 4.3.1:
* w := sum of u (len m) and v (len n)
* n > 0 and m >= n
* The calling function has to handle a possible final carry.
*/
mpd_uint_t
_mpd_baseadd(mpd_uint_t *w, const mpd_uint_t *u, const mpd_uint_t *v,
mpd_size_t m, mpd_size_t n)
{
mpd_uint_t s;
mpd_uint_t carry = 0;
mpd_size_t i;
assert(n > 0 && m >= n);
/* add n members of u and v */
for (i = 0; i < n; i++) {
s = u[i] + (v[i] + carry);
carry = (s < u[i]) | (s >= MPD_RADIX);
w[i] = carry ? s-MPD_RADIX : s;
}
/* if there is a carry, propagate it */
for (; carry && i < m; i++) {
s = u[i] + carry;
carry = (s == MPD_RADIX);
w[i] = carry ? 0 : s;
}
/* copy the rest of u */
for (; i < m; i++) {
w[i] = u[i];
}
return carry;
}
/*
* Add the contents of u to w. Carries are propagated further. The caller
* has to make sure that w is big enough.
*/
void
_mpd_baseaddto(mpd_uint_t *w, const mpd_uint_t *u, mpd_size_t n)
{
mpd_uint_t s;
mpd_uint_t carry = 0;
mpd_size_t i;
if (n == 0) return;
/* add n members of u to w */
for (i = 0; i < n; i++) {
s = w[i] + (u[i] + carry);
carry = (s < w[i]) | (s >= MPD_RADIX);
w[i] = carry ? s-MPD_RADIX : s;
}
/* if there is a carry, propagate it */
for (; carry; i++) {
s = w[i] + carry;
carry = (s == MPD_RADIX);
w[i] = carry ? 0 : s;
}
}
/*
* Add v to w (len m). The calling function has to handle a possible
* final carry. Assumption: m > 0.
*/
mpd_uint_t
_mpd_shortadd(mpd_uint_t *w, mpd_size_t m, mpd_uint_t v)
{
mpd_uint_t s;
mpd_uint_t carry;
mpd_size_t i;
assert(m > 0);
/* add v to w */
s = w[0] + v;
carry = (s < v) | (s >= MPD_RADIX);
w[0] = carry ? s-MPD_RADIX : s;
/* if there is a carry, propagate it */
for (i = 1; carry && i < m; i++) {
s = w[i] + carry;
carry = (s == MPD_RADIX);
w[i] = carry ? 0 : s;
}
return carry;
}
/* Increment u. The calling function has to handle a possible carry. */
mpd_uint_t
_mpd_baseincr(mpd_uint_t *u, mpd_size_t n)
{
mpd_uint_t s;
mpd_uint_t carry = 1;
mpd_size_t i;
assert(n > 0);
/* if there is a carry, propagate it */
for (i = 0; carry && i < n; i++) {
s = u[i] + carry;
carry = (s == MPD_RADIX);
u[i] = carry ? 0 : s;
}
return carry;
}
/*
* Knuth, TAOCP, Volume 2, 4.3.1:
* w := difference of u (len m) and v (len n).
* number in u >= number in v;
*/
void
_mpd_basesub(mpd_uint_t *w, const mpd_uint_t *u, const mpd_uint_t *v,
mpd_size_t m, mpd_size_t n)
{
mpd_uint_t d;
mpd_uint_t borrow = 0;
mpd_size_t i;
assert(m > 0 && n > 0);
/* subtract n members of v from u */
for (i = 0; i < n; i++) {
d = u[i] - (v[i] + borrow);
borrow = (u[i] < d);
w[i] = borrow ? d + MPD_RADIX : d;
}
/* if there is a borrow, propagate it */
for (; borrow && i < m; i++) {
d = u[i] - borrow;
borrow = (u[i] == 0);
w[i] = borrow ? MPD_RADIX-1 : d;
}
/* copy the rest of u */
for (; i < m; i++) {
w[i] = u[i];
}
}
/*
* Subtract the contents of u from w. w is larger than u. Borrows are
* propagated further, but eventually w can absorb the final borrow.
*/
void
_mpd_basesubfrom(mpd_uint_t *w, const mpd_uint_t *u, mpd_size_t n)
{
mpd_uint_t d;
mpd_uint_t borrow = 0;
mpd_size_t i;
if (n == 0) return;
/* subtract n members of u from w */
for (i = 0; i < n; i++) {
d = w[i] - (u[i] + borrow);
borrow = (w[i] < d);
w[i] = borrow ? d + MPD_RADIX : d;
}
/* if there is a borrow, propagate it */
for (; borrow; i++) {
d = w[i] - borrow;
borrow = (w[i] == 0);
w[i] = borrow ? MPD_RADIX-1 : d;
}
}
/* w := product of u (len n) and v (single word) */
void
_mpd_shortmul(mpd_uint_t *w, const mpd_uint_t *u, mpd_size_t n, mpd_uint_t v)
{
mpd_uint_t hi, lo;
mpd_uint_t carry = 0;
mpd_size_t i;
assert(n > 0);
for (i=0; i < n; i++) {
_mpd_mul_words(&hi, &lo, u[i], v);
lo = carry + lo;
if (lo < carry) hi++;
_mpd_div_words_r(&carry, &w[i], hi, lo);
}
w[i] = carry;
}
/*
* Knuth, TAOCP, Volume 2, 4.3.1:
* w := product of u (len m) and v (len n)
* w must be initialized to zero
*/
void
_mpd_basemul(mpd_uint_t *w, const mpd_uint_t *u, const mpd_uint_t *v,
mpd_size_t m, mpd_size_t n)
{
mpd_uint_t hi, lo;
mpd_uint_t carry;
mpd_size_t i, j;
assert(m > 0 && n > 0);
for (j=0; j < n; j++) {
carry = 0;
for (i=0; i < m; i++) {
_mpd_mul_words(&hi, &lo, u[i], v[j]);
lo = w[i+j] + lo;
if (lo < w[i+j]) hi++;
lo = carry + lo;
if (lo < carry) hi++;
_mpd_div_words_r(&carry, &w[i+j], hi, lo);
}
w[j+m] = carry;
}
}
/*
* Knuth, TAOCP Volume 2, 4.3.1, exercise 16:
* w := quotient of u (len n) divided by a single word v
*/
mpd_uint_t
_mpd_shortdiv(mpd_uint_t *w, const mpd_uint_t *u, mpd_size_t n, mpd_uint_t v)
{
mpd_uint_t hi, lo;
mpd_uint_t rem = 0;
mpd_size_t i;
assert(n > 0);
for (i=n-1; i != MPD_SIZE_MAX; i--) {
_mpd_mul_words(&hi, &lo, rem, MPD_RADIX);
lo = u[i] + lo;
if (lo < u[i]) hi++;
_mpd_div_words(&w[i], &rem, hi, lo, v);
}
return rem;
}
/*
* Knuth, TAOCP Volume 2, 4.3.1:
* q, r := quotient and remainder of uconst (len nplusm)
* divided by vconst (len n)
* nplusm >= n
*
* If r is not NULL, r will contain the remainder. If r is NULL, the
* return value indicates if there is a remainder: 1 for true, 0 for
* false. A return value of -1 indicates an error.
*/
int
_mpd_basedivmod(mpd_uint_t *q, mpd_uint_t *r,
const mpd_uint_t *uconst, const mpd_uint_t *vconst,
mpd_size_t nplusm, mpd_size_t n)
{
mpd_uint_t ustatic[MPD_MINALLOC_MAX];
mpd_uint_t vstatic[MPD_MINALLOC_MAX];
mpd_uint_t *u = ustatic;
mpd_uint_t *v = vstatic;
mpd_uint_t d, qhat, rhat, w2[2];
mpd_uint_t hi, lo, x;
mpd_uint_t carry;
mpd_size_t i, j, m;
int retval = 0;
assert(n > 1 && nplusm >= n);
m = sub_size_t(nplusm, n);
/* D1: normalize */
d = MPD_RADIX / (vconst[n-1] + 1);
if (nplusm >= MPD_MINALLOC_MAX) {
if ((u = mpd_alloc(nplusm+1, sizeof *u)) == NULL) {
return -1;
}
}
if (n >= MPD_MINALLOC_MAX) {
if ((v = mpd_alloc(n+1, sizeof *v)) == NULL) {
mpd_free(u);
return -1;
}
}
_mpd_shortmul(u, uconst, nplusm, d);
_mpd_shortmul(v, vconst, n, d);
/* D2: loop */
for (j=m; j != MPD_SIZE_MAX; j--) {
/* D3: calculate qhat and rhat */
rhat = _mpd_shortdiv(w2, u+j+n-1, 2, v[n-1]);
qhat = w2[1] * MPD_RADIX + w2[0];
while (1) {
if (qhat < MPD_RADIX) {
_mpd_singlemul(w2, qhat, v[n-2]);
if (w2[1] <= rhat) {
if (w2[1] != rhat || w2[0] <= u[j+n-2]) {
break;
}
}
}
qhat -= 1;
rhat += v[n-1];
if (rhat < v[n-1] || rhat >= MPD_RADIX) {
break;
}
}
/* D4: multiply and subtract */
carry = 0;
for (i=0; i <= n; i++) {
_mpd_mul_words(&hi, &lo, qhat, v[i]);
lo = carry + lo;
if (lo < carry) hi++;
_mpd_div_words_r(&hi, &lo, hi, lo);
x = u[i+j] - lo;
carry = (u[i+j] < x);
u[i+j] = carry ? x+MPD_RADIX : x;
carry += hi;
}
q[j] = qhat;
/* D5: test remainder */
if (carry) {
q[j] -= 1;
/* D6: add back */
(void)_mpd_baseadd(u+j, u+j, v, n+1, n);
}
}
/* D8: unnormalize */
if (r != NULL) {
_mpd_shortdiv(r, u, n, d);
/* we are not interested in the return value here */
retval = 0;
}
else {
retval = !_mpd_isallzero(u, n);
}
if (u != ustatic) mpd_free(u);
if (v != vstatic) mpd_free(v);
return retval;
}
/*
* Left shift of src by 'shift' digits; src may equal dest.
*
* dest := area of n mpd_uint_t with space for srcdigits+shift digits.
* src := coefficient with length m.
*
* The case splits in the function are non-obvious. The following
* equations might help:
*
* Let msdigits denote the number of digits in the most significant
* word of src. Then 1 <= msdigits <= rdigits.
*
* 1) shift = q * rdigits + r
* 2) srcdigits = qsrc * rdigits + msdigits
* 3) destdigits = shift + srcdigits
* = q * rdigits + r + qsrc * rdigits + msdigits
* = q * rdigits + (qsrc * rdigits + (r + msdigits))
*
* The result has q zero words, followed by the coefficient that
* is left-shifted by r. The case r == 0 is trivial. For r > 0, it
* is important to keep in mind that we always read m source words,
* but write m+1 destination words if r + msdigits > rdigits, m words
* otherwise.
*/
void
_mpd_baseshiftl(mpd_uint_t *dest, mpd_uint_t *src, mpd_size_t n, mpd_size_t m,
mpd_size_t shift)
{
mpd_uint_t l=l, lprev=lprev, h=h; /* b/c warnings */
mpd_uint_t q, r;
mpd_uint_t ph;
assert(m > 0 && n >= m);
_mpd_div_word(&q, &r, (mpd_uint_t)shift, MPD_RDIGITS);
if (r != 0) {
ph = mpd_pow10[r];
--m; --n;
_mpd_divmod_pow10(&h, &lprev, src[m--], MPD_RDIGITS-r);
if (h != 0) { /* r + msdigits > rdigits <==> h != 0 */
dest[n--] = h;
}
/* write m-1 shifted words */
for (; m != MPD_SIZE_MAX; m--,n--) {
_mpd_divmod_pow10(&h, &l, src[m], MPD_RDIGITS-r);
dest[n] = ph * lprev + h;
lprev = l;
}
/* write least significant word */
dest[q] = ph * lprev;
}
else {
while (--m != MPD_SIZE_MAX) {
dest[m+q] = src[m];
}
}
mpd_uint_zero(dest, q);
}
/*
* Right shift of src by 'shift' digits; src may equal dest.
* Assumption: srcdigits-shift > 0.
*
* dest := area with space for srcdigits-shift digits.
* src := coefficient with length 'slen'.
*
* The case splits in the function rely on the following equations:
*
* Let msdigits denote the number of digits in the most significant
* word of src. Then 1 <= msdigits <= rdigits.
*
* 1) shift = q * rdigits + r
* 2) srcdigits = qsrc * rdigits + msdigits
* 3) destdigits = srcdigits - shift
* = qsrc * rdigits + msdigits - (q * rdigits + r)
* = (qsrc - q) * rdigits + msdigits - r
*
* Since destdigits > 0 and 1 <= msdigits <= rdigits:
*
* 4) qsrc >= q
* 5) qsrc == q ==> msdigits > r
*
* The result has slen-q words if msdigits > r, slen-q-1 words otherwise.
*/
mpd_uint_t
_mpd_baseshiftr(mpd_uint_t *dest, mpd_uint_t *src, mpd_size_t slen,
mpd_size_t shift)
{
/* spurious uninitialized warnings */
mpd_uint_t l=l, h=h, hprev=hprev; /* low, high, previous high */
mpd_uint_t rnd, rest; /* rounding digit, rest */
mpd_uint_t q, r;
mpd_size_t i, j;
mpd_uint_t ph;
assert(slen > 0);
_mpd_div_word(&q, &r, (mpd_uint_t)shift, MPD_RDIGITS);
rnd = rest = 0;
if (r != 0) {
ph = mpd_pow10[MPD_RDIGITS-r];
_mpd_divmod_pow10(&hprev, &rest, src[q], r);
_mpd_divmod_pow10(&rnd, &rest, rest, r-1);
if (rest == 0 && q > 0) {
rest = !_mpd_isallzero(src, q);
}
/* write slen-q-1 words */
for (j=0,i=q+1; i<slen; i++,j++) {
_mpd_divmod_pow10(&h, &l, src[i], r);
dest[j] = ph * l + hprev;
hprev = h;
}
/* write most significant word */
if (hprev != 0) { /* always the case if slen==q-1 */
dest[j] = hprev;
}
}
else {
if (q > 0) {
_mpd_divmod_pow10(&rnd, &rest, src[q-1], MPD_RDIGITS-1);
/* is there any non-zero digit below rnd? */
if (rest == 0) rest = !_mpd_isallzero(src, q-1);
}
for (j = 0; j < slen-q; j++) {
dest[j] = src[q+j];
}
}
/* 0-4 ==> rnd+rest < 0.5 */
/* 5 ==> rnd+rest == 0.5 */
/* 6-9 ==> rnd+rest > 0.5 */
return (rnd == 0 || rnd == 5) ? rnd + !!rest : rnd;
}
/*********************************************************************/
/* Calculations in base b */
/*********************************************************************/
/*
* Add v to w (len m). The calling function has to handle a possible
* final carry. Assumption: m > 0.
*/
mpd_uint_t
_mpd_shortadd_b(mpd_uint_t *w, mpd_size_t m, mpd_uint_t v, mpd_uint_t b)
{
mpd_uint_t s;
mpd_uint_t carry;
mpd_size_t i;
assert(m > 0);
/* add v to w */
s = w[0] + v;
carry = (s < v) | (s >= b);
w[0] = carry ? s-b : s;
/* if there is a carry, propagate it */
for (i = 1; carry && i < m; i++) {
s = w[i] + carry;
carry = (s == b);
w[i] = carry ? 0 : s;
}
return carry;
}
/* w := product of u (len n) and v (single word). Return carry. */
mpd_uint_t
_mpd_shortmul_c(mpd_uint_t *w, const mpd_uint_t *u, mpd_size_t n, mpd_uint_t v)
{
mpd_uint_t hi, lo;
mpd_uint_t carry = 0;
mpd_size_t i;
assert(n > 0);
for (i=0; i < n; i++) {
_mpd_mul_words(&hi, &lo, u[i], v);
lo = carry + lo;
if (lo < carry) hi++;
_mpd_div_words_r(&carry, &w[i], hi, lo);
}
return carry;
}
/* w := product of u (len n) and v (single word) */
mpd_uint_t
_mpd_shortmul_b(mpd_uint_t *w, const mpd_uint_t *u, mpd_size_t n,
mpd_uint_t v, mpd_uint_t b)
{
mpd_uint_t hi, lo;
mpd_uint_t carry = 0;
mpd_size_t i;
assert(n > 0);
for (i=0; i < n; i++) {
_mpd_mul_words(&hi, &lo, u[i], v);
lo = carry + lo;
if (lo < carry) hi++;
_mpd_div_words(&carry, &w[i], hi, lo, b);
}
return carry;
}
/*
* Knuth, TAOCP Volume 2, 4.3.1, exercise 16:
* w := quotient of u (len n) divided by a single word v
*/
mpd_uint_t
_mpd_shortdiv_b(mpd_uint_t *w, const mpd_uint_t *u, mpd_size_t n,
mpd_uint_t v, mpd_uint_t b)
{
mpd_uint_t hi, lo;
mpd_uint_t rem = 0;
mpd_size_t i;
assert(n > 0);
for (i=n-1; i != MPD_SIZE_MAX; i--) {
_mpd_mul_words(&hi, &lo, rem, b);
lo = u[i] + lo;
if (lo < u[i]) hi++;
_mpd_div_words(&w[i], &rem, hi, lo, v);
}
return rem;
}
| 18,274 | 571 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Modules/_decimal/libmpdec/crt.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:8;coding:utf-8 -*-â
âvi: set net ft=c ts=4 sts=4 sw=4 fenc=utf-8 :viâ
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ¡
â Copyright (c) 2008-2016 Stefan Krah. All rights reserved. â
â â
â Redistribution and use in source and binary forms, with or without â
â modification, are permitted provided that the following conditions â
â are met: â
â â
â 1. Redistributions of source code must retain the above copyright â
â notice, this list of conditions and the following disclaimer. â
â â
â 2. Redistributions in binary form must reproduce the above copyright â
â notice, this list of conditions and the following disclaimer in â
â the documentation and/or other materials provided with the â
â distribution. â
â â
â THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS "AS IS" AND â
â ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE â
â IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR â
â PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS â
â BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, â
â OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT â
â OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR â
â BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, â
â WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE â
â OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, â
â EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
#include "third_party/python/Modules/_decimal/libmpdec/crt.h"
#include "third_party/python/Modules/_decimal/libmpdec/mpdecimal.h"
#include "third_party/python/Modules/_decimal/libmpdec/numbertheory.h"
#include "third_party/python/Modules/_decimal/libmpdec/umodarith.h"
/* clang-format off */
asm(".ident\t\"\\n\\n\
libmpdec (BSD-2)\\n\
Copyright 2008-2016 Stefan Krah\"");
asm(".include \"libc/disclaimer.inc\"");
/* Bignum: Chinese Remainder Theorem, extends the maximum transform length. */
/* Multiply P1P2 by v, store result in w. */
static inline void
_crt_mulP1P2_3(mpd_uint_t w[3], mpd_uint_t v)
{
mpd_uint_t hi1, hi2, lo;
_mpd_mul_words(&hi1, &lo, LH_P1P2, v);
w[0] = lo;
_mpd_mul_words(&hi2, &lo, UH_P1P2, v);
lo = hi1 + lo;
if (lo < hi1) hi2++;
w[1] = lo;
w[2] = hi2;
}
/* Add 3 words from v to w. The result is known to fit in w. */
static inline void
_crt_add3(mpd_uint_t w[3], mpd_uint_t v[3])
{
mpd_uint_t carry;
mpd_uint_t s;
s = w[0] + v[0];
carry = (s < w[0]);
w[0] = s;
s = w[1] + (v[1] + carry);
carry = (s < w[1]);
w[1] = s;
w[2] = w[2] + (v[2] + carry);
}
/* Divide 3 words in u by v, store result in w, return remainder. */
static inline mpd_uint_t
_crt_div3(mpd_uint_t *w, const mpd_uint_t *u, mpd_uint_t v)
{
mpd_uint_t r1 = u[2];
mpd_uint_t r2;
if (r1 < v) {
w[2] = 0;
}
else {
_mpd_div_word(&w[2], &r1, u[2], v); /* GCOV_NOT_REACHED */
}
_mpd_div_words(&w[1], &r2, r1, u[1], v);
_mpd_div_words(&w[0], &r1, r2, u[0], v);
return r1;
}
/*
* Chinese Remainder Theorem:
* Algorithm from Joerg Arndt, "Matters Computational",
* Chapter 37.4.1 [http://www.jjj.de/fxt/]
*
* See also Knuth, TAOCP, Volume 2, 4.3.2, exercise 7.
*/
/*
* CRT with carry: x1, x2, x3 contain numbers modulo p1, p2, p3. For each
* triple of members of the arrays, find the unique z modulo p1*p2*p3, with
* zmax = p1*p2*p3 - 1.
*
* In each iteration of the loop, split z into result[i] = z % MPD_RADIX
* and carry = z / MPD_RADIX. Let N be the size of carry[] and cmax the
* maximum carry.
*
* Limits for the 32-bit build:
*
* N = 2**96
* cmax = 7711435591312380274
*
* Limits for the 64 bit build:
*
* N = 2**192
* cmax = 627710135393475385904124401220046371710
*
* The following statements hold for both versions:
*
* 1) cmax + zmax < N, so the addition does not overflow.
*
* 2) (cmax + zmax) / MPD_RADIX == cmax.
*
* 3) If c <= cmax, then c_next = (c + zmax) / MPD_RADIX <= cmax.
*/
void
crt3(mpd_uint_t *x1, mpd_uint_t *x2, mpd_uint_t *x3, mpd_size_t rsize)
{
mpd_uint_t p1 = mpd_moduli[P1];
mpd_uint_t umod;
mpd_uint_t a1, a2, a3;
mpd_uint_t s;
mpd_uint_t z[3], t[3];
mpd_uint_t carry[3] = {0,0,0};
mpd_uint_t hi, lo;
mpd_size_t i;
for (i = 0; i < rsize; i++) {
a1 = x1[i];
a2 = x2[i];
a3 = x3[i];
SETMODULUS(P2);
s = ext_submod(a2, a1, umod);
s = MULMOD(s, INV_P1_MOD_P2);
_mpd_mul_words(&hi, &lo, s, p1);
lo = lo + a1;
if (lo < a1) hi++;
SETMODULUS(P3);
s = dw_submod(a3, hi, lo, umod);
s = MULMOD(s, INV_P1P2_MOD_P3);
z[0] = lo;
z[1] = hi;
z[2] = 0;
_crt_mulP1P2_3(t, s);
_crt_add3(z, t);
_crt_add3(carry, z);
x1[i] = _crt_div3(carry, carry, MPD_RADIX);
}
assert(carry[0] == 0 && carry[1] == 0 && carry[2] == 0);
}
| 6,263 | 158 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Modules/_decimal/libmpdec/convolute.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:8;coding:utf-8 -*-â
âvi: set net ft=c ts=4 sts=4 sw=4 fenc=utf-8 :viâ
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ¡
â Copyright (c) 2008-2016 Stefan Krah. All rights reserved. â
â â
â Redistribution and use in source and binary forms, with or without â
â modification, are permitted provided that the following conditions â
â are met: â
â â
â 1. Redistributions of source code must retain the above copyright â
â notice, this list of conditions and the following disclaimer. â
â â
â 2. Redistributions in binary form must reproduce the above copyright â
â notice, this list of conditions and the following disclaimer in â
â the documentation and/or other materials provided with the â
â distribution. â
â â
â THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS "AS IS" AND â
â ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE â
â IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR â
â PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS â
â BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, â
â OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT â
â OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR â
â BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, â
â WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE â
â OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, â
â EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
#include "third_party/python/Modules/_decimal/libmpdec/bits.h"
#include "third_party/python/Modules/_decimal/libmpdec/constants.h"
#include "third_party/python/Modules/_decimal/libmpdec/convolute.h"
#include "third_party/python/Modules/_decimal/libmpdec/fnt.h"
#include "third_party/python/Modules/_decimal/libmpdec/fourstep.h"
#include "third_party/python/Modules/_decimal/libmpdec/mpdecimal.h"
#include "third_party/python/Modules/_decimal/libmpdec/numbertheory.h"
#include "third_party/python/Modules/_decimal/libmpdec/sixstep.h"
#include "third_party/python/Modules/_decimal/libmpdec/umodarith.h"
/* clang-format off */
asm(".ident\t\"\\n\\n\
libmpdec (BSD-2)\\n\
Copyright 2008-2016 Stefan Krah\"");
asm(".include \"libc/disclaimer.inc\"");
/* Bignum: Fast convolution using the Number Theoretic Transform.
Used for the multiplication of very large coefficients. */
/* Convolute the data in c1 and c2. Result is in c1. */
int
fnt_convolute(mpd_uint_t *c1, mpd_uint_t *c2, mpd_size_t n, int modnum)
{
int (*fnt)(mpd_uint_t *, mpd_size_t, int);
int (*inv_fnt)(mpd_uint_t *, mpd_size_t, int);
mpd_uint_t n_inv, umod;
mpd_size_t i;
SETMODULUS(modnum);
n_inv = POWMOD(n, (umod-2));
if (ispower2(n)) {
if (n > SIX_STEP_THRESHOLD) {
fnt = six_step_fnt;
inv_fnt = inv_six_step_fnt;
}
else {
fnt = std_fnt;
inv_fnt = std_inv_fnt;
}
}
else {
fnt = four_step_fnt;
inv_fnt = inv_four_step_fnt;
}
if (!fnt(c1, n, modnum)) {
return 0;
}
if (!fnt(c2, n, modnum)) {
return 0;
}
for (i = 0; i < n-1; i += 2) {
mpd_uint_t x0 = c1[i];
mpd_uint_t y0 = c2[i];
mpd_uint_t x1 = c1[i+1];
mpd_uint_t y1 = c2[i+1];
MULMOD2(&x0, y0, &x1, y1);
c1[i] = x0;
c1[i+1] = x1;
}
if (!inv_fnt(c1, n, modnum)) {
return 0;
}
for (i = 0; i < n-3; i += 4) {
mpd_uint_t x0 = c1[i];
mpd_uint_t x1 = c1[i+1];
mpd_uint_t x2 = c1[i+2];
mpd_uint_t x3 = c1[i+3];
MULMOD2C(&x0, &x1, n_inv);
MULMOD2C(&x2, &x3, n_inv);
c1[i] = x0;
c1[i+1] = x1;
c1[i+2] = x2;
c1[i+3] = x3;
}
return 1;
}
/* Autoconvolute the data in c1. Result is in c1. */
int
fnt_autoconvolute(mpd_uint_t *c1, mpd_size_t n, int modnum)
{
int (*fnt)(mpd_uint_t *, mpd_size_t, int);
int (*inv_fnt)(mpd_uint_t *, mpd_size_t, int);
mpd_uint_t n_inv, umod;
mpd_size_t i;
SETMODULUS(modnum);
n_inv = POWMOD(n, (umod-2));
if (ispower2(n)) {
if (n > SIX_STEP_THRESHOLD) {
fnt = six_step_fnt;
inv_fnt = inv_six_step_fnt;
}
else {
fnt = std_fnt;
inv_fnt = std_inv_fnt;
}
}
else {
fnt = four_step_fnt;
inv_fnt = inv_four_step_fnt;
}
if (!fnt(c1, n, modnum)) {
return 0;
}
for (i = 0; i < n-1; i += 2) {
mpd_uint_t x0 = c1[i];
mpd_uint_t x1 = c1[i+1];
MULMOD2(&x0, x0, &x1, x1);
c1[i] = x0;
c1[i+1] = x1;
}
if (!inv_fnt(c1, n, modnum)) {
return 0;
}
for (i = 0; i < n-3; i += 4) {
mpd_uint_t x0 = c1[i];
mpd_uint_t x1 = c1[i+1];
mpd_uint_t x2 = c1[i+2];
mpd_uint_t x3 = c1[i+3];
MULMOD2C(&x0, &x1, n_inv);
MULMOD2C(&x2, &x3, n_inv);
c1[i] = x0;
c1[i+1] = x1;
c1[i+2] = x2;
c1[i+3] = x3;
}
return 1;
}
| 6,341 | 159 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Modules/_decimal/libmpdec/crt.h | #ifndef CRT_H
#define CRT_H
#include "third_party/python/Modules/_decimal/libmpdec/mpdecimal.h"
/* clang-format off */
/* Internal header file: all symbols have local scope in the DSO */
void crt3(mpd_uint_t *x1, mpd_uint_t *x2, mpd_uint_t *x3, mpd_size_t nmemb);
#endif
| 275 | 12 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Modules/_decimal/libmpdec/io.h | #ifndef IO_H
#define IO_H
#include "third_party/python/Modules/_decimal/libmpdec/mpdecimal.h"
/* clang-format off */
#if SIZE_MAX == MPD_SIZE_MAX
#define mpd_strtossize _mpd_strtossize
#else
static inline mpd_ssize_t
mpd_strtossize(const char *s, char **end, int base)
{
int64_t retval;
errno = 0;
retval = _mpd_strtossize(s, end, base);
if (errno == 0 && (retval > MPD_SSIZE_MAX || retval < MPD_SSIZE_MIN)) {
errno = ERANGE;
}
if (errno == ERANGE) {
return (retval < 0) ? MPD_SSIZE_MIN : MPD_SSIZE_MAX;
}
return (mpd_ssize_t)retval;
}
#endif
#endif
| 604 | 28 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Modules/_decimal/libmpdec/io.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:8;coding:utf-8 -*-â
âvi: set net ft=c ts=4 sts=4 sw=4 fenc=utf-8 :viâ
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ¡
â Copyright (c) 2008-2016 Stefan Krah. All rights reserved. â
â â
â Redistribution and use in source and binary forms, with or without â
â modification, are permitted provided that the following conditions â
â are met: â
â â
â 1. Redistributions of source code must retain the above copyright â
â notice, this list of conditions and the following disclaimer. â
â â
â 2. Redistributions in binary form must reproduce the above copyright â
â notice, this list of conditions and the following disclaimer in â
â the documentation and/or other materials provided with the â
â distribution. â
â â
â THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS "AS IS" AND â
â ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE â
â IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR â
â PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS â
â BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, â
â OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT â
â OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR â
â BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, â
â WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE â
â OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, â
â EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
#include "libc/errno.h"
#include "libc/fmt/fmt.h"
#include "libc/str/locale.h"
#include "libc/str/unicode.h"
#include "third_party/python/Modules/_decimal/libmpdec/bits.h"
#include "third_party/python/Modules/_decimal/libmpdec/constants.h"
#include "third_party/python/Modules/_decimal/libmpdec/io.h"
#include "third_party/python/Modules/_decimal/libmpdec/mpdecimal.h"
#include "third_party/python/Modules/_decimal/libmpdec/typearith.h"
/* clang-format off */
#if __GNUC__ >= 11
#pragma GCC diagnostic ignored "-Wmisleading-indentation"
#endif
asm(".ident\t\"\\n\\n\
libmpdec (BSD-2)\\n\
Copyright 2008-2016 Stefan Krah\"");
asm(".include \"libc/disclaimer.inc\"");
/* This file contains functions for decimal <-> string conversions, including
PEP-3101 formatting for numeric types. */
/* Disable warning that is part of -Wextra since gcc 7.0. */
#if defined(__GNUC__) && !defined(__INTEL_COMPILER) && __GNUC__ >= 7
#pragma GCC diagnostic ignored "-Wimplicit-fallthrough"
#endif
/*
* Work around the behavior of tolower() and strcasecmp() in certain
* locales. For example, in tr_TR.utf8:
*
* tolower((unsigned char)'I') == 'I'
*
* u is the exact uppercase version of l; n is strlen(l) or strlen(l)+1
*/
static inline int
_mpd_strneq(const char *s, const char *l, const char *u, size_t n)
{
while (--n != SIZE_MAX) {
if (*s != *l && *s != *u) {
return 0;
}
s++; u++; l++;
}
return 1;
}
static mpd_ssize_t
strtoexp(const char *s)
{
char *end;
mpd_ssize_t retval;
errno = 0;
retval = mpd_strtossize(s, &end, 10);
if (errno == 0 && !(*s != '\0' && *end == '\0'))
errno = EINVAL;
return retval;
}
/*
* Scan 'len' words. The most significant word contains 'r' digits,
* the remaining words are full words. Skip dpoint. The string 's' must
* consist of digits and an optional single decimal point at 'dpoint'.
*/
static void
string_to_coeff(mpd_uint_t *data, const char *s, const char *dpoint, int r,
size_t len)
{
int j;
if (r > 0) {
data[--len] = 0;
for (j = 0; j < r; j++, s++) {
if (s == dpoint) s++;
data[len] = 10 * data[len] + (*s - '0');
}
}
while (--len != SIZE_MAX) {
data[len] = 0;
for (j = 0; j < MPD_RDIGITS; j++, s++) {
if (s == dpoint) s++;
data[len] = 10 * data[len] + (*s - '0');
}
}
}
/*
* Partially verify a numeric string of the form:
*
* [cdigits][.][cdigits][eE][+-][edigits]
*
* If successful, return a pointer to the location of the first
* relevant coefficient digit. This digit is either non-zero or
* part of one of the following patterns:
*
* ["0\x00", "0.\x00", "0.E", "0.e", "0E", "0e"]
*
* The locations of a single optional dot or indicator are stored
* in 'dpoint' and 'exp'.
*
* The end of the string is stored in 'end'. If an indicator [eE]
* occurs without trailing [edigits], the condition is caught
* later by strtoexp().
*/
static const char *
scan_dpoint_exp(const char *s, const char **dpoint, const char **exp,
const char **end)
{
const char *coeff = NULL;
*dpoint = NULL;
*exp = NULL;
for (; *s != '\0'; s++) {
switch (*s) {
case '.':
if (*dpoint != NULL || *exp != NULL)
return NULL;
*dpoint = s;
break;
case 'E': case 'e':
if (*exp != NULL)
return NULL;
*exp = s;
if (*(s+1) == '+' || *(s+1) == '-')
s++;
break;
default:
if (!isdigit((uchar)*s))
return NULL;
if (coeff == NULL && *exp == NULL) {
if (*s == '0') {
if (!isdigit((uchar)*(s+1)))
if (!(*(s+1) == '.' &&
isdigit((uchar)*(s+2))))
coeff = s;
}
else {
coeff = s;
}
}
break;
}
}
*end = s;
return coeff;
}
/* scan the payload of a NaN */
static const char *
scan_payload(const char *s, const char **end)
{
const char *coeff;
while (*s == '0')
s++;
coeff = s;
while (isdigit((uchar)*s))
s++;
*end = s;
return (*s == '\0') ? coeff : NULL;
}
/* convert a character string to a decimal */
void
mpd_qset_string(mpd_t *dec, const char *s, const mpd_context_t *ctx,
uint32_t *status)
{
mpd_ssize_t q, r, len;
const char *coeff, *end;
const char *dpoint = NULL, *exp = NULL;
size_t digits;
uint8_t sign = MPD_POS;
mpd_set_flags(dec, 0);
dec->len = 0;
dec->exp = 0;
/* sign */
if (*s == '+') {
s++;
}
else if (*s == '-') {
mpd_set_negative(dec);
sign = MPD_NEG;
s++;
}
if (_mpd_strneq(s, "nan", "NAN", 3)) { /* NaN */
s += 3;
mpd_setspecial(dec, sign, MPD_NAN);
if (*s == '\0')
return;
/* validate payload: digits only */
if ((coeff = scan_payload(s, &end)) == NULL)
goto conversion_error;
/* payload consists entirely of zeros */
if (*coeff == '\0')
return;
digits = end - coeff;
/* prec >= 1, clamp is 0 or 1 */
if (digits > (size_t)(ctx->prec-ctx->clamp))
goto conversion_error;
} /* sNaN */
else if (_mpd_strneq(s, "snan", "SNAN", 4)) {
s += 4;
mpd_setspecial(dec, sign, MPD_SNAN);
if (*s == '\0')
return;
/* validate payload: digits only */
if ((coeff = scan_payload(s, &end)) == NULL)
goto conversion_error;
/* payload consists entirely of zeros */
if (*coeff == '\0')
return;
digits = end - coeff;
if (digits > (size_t)(ctx->prec-ctx->clamp))
goto conversion_error;
}
else if (_mpd_strneq(s, "inf", "INF", 3)) {
s += 3;
if (*s == '\0' || _mpd_strneq(s, "inity", "INITY", 6)) {
/* numeric-value: infinity */
mpd_setspecial(dec, sign, MPD_INF);
return;
}
goto conversion_error;
}
else {
/* scan for start of coefficient, decimal point, indicator, end */
if ((coeff = scan_dpoint_exp(s, &dpoint, &exp, &end)) == NULL)
goto conversion_error;
/* numeric-value: [exponent-part] */
if (exp) {
/* exponent-part */
end = exp; exp++;
dec->exp = strtoexp(exp);
if (errno) {
if (!(errno == ERANGE &&
(dec->exp == MPD_SSIZE_MAX ||
dec->exp == MPD_SSIZE_MIN)))
goto conversion_error;
}
}
digits = end - coeff;
if (dpoint) {
size_t fracdigits = end-dpoint-1;
if (dpoint > coeff) digits--;
if (fracdigits > MPD_MAX_PREC) {
goto conversion_error;
}
if (dec->exp < MPD_SSIZE_MIN+(mpd_ssize_t)fracdigits) {
dec->exp = MPD_SSIZE_MIN;
}
else {
dec->exp -= (mpd_ssize_t)fracdigits;
}
}
if (digits > MPD_MAX_PREC) {
goto conversion_error;
}
if (dec->exp > MPD_EXP_INF) {
dec->exp = MPD_EXP_INF;
}
if (dec->exp == MPD_SSIZE_MIN) {
dec->exp = MPD_SSIZE_MIN+1;
}
}
_mpd_idiv_word(&q, &r, (mpd_ssize_t)digits, MPD_RDIGITS);
len = (r == 0) ? q : q+1;
if (len == 0) {
goto conversion_error; /* GCOV_NOT_REACHED */
}
if (!mpd_qresize(dec, len, status)) {
mpd_seterror(dec, MPD_Malloc_error, status);
return;
}
dec->len = len;
string_to_coeff(dec->data, coeff, dpoint, (int)r, len);
mpd_setdigits(dec);
mpd_qfinalize(dec, ctx, status);
return;
conversion_error:
/* standard wants a positive NaN */
mpd_seterror(dec, MPD_Conversion_syntax, status);
}
/* Print word x with n decimal digits to string s. dot is either NULL
or the location of a decimal point. */
#define EXTRACT_DIGIT(s, x, d, dot) \
if (s == dot) *s++ = '.'; *s++ = '0' + (char)(x / d); x %= d
static inline char *
word_to_string(char *s, mpd_uint_t x, int n, char *dot)
{
switch(n) {
case 20: EXTRACT_DIGIT(s, x, 10000000000000000000ULL, dot); /* GCOV_NOT_REACHED */
case 19: EXTRACT_DIGIT(s, x, 1000000000000000000ULL, dot);
case 18: EXTRACT_DIGIT(s, x, 100000000000000000ULL, dot);
case 17: EXTRACT_DIGIT(s, x, 10000000000000000ULL, dot);
case 16: EXTRACT_DIGIT(s, x, 1000000000000000ULL, dot);
case 15: EXTRACT_DIGIT(s, x, 100000000000000ULL, dot);
case 14: EXTRACT_DIGIT(s, x, 10000000000000ULL, dot);
case 13: EXTRACT_DIGIT(s, x, 1000000000000ULL, dot);
case 12: EXTRACT_DIGIT(s, x, 100000000000ULL, dot);
case 11: EXTRACT_DIGIT(s, x, 10000000000ULL, dot);
case 10: EXTRACT_DIGIT(s, x, 1000000000UL, dot);
case 9: EXTRACT_DIGIT(s, x, 100000000UL, dot);
case 8: EXTRACT_DIGIT(s, x, 10000000UL, dot);
case 7: EXTRACT_DIGIT(s, x, 1000000UL, dot);
case 6: EXTRACT_DIGIT(s, x, 100000UL, dot);
case 5: EXTRACT_DIGIT(s, x, 10000UL, dot);
case 4: EXTRACT_DIGIT(s, x, 1000UL, dot);
case 3: EXTRACT_DIGIT(s, x, 100UL, dot);
case 2: EXTRACT_DIGIT(s, x, 10UL, dot);
default: if (s == dot) *s++ = '.'; *s++ = '0' + (char)x;
}
*s = '\0';
return s;
}
/* Print exponent x to string s. Undefined for MPD_SSIZE_MIN. */
static inline char *
exp_to_string(char *s, mpd_ssize_t x)
{
char sign = '+';
if (x < 0) {
sign = '-';
x = -x;
}
*s++ = sign;
return word_to_string(s, x, mpd_word_digits(x), NULL);
}
/* Print the coefficient of dec to string s. len(dec) > 0. */
static inline char *
coeff_to_string(char *s, const mpd_t *dec)
{
mpd_uint_t x;
mpd_ssize_t i;
/* most significant word */
x = mpd_msword(dec);
s = word_to_string(s, x, mpd_word_digits(x), NULL);
/* remaining full words */
for (i=dec->len-2; i >= 0; --i) {
x = dec->data[i];
s = word_to_string(s, x, MPD_RDIGITS, NULL);
}
return s;
}
/* Print the coefficient of dec to string s. len(dec) > 0. dot is either
NULL or a pointer to the location of a decimal point. */
static inline char *
coeff_to_string_dot(char *s, char *dot, const mpd_t *dec)
{
mpd_uint_t x;
mpd_ssize_t i;
/* most significant word */
x = mpd_msword(dec);
s = word_to_string(s, x, mpd_word_digits(x), dot);
/* remaining full words */
for (i=dec->len-2; i >= 0; --i) {
x = dec->data[i];
s = word_to_string(s, x, MPD_RDIGITS, dot);
}
return s;
}
/* Format type */
#define MPD_FMT_LOWER 0x00000000
#define MPD_FMT_UPPER 0x00000001
#define MPD_FMT_TOSCI 0x00000002
#define MPD_FMT_TOENG 0x00000004
#define MPD_FMT_EXP 0x00000008
#define MPD_FMT_FIXED 0x00000010
#define MPD_FMT_PERCENT 0x00000020
#define MPD_FMT_SIGN_SPACE 0x00000040
#define MPD_FMT_SIGN_PLUS 0x00000080
/* Default place of the decimal point for MPD_FMT_TOSCI, MPD_FMT_EXP */
#define MPD_DEFAULT_DOTPLACE 1
/*
* Set *result to the string representation of a decimal. Return the length
* of *result, not including the terminating '\0' character.
*
* Formatting is done according to 'flags'. A return value of -1 with *result
* set to NULL indicates MPD_Malloc_error.
*
* 'dplace' is the default place of the decimal point. It is always set to
* MPD_DEFAULT_DOTPLACE except for zeros in combination with MPD_FMT_EXP.
*/
static mpd_ssize_t
_mpd_to_string(char **result, const mpd_t *dec, int flags, mpd_ssize_t dplace)
{
char *decstring = NULL, *cp = NULL;
mpd_ssize_t ldigits;
mpd_ssize_t mem = 0, k;
if (mpd_isspecial(dec)) {
mem = sizeof "-Infinity%";
if (mpd_isnan(dec) && dec->len > 0) {
/* diagnostic code */
mem += dec->digits;
}
cp = decstring = mpd_alloc(mem, sizeof *decstring);
if (cp == NULL) {
*result = NULL;
return -1;
}
if (mpd_isnegative(dec)) {
*cp++ = '-';
}
else if (flags&MPD_FMT_SIGN_SPACE) {
*cp++ = ' ';
}
else if (flags&MPD_FMT_SIGN_PLUS) {
*cp++ = '+';
}
if (mpd_isnan(dec)) {
if (mpd_isqnan(dec)) {
strcpy(cp, "NaN");
cp += 3;
}
else {
strcpy(cp, "sNaN");
cp += 4;
}
if (dec->len > 0) { /* diagnostic code */
cp = coeff_to_string(cp, dec);
}
}
else if (mpd_isinfinite(dec)) {
strcpy(cp, "Infinity");
cp += 8;
}
else { /* debug */
abort(); /* GCOV_NOT_REACHED */
}
}
else {
assert(dec->len > 0);
/*
* For easier manipulation of the decimal point's location
* and the exponent that is finally printed, the number is
* rescaled to a virtual representation with exp = 0. Here
* ldigits denotes the number of decimal digits to the left
* of the decimal point and remains constant once initialized.
*
* dplace is the location of the decimal point relative to
* the start of the coefficient. Note that 3) always holds
* when dplace is shifted.
*
* 1) ldigits := dec->digits - dec->exp
* 2) dplace := ldigits (initially)
* 3) exp := ldigits - dplace (initially exp = 0)
*
* 0.00000_.____._____000000.
* ^ ^ ^ ^
* | | | |
* | | | `- dplace >= digits
* | | `- dplace in the middle of the coefficient
* | ` dplace = 1 (after the first coefficient digit)
* `- dplace <= 0
*/
ldigits = dec->digits + dec->exp;
if (flags&MPD_FMT_EXP) {
;
}
else if (flags&MPD_FMT_FIXED || (dec->exp <= 0 && ldigits > -6)) {
/* MPD_FMT_FIXED: always use fixed point notation.
* MPD_FMT_TOSCI, MPD_FMT_TOENG: for a certain range,
* override exponent notation. */
dplace = ldigits;
}
else if (flags&MPD_FMT_TOENG) {
if (mpd_iszero(dec)) {
/* If the exponent is divisible by three,
* dplace = 1. Otherwise, move dplace one
* or two places to the left. */
dplace = -1 + mod_mpd_ssize_t(dec->exp+2, 3);
}
else { /* ldigits-1 is the adjusted exponent, which
* should be divisible by three. If not, move
* dplace one or two places to the right. */
dplace += mod_mpd_ssize_t(ldigits-1, 3);
}
}
/*
* Basic space requirements:
*
* [-][.][coeffdigits][E][-][expdigits+1][%]['\0']
*
* If the decimal point lies outside of the coefficient digits,
* space is adjusted accordingly.
*/
if (dplace <= 0) {
mem = -dplace + dec->digits + 2;
}
else if (dplace >= dec->digits) {
mem = dplace;
}
else {
mem = dec->digits;
}
mem += (MPD_EXPDIGITS+1+6);
cp = decstring = mpd_alloc(mem, sizeof *decstring);
if (cp == NULL) {
*result = NULL;
return -1;
}
if (mpd_isnegative(dec)) {
*cp++ = '-';
}
else if (flags&MPD_FMT_SIGN_SPACE) {
*cp++ = ' ';
}
else if (flags&MPD_FMT_SIGN_PLUS) {
*cp++ = '+';
}
if (dplace <= 0) {
/* space: -dplace+dec->digits+2 */
*cp++ = '0';
*cp++ = '.';
for (k = 0; k < -dplace; k++) {
*cp++ = '0';
}
cp = coeff_to_string(cp, dec);
}
else if (dplace >= dec->digits) {
/* space: dplace */
cp = coeff_to_string(cp, dec);
for (k = 0; k < dplace-dec->digits; k++) {
*cp++ = '0';
}
}
else {
/* space: dec->digits+1 */
cp = coeff_to_string_dot(cp, cp+dplace, dec);
}
/*
* Conditions for printing an exponent:
*
* MPD_FMT_TOSCI, MPD_FMT_TOENG: only if ldigits != dplace
* MPD_FMT_FIXED: never (ldigits == dplace)
* MPD_FMT_EXP: always
*/
if (ldigits != dplace || flags&MPD_FMT_EXP) {
/* space: expdigits+2 */
*cp++ = (flags&MPD_FMT_UPPER) ? 'E' : 'e';
cp = exp_to_string(cp, ldigits-dplace);
}
}
if (flags&MPD_FMT_PERCENT) {
*cp++ = '%';
}
assert(cp < decstring+mem);
assert(cp-decstring < MPD_SSIZE_MAX);
*cp = '\0';
*result = decstring;
return (mpd_ssize_t)(cp-decstring);
}
char *
mpd_to_sci(const mpd_t *dec, int fmt)
{
char *res;
int flags = MPD_FMT_TOSCI;
flags |= fmt ? MPD_FMT_UPPER : MPD_FMT_LOWER;
(void)_mpd_to_string(&res, dec, flags, MPD_DEFAULT_DOTPLACE);
return res;
}
char *
mpd_to_eng(const mpd_t *dec, int fmt)
{
char *res;
int flags = MPD_FMT_TOENG;
flags |= fmt ? MPD_FMT_UPPER : MPD_FMT_LOWER;
(void)_mpd_to_string(&res, dec, flags, MPD_DEFAULT_DOTPLACE);
return res;
}
mpd_ssize_t
mpd_to_sci_size(char **res, const mpd_t *dec, int fmt)
{
int flags = MPD_FMT_TOSCI;
flags |= fmt ? MPD_FMT_UPPER : MPD_FMT_LOWER;
return _mpd_to_string(res, dec, flags, MPD_DEFAULT_DOTPLACE);
}
mpd_ssize_t
mpd_to_eng_size(char **res, const mpd_t *dec, int fmt)
{
int flags = MPD_FMT_TOENG;
flags |= fmt ? MPD_FMT_UPPER : MPD_FMT_LOWER;
return _mpd_to_string(res, dec, flags, MPD_DEFAULT_DOTPLACE);
}
/* Copy a single UTF-8 char to dest. See: The Unicode Standard, version 5.2,
chapter 3.9: Well-formed UTF-8 byte sequences. */
static int
_mpd_copy_utf8(char dest[5], const char *s)
{
const uchar *cp = (const uchar *)s;
uchar lb, ub;
int count, i;
if (*cp == 0) {
/* empty string */
dest[0] = '\0';
return 0;
}
else if (*cp <= 0x7f) {
/* ascii */
dest[0] = *cp;
dest[1] = '\0';
return 1;
}
else if (0xc2 <= *cp && *cp <= 0xdf) {
lb = 0x80; ub = 0xbf;
count = 2;
}
else if (*cp == 0xe0) {
lb = 0xa0; ub = 0xbf;
count = 3;
}
else if (*cp <= 0xec) {
lb = 0x80; ub = 0xbf;
count = 3;
}
else if (*cp == 0xed) {
lb = 0x80; ub = 0x9f;
count = 3;
}
else if (*cp <= 0xef) {
lb = 0x80; ub = 0xbf;
count = 3;
}
else if (*cp == 0xf0) {
lb = 0x90; ub = 0xbf;
count = 4;
}
else if (*cp <= 0xf3) {
lb = 0x80; ub = 0xbf;
count = 4;
}
else if (*cp == 0xf4) {
lb = 0x80; ub = 0x8f;
count = 4;
}
else {
/* invalid */
goto error;
}
dest[0] = *cp++;
if (*cp < lb || ub < *cp) {
goto error;
}
dest[1] = *cp++;
for (i = 2; i < count; i++) {
if (*cp < 0x80 || 0xbf < *cp) {
goto error;
}
dest[i] = *cp++;
}
dest[i] = '\0';
return count;
error:
dest[0] = '\0';
return -1;
}
int
mpd_validate_lconv(mpd_spec_t *spec)
{
size_t n;
#if CHAR_MAX == SCHAR_MAX
const char *cp = spec->grouping;
while (*cp != '\0') {
if (*cp++ < 0) {
return -1;
}
}
#endif
n = strlen(spec->dot);
if (n == 0 || n > 4) {
return -1;
}
if (strlen(spec->sep) > 4) {
return -1;
}
return 0;
}
int
mpd_parse_fmt_str(mpd_spec_t *spec, const char *fmt, int caps)
{
char *cp = (char *)fmt;
int have_align = 0, n;
/* defaults */
spec->min_width = 0;
spec->prec = -1;
spec->type = caps ? 'G' : 'g';
spec->align = '>';
spec->sign = '-';
spec->dot = "";
spec->sep = "";
spec->grouping = "";
/* presume that the first character is a UTF-8 fill character */
if ((n = _mpd_copy_utf8(spec->fill, cp)) < 0) {
return 0;
}
/* alignment directive, prefixed by a fill character */
if (*cp && (*(cp+n) == '<' || *(cp+n) == '>' ||
*(cp+n) == '=' || *(cp+n) == '^')) {
cp += n;
spec->align = *cp++;
have_align = 1;
} /* alignment directive */
else {
/* default fill character */
spec->fill[0] = ' ';
spec->fill[1] = '\0';
if (*cp == '<' || *cp == '>' ||
*cp == '=' || *cp == '^') {
spec->align = *cp++;
have_align = 1;
}
}
/* sign formatting */
if (*cp == '+' || *cp == '-' || *cp == ' ') {
spec->sign = *cp++;
}
/* zero padding */
if (*cp == '0') {
/* zero padding implies alignment, which should not be
* specified twice. */
if (have_align) {
return 0;
}
spec->align = 'z';
spec->fill[0] = *cp++;
spec->fill[1] = '\0';
}
/* minimum width */
if (isdigit((uchar)*cp)) {
if (*cp == '0') {
return 0;
}
errno = 0;
spec->min_width = mpd_strtossize(cp, &cp, 10);
if (errno == ERANGE || errno == EINVAL) {
return 0;
}
}
/* thousands separator */
if (*cp == ',') {
spec->dot = ".";
spec->sep = ",";
spec->grouping = "\003\003";
cp++;
}
/* fraction digits or significant digits */
if (*cp == '.') {
cp++;
if (!isdigit((uchar)*cp)) {
return 0;
}
errno = 0;
spec->prec = mpd_strtossize(cp, &cp, 10);
if (errno == ERANGE || errno == EINVAL) {
return 0;
}
}
/* type */
if (*cp == 'E' || *cp == 'e' || *cp == 'F' || *cp == 'f' ||
*cp == 'G' || *cp == 'g' || *cp == '%') {
spec->type = *cp++;
}
else if (*cp == 'N' || *cp == 'n') {
/* locale specific conversion */
struct lconv *lc;
/* separator has already been specified */
if (*spec->sep) {
return 0;
}
spec->type = *cp++;
spec->type = (spec->type == 'N') ? 'G' : 'g';
lc = localeconv();
spec->dot = lc->decimal_point;
spec->sep = lc->thousands_sep;
spec->grouping = lc->grouping;
if (mpd_validate_lconv(spec) < 0) {
return 0; /* GCOV_NOT_REACHED */
}
}
/* check correctness */
if (*cp != '\0') {
return 0;
}
return 1;
}
/*
* The following functions assume that spec->min_width <= MPD_MAX_PREC, which
* is made sure in mpd_qformat_spec. Then, even with a spec that inserts a
* four-byte separator after each digit, nbytes in the following struct
* cannot overflow.
*/
/* Multibyte string */
typedef struct {
mpd_ssize_t nbytes; /* length in bytes */
mpd_ssize_t nchars; /* length in chars */
mpd_ssize_t cur; /* current write index */
char *data;
} mpd_mbstr_t;
static inline void
_mpd_bcopy(char *dest, const char *src, mpd_ssize_t n)
{
/* [jart] just use memmove */
memmove(dest, src, n);
}
static inline void
_mbstr_copy_char(mpd_mbstr_t *dest, const char *src, mpd_ssize_t n)
{
dest->nbytes += n;
dest->nchars += (n > 0 ? 1 : 0);
dest->cur -= n;
if (dest->data != NULL) {
_mpd_bcopy(dest->data+dest->cur, src, n);
}
}
static inline void
_mbstr_copy_ascii(mpd_mbstr_t *dest, const char *src, mpd_ssize_t n)
{
dest->nbytes += n;
dest->nchars += n;
dest->cur -= n;
if (dest->data != NULL) {
_mpd_bcopy(dest->data+dest->cur, src, n);
}
}
static inline void
_mbstr_copy_pad(mpd_mbstr_t *dest, mpd_ssize_t n)
{
dest->nbytes += n;
dest->nchars += n;
dest->cur -= n;
if (dest->data != NULL) {
char *cp = dest->data + dest->cur;
while (--n >= 0) {
cp[n] = '0';
}
}
}
/*
* Copy a numeric string to dest->data, adding separators in the integer
* part according to spec->grouping. If leading zero padding is enabled
* and the result is smaller than spec->min_width, continue adding zeros
* and separators until the minimum width is reached.
*
* The final length of dest->data is stored in dest->nbytes. The number
* of UTF-8 characters is stored in dest->nchars.
*
* First run (dest->data == NULL): determine the length of the result
* string and store it in dest->nbytes.
*
* Second run (write to dest->data): data is written in chunks and in
* reverse order, starting with the rest of the numeric string.
*/
static void
_mpd_add_sep_dot(mpd_mbstr_t *dest,
const char *sign, /* location of optional sign */
const char *src, mpd_ssize_t n_src, /* integer part and length */
const char *dot, /* location of optional decimal point */
const char *rest, mpd_ssize_t n_rest, /* remaining part and length */
const mpd_spec_t *spec)
{
mpd_ssize_t n_sep, n_sign, consume;
const char *g;
int pad = 0;
n_sign = sign ? 1 : 0;
n_sep = (mpd_ssize_t)strlen(spec->sep);
/* Initial write index: set to location of '\0' in the output string.
* Irrelevant for the first run. */
dest->cur = dest->nbytes;
dest->nbytes = dest->nchars = 0;
_mbstr_copy_ascii(dest, rest, n_rest);
if (dot) {
_mbstr_copy_char(dest, dot, (mpd_ssize_t)strlen(dot));
}
g = spec->grouping;
consume = *g;
while (1) {
/* If the group length is 0 or CHAR_MAX or greater than the
* number of source bytes, consume all remaining bytes. */
if (*g == 0 || *g == CHAR_MAX || consume > n_src) {
consume = n_src;
}
n_src -= consume;
if (pad) {
_mbstr_copy_pad(dest, consume);
}
else {
_mbstr_copy_ascii(dest, src+n_src, consume);
}
if (n_src == 0) {
/* Either the real source of intpart digits or the virtual
* source of padding zeros is exhausted. */
if (spec->align == 'z' &&
dest->nchars + n_sign < spec->min_width) {
/* Zero padding is set and length < min_width:
* Generate n_src additional characters. */
n_src = spec->min_width - (dest->nchars + n_sign);
/* Next iteration:
* case *g == 0 || *g == CHAR_MAX:
* consume all padding characters
* case consume < g*:
* fill remainder of current group
* case consume == g*
* copying is a no-op */
consume = *g - consume;
/* Switch on virtual source of zeros. */
pad = 1;
continue;
}
break;
}
if (n_sep > 0) {
/* If padding is switched on, separators are counted
* as padding characters. This rule does not apply if
* the separator would be the first character of the
* result string. */
if (pad && n_src > 1) n_src -= 1;
_mbstr_copy_char(dest, spec->sep, n_sep);
}
/* If non-NUL, use the next value for grouping. */
if (*g && *(g+1)) g++;
consume = *g;
}
if (sign) {
_mbstr_copy_ascii(dest, sign, 1);
}
if (dest->data) {
dest->data[dest->nbytes] = '\0';
}
}
/*
* Convert a numeric-string to its locale-specific appearance.
* The string must have one of these forms:
*
* 1) [sign] digits [exponent-part]
* 2) [sign] digits '.' [digits] [exponent-part]
*
* Not allowed, since _mpd_to_string() never returns this form:
*
* 3) [sign] '.' digits [exponent-part]
*
* Input: result->data := original numeric string (ASCII)
* result->bytes := strlen(result->data)
* result->nchars := strlen(result->data)
*
* Output: result->data := modified or original string
* result->bytes := strlen(result->data)
* result->nchars := number of characters (possibly UTF-8)
*/
static int
_mpd_apply_lconv(mpd_mbstr_t *result, const mpd_spec_t *spec, uint32_t *status)
{
const char *sign = NULL, *intpart = NULL, *dot = NULL;
const char *rest, *dp;
char *decstring;
mpd_ssize_t n_int, n_rest;
/* original numeric string */
dp = result->data;
/* sign */
if (*dp == '+' || *dp == '-' || *dp == ' ') {
sign = dp++;
}
/* integer part */
assert(isdigit((uchar)*dp));
intpart = dp++;
while (isdigit((uchar)*dp)) {
dp++;
}
n_int = (mpd_ssize_t)(dp-intpart);
/* decimal point */
if (*dp == '.') {
dp++; dot = spec->dot;
}
/* rest */
rest = dp;
n_rest = result->nbytes - (mpd_ssize_t)(dp-result->data);
if (dot == NULL && (*spec->sep == '\0' || *spec->grouping == '\0')) {
/* _mpd_add_sep_dot() would not change anything */
return 1;
}
/* Determine the size of the new decimal string after inserting the
* decimal point, optional separators and optional padding. */
decstring = result->data;
result->data = NULL;
_mpd_add_sep_dot(result, sign, intpart, n_int, dot,
rest, n_rest, spec);
result->data = mpd_alloc(result->nbytes+1, 1);
if (result->data == NULL) {
*status |= MPD_Malloc_error;
mpd_free(decstring);
return 0;
}
/* Perform actual writes. */
_mpd_add_sep_dot(result, sign, intpart, n_int, dot,
rest, n_rest, spec);
mpd_free(decstring);
return 1;
}
/* Add padding to the formatted string if necessary. */
static int
_mpd_add_pad(mpd_mbstr_t *result, const mpd_spec_t *spec, uint32_t *status)
{
if (result->nchars < spec->min_width) {
mpd_ssize_t add_chars, add_bytes;
size_t lpad = 0, rpad = 0;
size_t n_fill, len, i, j;
char align = spec->align;
uint8_t err = 0;
char *cp;
n_fill = strlen(spec->fill);
add_chars = (spec->min_width - result->nchars);
/* max value: MPD_MAX_PREC * 4 */
add_bytes = add_chars * (mpd_ssize_t)n_fill;
cp = result->data = mpd_realloc(result->data,
result->nbytes+add_bytes+1,
sizeof *result->data, &err);
if (err) {
*status |= MPD_Malloc_error;
mpd_free(result->data);
return 0;
}
if (align == 'z') {
align = '=';
}
if (align == '<') {
rpad = add_chars;
}
else if (align == '>' || align == '=') {
lpad = add_chars;
}
else { /* align == '^' */
lpad = add_chars/2;
rpad = add_chars-lpad;
}
len = result->nbytes;
if (align == '=' && (*cp == '-' || *cp == '+' || *cp == ' ')) {
/* leave sign in the leading position */
cp++; len--;
}
memmove(cp+n_fill*lpad, cp, len);
for (i = 0; i < lpad; i++) {
for (j = 0; j < n_fill; j++) {
cp[i*n_fill+j] = spec->fill[j];
}
}
cp += (n_fill*lpad + len);
for (i = 0; i < rpad; i++) {
for (j = 0; j < n_fill; j++) {
cp[i*n_fill+j] = spec->fill[j];
}
}
result->nbytes += add_bytes;
result->nchars += add_chars;
result->data[result->nbytes] = '\0';
}
return 1;
}
/* Round a number to prec digits. The adjusted exponent stays the same
or increases by one if rounding up crosses a power of ten boundary.
If result->digits would exceed MPD_MAX_PREC+1, MPD_Invalid_operation
is set and the result is NaN. */
static inline void
_mpd_round(mpd_t *result, const mpd_t *a, mpd_ssize_t prec,
const mpd_context_t *ctx, uint32_t *status)
{
mpd_ssize_t exp = a->exp + a->digits - prec;
if (prec <= 0) {
mpd_seterror(result, MPD_Invalid_operation, status); /* GCOV_NOT_REACHED */
return; /* GCOV_NOT_REACHED */
}
if (mpd_isspecial(a) || mpd_iszero(a)) {
mpd_qcopy(result, a, status); /* GCOV_NOT_REACHED */
return; /* GCOV_NOT_REACHED */
}
mpd_qrescale_fmt(result, a, exp, ctx, status);
if (result->digits > prec) {
mpd_qrescale_fmt(result, result, exp+1, ctx, status);
}
}
/*
* Return the string representation of an mpd_t, formatted according to 'spec'.
* The format specification is assumed to be valid. Memory errors are indicated
* as usual. This function is quiet.
*/
char *
mpd_qformat_spec(const mpd_t *dec, const mpd_spec_t *spec,
const mpd_context_t *ctx, uint32_t *status)
{
mpd_uint_t dt[MPD_MINALLOC_MAX];
mpd_t tmp = {MPD_STATIC|MPD_STATIC_DATA,0,0,0,MPD_MINALLOC_MAX,dt};
mpd_ssize_t dplace = MPD_DEFAULT_DOTPLACE;
mpd_mbstr_t result;
mpd_spec_t stackspec;
char type = spec->type;
int flags = 0;
if (spec->min_width > MPD_MAX_PREC) {
*status |= MPD_Invalid_operation;
return NULL;
}
if (isupper((uchar)type)) {
type = tolower((uchar)type);
flags |= MPD_FMT_UPPER;
}
if (spec->sign == ' ') {
flags |= MPD_FMT_SIGN_SPACE;
}
else if (spec->sign == '+') {
flags |= MPD_FMT_SIGN_PLUS;
}
if (mpd_isspecial(dec)) {
if (spec->align == 'z') {
stackspec = *spec;
stackspec.fill[0] = ' ';
stackspec.fill[1] = '\0';
stackspec.align = '>';
spec = &stackspec;
}
if (type == '%') {
flags |= MPD_FMT_PERCENT;
}
}
else {
uint32_t workstatus = 0;
mpd_ssize_t prec;
switch (type) {
case 'g': flags |= MPD_FMT_TOSCI; break;
case 'e': flags |= MPD_FMT_EXP; break;
case '%': flags |= MPD_FMT_PERCENT;
if (!mpd_qcopy(&tmp, dec, status)) {
return NULL;
}
tmp.exp += 2;
dec = &tmp;
type = 'f'; /* fall through */
case 'f': flags |= MPD_FMT_FIXED; break;
default: abort(); /* debug: GCOV_NOT_REACHED */
}
if (spec->prec >= 0) {
if (spec->prec > MPD_MAX_PREC) {
*status |= MPD_Invalid_operation;
goto error;
}
switch (type) {
case 'g':
prec = (spec->prec == 0) ? 1 : spec->prec;
if (dec->digits > prec) {
_mpd_round(&tmp, dec, prec, ctx,
&workstatus);
dec = &tmp;
}
break;
case 'e':
if (mpd_iszero(dec)) {
dplace = 1-spec->prec;
}
else {
_mpd_round(&tmp, dec, spec->prec+1, ctx,
&workstatus);
dec = &tmp;
}
break;
case 'f':
mpd_qrescale(&tmp, dec, -spec->prec, ctx,
&workstatus);
dec = &tmp;
break;
}
}
if (type == 'f') {
if (mpd_iszero(dec) && dec->exp > 0) {
mpd_qrescale(&tmp, dec, 0, ctx, &workstatus);
dec = &tmp;
}
}
if (workstatus&MPD_Errors) {
*status |= (workstatus&MPD_Errors);
goto error;
}
}
/*
* At this point, for all scaled or non-scaled decimals:
* 1) 1 <= digits <= MAX_PREC+1
* 2) adjexp(scaled) = adjexp(orig) [+1]
* 3) case 'g': MIN_ETINY <= exp <= MAX_EMAX+1
* case 'e': MIN_ETINY-MAX_PREC <= exp <= MAX_EMAX+1
* case 'f': MIN_ETINY <= exp <= MAX_EMAX+1
* 4) max memory alloc in _mpd_to_string:
* case 'g': MAX_PREC+36
* case 'e': MAX_PREC+36
* case 'f': 2*MPD_MAX_PREC+30
*/
result.nbytes = _mpd_to_string(&result.data, dec, flags, dplace);
result.nchars = result.nbytes;
if (result.nbytes < 0) {
*status |= MPD_Malloc_error;
goto error;
}
if (*spec->dot != '\0' && !mpd_isspecial(dec)) {
if (result.nchars > MPD_MAX_PREC+36) {
/* Since a group length of one is not explicitly
* disallowed, ensure that it is always possible to
* insert a four byte separator after each digit. */
*status |= MPD_Invalid_operation;
mpd_free(result.data);
goto error;
}
if (!_mpd_apply_lconv(&result, spec, status)) {
goto error;
}
}
if (spec->min_width) {
if (!_mpd_add_pad(&result, spec, status)) {
goto error;
}
}
mpd_del(&tmp);
return result.data;
error:
mpd_del(&tmp);
return NULL;
}
char *
mpd_qformat(const mpd_t *dec, const char *fmt, const mpd_context_t *ctx,
uint32_t *status)
{
mpd_spec_t spec;
if (!mpd_parse_fmt_str(&spec, fmt, 1)) {
*status |= MPD_Invalid_operation;
return NULL;
}
return mpd_qformat_spec(dec, &spec, ctx, status);
}
/*
* The specification has a *condition* called Invalid_operation and an
* IEEE *signal* called Invalid_operation. The former corresponds to
* MPD_Invalid_operation, the latter to MPD_IEEE_Invalid_operation.
* MPD_IEEE_Invalid_operation comprises the following conditions:
*
* [MPD_Conversion_syntax, MPD_Division_impossible, MPD_Division_undefined,
* MPD_Fpu_error, MPD_Invalid_context, MPD_Invalid_operation,
* MPD_Malloc_error]
*
* In the following functions, 'flag' denotes the condition, 'signal'
* denotes the IEEE signal.
*/
static const char *mpd_flag_string[MPD_NUM_FLAGS] = {
"Clamped",
"Conversion_syntax",
"Division_by_zero",
"Division_impossible",
"Division_undefined",
"Fpu_error",
"Inexact",
"Invalid_context",
"Invalid_operation",
"Malloc_error",
"Not_implemented",
"Overflow",
"Rounded",
"Subnormal",
"Underflow",
};
static const char *mpd_signal_string[MPD_NUM_FLAGS] = {
"Clamped",
"IEEE_Invalid_operation",
"Division_by_zero",
"IEEE_Invalid_operation",
"IEEE_Invalid_operation",
"IEEE_Invalid_operation",
"Inexact",
"IEEE_Invalid_operation",
"IEEE_Invalid_operation",
"IEEE_Invalid_operation",
"Not_implemented",
"Overflow",
"Rounded",
"Subnormal",
"Underflow",
};
/* print conditions to buffer, separated by spaces */
int
mpd_snprint_flags(char *dest, int nmemb, uint32_t flags)
{
char *cp;
int n, j;
assert(nmemb >= MPD_MAX_FLAG_STRING);
*dest = '\0'; cp = dest;
for (j = 0; j < MPD_NUM_FLAGS; j++) {
if (flags & (1U<<j)) {
n = snprintf(cp, nmemb, "%s ", mpd_flag_string[j]);
if (n < 0 || n >= nmemb) return -1;
cp += n; nmemb -= n;
}
}
if (cp != dest) {
*(--cp) = '\0';
}
return (int)(cp-dest);
}
/* print conditions to buffer, in list form */
int
mpd_lsnprint_flags(char *dest, int nmemb, uint32_t flags, const char *flag_string[])
{
char *cp;
int n, j;
assert(nmemb >= MPD_MAX_FLAG_LIST);
if (flag_string == NULL) {
flag_string = mpd_flag_string;
}
*dest = '[';
*(dest+1) = '\0';
cp = dest+1;
--nmemb;
for (j = 0; j < MPD_NUM_FLAGS; j++) {
if (flags & (1U<<j)) {
n = snprintf(cp, nmemb, "%s, ", flag_string[j]);
if (n < 0 || n >= nmemb) return -1;
cp += n; nmemb -= n;
}
}
/* erase the last ", " */
if (cp != dest+1) {
cp -= 2;
}
*cp++ = ']';
*cp = '\0';
return (int)(cp-dest); /* strlen, without NUL terminator */
}
/* print signals to buffer, in list form */
int
mpd_lsnprint_signals(char *dest, int nmemb, uint32_t flags, const char *signal_string[])
{
char *cp;
int n, j;
int ieee_invalid_done = 0;
assert(nmemb >= MPD_MAX_SIGNAL_LIST);
if (signal_string == NULL) {
signal_string = mpd_signal_string;
}
*dest = '[';
*(dest+1) = '\0';
cp = dest+1;
--nmemb;
for (j = 0; j < MPD_NUM_FLAGS; j++) {
uint32_t f = flags & (1U<<j);
if (f) {
if (f&MPD_IEEE_Invalid_operation) {
if (ieee_invalid_done) {
continue;
}
ieee_invalid_done = 1;
}
n = snprintf(cp, nmemb, "%s, ", signal_string[j]);
if (n < 0 || n >= nmemb) return -1;
cp += n; nmemb -= n;
}
}
/* erase the last ", " */
if (cp != dest+1) {
cp -= 2;
}
*cp++ = ']';
*cp = '\0';
return (int)(cp-dest); /* strlen, without NUL terminator */
}
/* The following two functions are mainly intended for debugging. */
void
mpd_fprint(FILE *file, const mpd_t *dec)
{
char *decstring;
decstring = mpd_to_sci(dec, 1);
if (decstring != NULL) {
fprintf(file, "%s\n", decstring);
mpd_free(decstring);
}
else {
fputs("mpd_fprint: output error\n", file); /* GCOV_NOT_REACHED */
}
}
void
mpd_print(const mpd_t *dec)
{
char *decstring;
decstring = mpd_to_sci(dec, 1);
if (decstring != NULL) {
printf("%s\n", decstring);
mpd_free(decstring);
}
else {
fputs("mpd_fprint: output error\n", stderr); /* GCOV_NOT_REACHED */
}
}
| 45,113 | 1,541 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Modules/_decimal/libmpdec/basearith.h | #ifndef BASEARITH_H
#define BASEARITH_H
#include "third_party/python/Modules/_decimal/libmpdec/mpdecimal.h"
#include "third_party/python/Modules/_decimal/libmpdec/typearith.h"
/* clang-format off */
/* Internal header file: all symbols have local scope in the DSO */
mpd_uint_t _mpd_baseadd(mpd_uint_t *w, const mpd_uint_t *u, const mpd_uint_t *v,
mpd_size_t m, mpd_size_t n);
void _mpd_baseaddto(mpd_uint_t *w, const mpd_uint_t *u, mpd_size_t n);
mpd_uint_t _mpd_shortadd(mpd_uint_t *w, mpd_size_t m, mpd_uint_t v);
mpd_uint_t _mpd_shortadd_b(mpd_uint_t *w, mpd_size_t m, mpd_uint_t v,
mpd_uint_t b);
mpd_uint_t _mpd_baseincr(mpd_uint_t *u, mpd_size_t n);
void _mpd_basesub(mpd_uint_t *w, const mpd_uint_t *u, const mpd_uint_t *v,
mpd_size_t m, mpd_size_t n);
void _mpd_basesubfrom(mpd_uint_t *w, const mpd_uint_t *u, mpd_size_t n);
void _mpd_basemul(mpd_uint_t *w, const mpd_uint_t *u, const mpd_uint_t *v,
mpd_size_t m, mpd_size_t n);
void _mpd_shortmul(mpd_uint_t *w, const mpd_uint_t *u, mpd_size_t n,
mpd_uint_t v);
mpd_uint_t _mpd_shortmul_c(mpd_uint_t *w, const mpd_uint_t *u, mpd_size_t n,
mpd_uint_t v);
mpd_uint_t _mpd_shortmul_b(mpd_uint_t *w, const mpd_uint_t *u, mpd_size_t n,
mpd_uint_t v, mpd_uint_t b);
mpd_uint_t _mpd_shortdiv(mpd_uint_t *w, const mpd_uint_t *u, mpd_size_t n,
mpd_uint_t v);
mpd_uint_t _mpd_shortdiv_b(mpd_uint_t *w, const mpd_uint_t *u, mpd_size_t n,
mpd_uint_t v, mpd_uint_t b);
int _mpd_basedivmod(mpd_uint_t *q, mpd_uint_t *r, const mpd_uint_t *uconst,
const mpd_uint_t *vconst, mpd_size_t nplusm, mpd_size_t n);
void _mpd_baseshiftl(mpd_uint_t *dest, mpd_uint_t *src, mpd_size_t n,
mpd_size_t m, mpd_size_t shift);
mpd_uint_t _mpd_baseshiftr(mpd_uint_t *dest, mpd_uint_t *src, mpd_size_t slen,
mpd_size_t shift);
extern const mpd_uint_t mprime_rdx;
/*
* Algorithm from: Division by Invariant Integers using Multiplication,
* T. Granlund and P. L. Montgomery, Proceedings of the SIGPLAN '94
* Conference on Programming Language Design and Implementation.
*
* http://gmplib.org/~tege/divcnst-pldi94.pdf
*
* Variables from the paper and their translations (See section 8):
*
* N := 64
* d := MPD_RADIX
* l := 64
* m' := floor((2**(64+64) - 1)/MPD_RADIX) - 2**64
*
* Since N-l == 0:
*
* dnorm := d
* n2 := hi
* n10 := lo
*
* ACL2 proof: mpd-div-words-r-correct
*/
static inline void
_mpd_div_words_r(mpd_uint_t *q, mpd_uint_t *r, mpd_uint_t hi, mpd_uint_t lo)
{
mpd_uint_t n_adj, h, l, t;
mpd_uint_t n1_neg;
/* n1_neg = if lo >= 2**63 then MPD_UINT_MAX else 0 */
n1_neg = (lo & (1ULL<<63)) ? MPD_UINT_MAX : 0;
/* n_adj = if lo >= 2**63 then lo+MPD_RADIX else lo */
n_adj = lo + (n1_neg & MPD_RADIX);
/* (h, l) = if lo >= 2**63 then m'*(hi+1) else m'*hi */
_mpd_mul_words(&h, &l, mprime_rdx, hi-n1_neg);
l = l + n_adj;
if (l < n_adj) h++;
t = h + hi;
/* At this point t == qest, with q == qest or q == qest+1:
* 1) 0 <= 2**64*hi + lo - qest*MPD_RADIX < 2*MPD_RADIX
*/
/* t = 2**64-1 - qest = 2**64 - (qest+1) */
t = MPD_UINT_MAX - t;
/* (h, l) = 2**64*MPD_RADIX - (qest+1)*MPD_RADIX */
_mpd_mul_words(&h, &l, t, MPD_RADIX);
l = l + lo;
if (l < lo) h++;
h += hi;
h -= MPD_RADIX;
/* (h, l) = 2**64*hi + lo - (qest+1)*MPD_RADIX (mod 2**128)
* Case q == qest+1:
* a) h == 0, l == r
* b) q := h - t == qest+1
* c) r := l
* Case q == qest:
* a) h == MPD_UINT_MAX, l == 2**64-(MPD_RADIX-r)
* b) q := h - t == qest
* c) r := l + MPD_RADIX = r
*/
*q = (h - t);
*r = l + (MPD_RADIX & h);
}
/* Multiply two single base MPD_RADIX words, store result in array w[2]. */
static inline void
_mpd_singlemul(mpd_uint_t w[2], mpd_uint_t u, mpd_uint_t v)
{
mpd_uint_t hi, lo;
_mpd_mul_words(&hi, &lo, u, v);
_mpd_div_words_r(&w[1], &w[0], hi, lo);
}
/* Multiply u (len 2) and v (len m, 1 <= m <= 2). */
static inline void
_mpd_mul_2_le2(mpd_uint_t w[4], mpd_uint_t u[2], mpd_uint_t v[2], mpd_ssize_t m)
{
mpd_uint_t hi, lo;
_mpd_mul_words(&hi, &lo, u[0], v[0]);
_mpd_div_words_r(&w[1], &w[0], hi, lo);
_mpd_mul_words(&hi, &lo, u[1], v[0]);
lo = w[1] + lo;
if (lo < w[1]) hi++;
_mpd_div_words_r(&w[2], &w[1], hi, lo);
if (m == 1) return;
_mpd_mul_words(&hi, &lo, u[0], v[1]);
lo = w[1] + lo;
if (lo < w[1]) hi++;
_mpd_div_words_r(&w[3], &w[1], hi, lo);
_mpd_mul_words(&hi, &lo, u[1], v[1]);
lo = w[2] + lo;
if (lo < w[2]) hi++;
lo = w[3] + lo;
if (lo < w[3]) hi++;
_mpd_div_words_r(&w[3], &w[2], hi, lo);
}
/*
* Test if all words from data[len-1] to data[0] are zero. If len is 0, nothing
* is tested and the coefficient is regarded as "all zero".
*/
static inline int
_mpd_isallzero(const mpd_uint_t *data, mpd_ssize_t len)
{
while (--len >= 0) {
if (data[len] != 0) return 0;
}
return 1;
}
/*
* Test if all full words from data[len-1] to data[0] are MPD_RADIX-1
* (all nines). Return true if len == 0.
*/
static inline int
_mpd_isallnine(const mpd_uint_t *data, mpd_ssize_t len)
{
while (--len >= 0) {
if (data[len] != MPD_RADIX-1) return 0;
}
return 1;
}
#endif /* BASEARITH_H */
| 5,518 | 162 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Modules/_decimal/libmpdec/transpose.h | #ifndef TRANSPOSE_H
#define TRANSPOSE_H
#include "third_party/python/Modules/_decimal/libmpdec/mpdecimal.h"
/* clang-format off */
/* Internal header file: all symbols have local scope in the DSO */
enum {FORWARD_CYCLE, BACKWARD_CYCLE};
void std_trans(mpd_uint_t dest[], mpd_uint_t src[], mpd_size_t rows, mpd_size_t cols);
int transpose_pow2(mpd_uint_t *matrix, mpd_size_t rows, mpd_size_t cols);
void transpose_3xpow2(mpd_uint_t *matrix, mpd_size_t rows, mpd_size_t cols);
static inline void pointerswap(mpd_uint_t **a, mpd_uint_t **b)
{
mpd_uint_t *tmp;
tmp = *b;
*b = *a;
*a = tmp;
}
#endif
| 617 | 24 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Modules/_decimal/libmpdec/difradix2.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:8;coding:utf-8 -*-â
âvi: set net ft=c ts=4 sts=4 sw=4 fenc=utf-8 :viâ
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ¡
â Copyright (c) 2008-2016 Stefan Krah. All rights reserved. â
â â
â Redistribution and use in source and binary forms, with or without â
â modification, are permitted provided that the following conditions â
â are met: â
â â
â 1. Redistributions of source code must retain the above copyright â
â notice, this list of conditions and the following disclaimer. â
â â
â 2. Redistributions in binary form must reproduce the above copyright â
â notice, this list of conditions and the following disclaimer in â
â the documentation and/or other materials provided with the â
â distribution. â
â â
â THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS "AS IS" AND â
â ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE â
â IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR â
â PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS â
â BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, â
â OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT â
â OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR â
â BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, â
â WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE â
â OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, â
â EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
#include "third_party/python/Modules/_decimal/libmpdec/bits.h"
#include "third_party/python/Modules/_decimal/libmpdec/difradix2.h"
#include "third_party/python/Modules/_decimal/libmpdec/mpdecimal.h"
#include "third_party/python/Modules/_decimal/libmpdec/numbertheory.h"
#include "third_party/python/Modules/_decimal/libmpdec/umodarith.h"
/* clang-format off */
asm(".ident\t\"\\n\\n\
libmpdec (BSD-2)\\n\
Copyright 2008-2016 Stefan Krah\"");
asm(".include \"libc/disclaimer.inc\"");
/* Bignum: The actual transform routine (decimation in frequency). */
/*
* Generate index pairs (x, bitreverse(x)) and carry out the permutation.
* n must be a power of two.
* Algorithm due to Brent/Lehmann, see Joerg Arndt, "Matters Computational",
* Chapter 1.14.4. [http://www.jjj.de/fxt/]
*/
static inline void
bitreverse_permute(mpd_uint_t a[], mpd_size_t n)
{
mpd_size_t x = 0;
mpd_size_t r = 0;
mpd_uint_t t;
do { /* Invariant: r = bitreverse(x) */
if (r > x) {
t = a[x];
a[x] = a[r];
a[r] = t;
}
/* Flip trailing consecutive 1 bits and the first zero bit
* that absorbs a possible carry. */
x += 1;
/* Mirror the operation on r: Flip n_trailing_zeros(x)+1
high bits of r. */
r ^= (n - (n >> (mpd_bsf(x)+1)));
/* The loop invariant is preserved. */
} while (x < n);
}
/* Fast Number Theoretic Transform, decimation in frequency. */
void
fnt_dif2(mpd_uint_t a[], mpd_size_t n, struct fnt_params *tparams)
{
mpd_uint_t *wtable = tparams->wtable;
mpd_uint_t umod;
mpd_uint_t u0, u1, v0, v1;
mpd_uint_t w, w0, w1, wstep;
mpd_size_t m, mhalf;
mpd_size_t j, r;
assert(ispower2(n));
assert(n >= 4);
SETMODULUS(tparams->modnum);
/* m == n */
mhalf = n / 2;
for (j = 0; j < mhalf; j += 2) {
w0 = wtable[j];
w1 = wtable[j+1];
u0 = a[j];
v0 = a[j+mhalf];
u1 = a[j+1];
v1 = a[j+1+mhalf];
a[j] = addmod(u0, v0, umod);
v0 = submod(u0, v0, umod);
a[j+1] = addmod(u1, v1, umod);
v1 = submod(u1, v1, umod);
MULMOD2(&v0, w0, &v1, w1);
a[j+mhalf] = v0;
a[j+1+mhalf] = v1;
}
wstep = 2;
for (m = n/2; m >= 2; m>>=1, wstep<<=1) {
mhalf = m / 2;
/* j == 0 */
for (r = 0; r < n; r += 2*m) {
u0 = a[r];
v0 = a[r+mhalf];
u1 = a[m+r];
v1 = a[m+r+mhalf];
a[r] = addmod(u0, v0, umod);
v0 = submod(u0, v0, umod);
a[m+r] = addmod(u1, v1, umod);
v1 = submod(u1, v1, umod);
a[r+mhalf] = v0;
a[m+r+mhalf] = v1;
}
for (j = 1; j < mhalf; j++) {
w = wtable[j*wstep];
for (r = 0; r < n; r += 2*m) {
u0 = a[r+j];
v0 = a[r+j+mhalf];
u1 = a[m+r+j];
v1 = a[m+r+j+mhalf];
a[r+j] = addmod(u0, v0, umod);
v0 = submod(u0, v0, umod);
a[m+r+j] = addmod(u1, v1, umod);
v1 = submod(u1, v1, umod);
MULMOD2C(&v0, &v1, w);
a[r+j+mhalf] = v0;
a[m+r+j+mhalf] = v1;
}
}
}
bitreverse_permute(a, n);
}
| 6,098 | 137 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Modules/_decimal/libmpdec/constants.h | #ifndef CONSTANTS_H
#define CONSTANTS_H
#include "third_party/python/Modules/_decimal/libmpdec/mpdecimal.h"
/* clang-format off */
#define MULMOD(a, b) x64_mulmod(a, b, umod)
#define MULMOD2C(a0, a1, w) x64_mulmod2c(a0, a1, w, umod)
#define MULMOD2(a0, b0, a1, b1) x64_mulmod2(a0, b0, a1, b1, umod)
#define POWMOD(base, exp) x64_powmod(base, exp, umod)
#define SETMODULUS(modnum) std_setmodulus(modnum, &umod)
#define SIZE3_NTT(x0, x1, x2, w3table) std_size3_ntt(x0, x1, x2, w3table, umod)
/* PentiumPro (or later) gcc inline asm */
extern const float MPD_TWO63;
extern const uint32_t mpd_invmoduli[3][3];
enum {P1, P2, P3};
extern const mpd_uint_t mpd_moduli[];
extern const mpd_uint_t mpd_roots[];
extern const mpd_size_t mpd_bits[];
extern const mpd_uint_t mpd_pow10[];
extern const mpd_uint_t INV_P1_MOD_P2;
extern const mpd_uint_t INV_P1P2_MOD_P3;
extern const mpd_uint_t LH_P1P2;
extern const mpd_uint_t UH_P1P2;
#endif /* CONSTANTS_H */
| 950 | 30 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Modules/_decimal/libmpdec/constants.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:8;coding:utf-8 -*-â
âvi: set net ft=c ts=4 sts=4 sw=4 fenc=utf-8 :viâ
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ¡
â Copyright (c) 2008-2016 Stefan Krah. All rights reserved. â
â â
â Redistribution and use in source and binary forms, with or without â
â modification, are permitted provided that the following conditions â
â are met: â
â â
â 1. Redistributions of source code must retain the above copyright â
â notice, this list of conditions and the following disclaimer. â
â â
â 2. Redistributions in binary form must reproduce the above copyright â
â notice, this list of conditions and the following disclaimer in â
â the documentation and/or other materials provided with the â
â distribution. â
â â
â THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS "AS IS" AND â
â ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE â
â IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR â
â PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS â
â BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, â
â OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT â
â OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR â
â BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, â
â WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE â
â OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, â
â EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
#include "third_party/python/Modules/_decimal/libmpdec/constants.h"
#include "third_party/python/Modules/_decimal/libmpdec/mpdecimal.h"
/* clang-format off */
asm(".ident\t\"\\n\\n\
libmpdec (BSD-2)\\n\
Copyright 2008-2016 Stefan Krah\"");
asm(".include \"libc/disclaimer.inc\"");
/* number-theory.c */
const mpd_uint_t mpd_moduli[3] = {
18446744069414584321ULL, 18446744056529682433ULL, 18446742974197923841ULL
};
const mpd_uint_t mpd_roots[3] = {7ULL, 10ULL, 19ULL};
/* crt.c */
const mpd_uint_t INV_P1_MOD_P2 = 18446744055098026669ULL;
const mpd_uint_t INV_P1P2_MOD_P3 = 287064143708160ULL;
const mpd_uint_t LH_P1P2 = 18446744052234715137ULL; /* (P1*P2) % 2^64 */
const mpd_uint_t UH_P1P2 = 18446744052234715141ULL; /* (P1*P2) / 2^64 */
/* transpose.c */
const mpd_size_t mpd_bits[64] = {
1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192, 16384,
32768, 65536, 131072, 262144, 524288, 1048576, 2097152, 4194304, 8388608,
16777216, 33554432, 67108864, 134217728, 268435456, 536870912, 1073741824,
2147483648ULL, 4294967296ULL, 8589934592ULL, 17179869184ULL, 34359738368ULL,
68719476736ULL, 137438953472ULL, 274877906944ULL, 549755813888ULL,
1099511627776ULL, 2199023255552ULL, 4398046511104, 8796093022208ULL,
17592186044416ULL, 35184372088832ULL, 70368744177664ULL, 140737488355328ULL,
281474976710656ULL, 562949953421312ULL, 1125899906842624ULL,
2251799813685248ULL, 4503599627370496ULL, 9007199254740992ULL,
18014398509481984ULL, 36028797018963968ULL, 72057594037927936ULL,
144115188075855872ULL, 288230376151711744ULL, 576460752303423488ULL,
1152921504606846976ULL, 2305843009213693952ULL, 4611686018427387904ULL,
9223372036854775808ULL
};
/* mpdecimal.c */
const mpd_uint_t mpd_pow10[MPD_RDIGITS+1] = {
1,10,100,1000,10000,100000,1000000,10000000,100000000,1000000000,
10000000000ULL,100000000000ULL,1000000000000ULL,10000000000000ULL,
100000000000000ULL,1000000000000000ULL,10000000000000000ULL,
100000000000000000ULL,1000000000000000000ULL,10000000000000000000ULL
};
/* magic number for constant division by MPD_RADIX */
const mpd_uint_t mprime_rdx = 15581492618384294730ULL;
const char *mpd_round_string[MPD_ROUND_GUARD] = {
"ROUND_UP", /* round away from 0 */
"ROUND_DOWN", /* round toward 0 (truncate) */
"ROUND_CEILING", /* round toward +infinity */
"ROUND_FLOOR", /* round toward -infinity */
"ROUND_HALF_UP", /* 0.5 is rounded up */
"ROUND_HALF_DOWN", /* 0.5 is rounded down */
"ROUND_HALF_EVEN", /* 0.5 is rounded to even */
"ROUND_05UP", /* round zero or five away from 0 */
"ROUND_TRUNC", /* truncate, but set infinity */
};
const char *mpd_clamp_string[MPD_CLAMP_GUARD] = {
"CLAMP_DEFAULT",
"CLAMP_IEEE_754"
};
| 5,639 | 95 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Modules/_decimal/libmpdec/difradix2.h | #ifndef DIF_RADIX2_H
#define DIF_RADIX2_H
#include "third_party/python/Modules/_decimal/libmpdec/mpdecimal.h"
#include "third_party/python/Modules/_decimal/libmpdec/numbertheory.h"
void fnt_dif2(mpd_uint_t[], mpd_size_t, struct fnt_params *);
#endif
| 252 | 9 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Modules/_decimal/libmpdec/context.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:8;coding:utf-8 -*-â
âvi: set net ft=c ts=4 sts=4 sw=4 fenc=utf-8 :viâ
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ¡
â Copyright (c) 2008-2016 Stefan Krah. All rights reserved. â
â â
â Redistribution and use in source and binary forms, with or without â
â modification, are permitted provided that the following conditions â
â are met: â
â â
â 1. Redistributions of source code must retain the above copyright â
â notice, this list of conditions and the following disclaimer. â
â â
â 2. Redistributions in binary form must reproduce the above copyright â
â notice, this list of conditions and the following disclaimer in â
â the documentation and/or other materials provided with the â
â distribution. â
â â
â THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS "AS IS" AND â
â ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE â
â IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR â
â PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS â
â BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, â
â OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT â
â OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR â
â BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, â
â WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE â
â OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, â
â EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
#include "libc/calls/calls.h"
#include "libc/sysv/consts/sig.h"
#include "third_party/python/Modules/_decimal/libmpdec/mpdecimal.h"
/* clang-format off */
asm(".ident\t\"\\n\\n\
libmpdec (BSD-2)\\n\
Copyright 2008-2016 Stefan Krah\"");
asm(".include \"libc/disclaimer.inc\"");
void
mpd_dflt_traphandler(mpd_context_t *ctx)
{
(void)ctx;
raise(SIGFPE);
}
void (* mpd_traphandler)(mpd_context_t *) = mpd_dflt_traphandler;
/* Set guaranteed minimum number of coefficient words. The function may
be used once at program start. Setting MPD_MINALLOC to out-of-bounds
values is a catastrophic error, so in that case the function exits rather
than relying on the user to check a return value. */
void
mpd_setminalloc(mpd_ssize_t n)
{
static int minalloc_is_set = 0;
if (minalloc_is_set) {
mpd_err_warn("mpd_setminalloc: ignoring request to set "
"MPD_MINALLOC a second time\n");
return;
}
if (n < MPD_MINALLOC_MIN || n > MPD_MINALLOC_MAX) {
mpd_err_fatal("illegal value for MPD_MINALLOC"); /* GCOV_NOT_REACHED */
}
MPD_MINALLOC = n;
minalloc_is_set = 1;
}
void
mpd_init(mpd_context_t *ctx, mpd_ssize_t prec)
{
mpd_ssize_t ideal_minalloc;
mpd_defaultcontext(ctx);
if (!mpd_qsetprec(ctx, prec)) {
mpd_addstatus_raise(ctx, MPD_Invalid_context);
return;
}
ideal_minalloc = 2 * ((prec+MPD_RDIGITS-1) / MPD_RDIGITS);
if (ideal_minalloc < MPD_MINALLOC_MIN) ideal_minalloc = MPD_MINALLOC_MIN;
if (ideal_minalloc > MPD_MINALLOC_MAX) ideal_minalloc = MPD_MINALLOC_MAX;
mpd_setminalloc(ideal_minalloc);
}
void
mpd_maxcontext(mpd_context_t *ctx)
{
ctx->prec=MPD_MAX_PREC;
ctx->emax=MPD_MAX_EMAX;
ctx->emin=MPD_MIN_EMIN;
ctx->round=MPD_ROUND_HALF_EVEN;
ctx->traps=MPD_Traps;
ctx->status=0;
ctx->newtrap=0;
ctx->clamp=0;
ctx->allcr=1;
}
void
mpd_defaultcontext(mpd_context_t *ctx)
{
ctx->prec=2*MPD_RDIGITS;
ctx->emax=MPD_MAX_EMAX;
ctx->emin=MPD_MIN_EMIN;
ctx->round=MPD_ROUND_HALF_UP;
ctx->traps=MPD_Traps;
ctx->status=0;
ctx->newtrap=0;
ctx->clamp=0;
ctx->allcr=1;
}
void
mpd_basiccontext(mpd_context_t *ctx)
{
ctx->prec=9;
ctx->emax=MPD_MAX_EMAX;
ctx->emin=MPD_MIN_EMIN;
ctx->round=MPD_ROUND_HALF_UP;
ctx->traps=MPD_Traps|MPD_Clamped;
ctx->status=0;
ctx->newtrap=0;
ctx->clamp=0;
ctx->allcr=1;
}
int
mpd_ieee_context(mpd_context_t *ctx, int bits)
{
if (bits <= 0 || bits > MPD_IEEE_CONTEXT_MAX_BITS || bits % 32) {
return -1;
}
ctx->prec = 9 * (bits/32) - 2;
ctx->emax = 3 * ((mpd_ssize_t)1<<(bits/16+3));
ctx->emin = 1 - ctx->emax;
ctx->round=MPD_ROUND_HALF_EVEN;
ctx->traps=0;
ctx->status=0;
ctx->newtrap=0;
ctx->clamp=1;
ctx->allcr=1;
return 0;
}
mpd_ssize_t
mpd_getprec(const mpd_context_t *ctx)
{
return ctx->prec;
}
mpd_ssize_t
mpd_getemax(const mpd_context_t *ctx)
{
return ctx->emax;
}
mpd_ssize_t
mpd_getemin(const mpd_context_t *ctx)
{
return ctx->emin;
}
int
mpd_getround(const mpd_context_t *ctx)
{
return ctx->round;
}
uint32_t
mpd_gettraps(const mpd_context_t *ctx)
{
return ctx->traps;
}
uint32_t
mpd_getstatus(const mpd_context_t *ctx)
{
return ctx->status;
}
int
mpd_getclamp(const mpd_context_t *ctx)
{
return ctx->clamp;
}
int
mpd_getcr(const mpd_context_t *ctx)
{
return ctx->allcr;
}
int
mpd_qsetprec(mpd_context_t *ctx, mpd_ssize_t prec)
{
if (prec <= 0 || prec > MPD_MAX_PREC) {
return 0;
}
ctx->prec = prec;
return 1;
}
int
mpd_qsetemax(mpd_context_t *ctx, mpd_ssize_t emax)
{
if (emax < 0 || emax > MPD_MAX_EMAX) {
return 0;
}
ctx->emax = emax;
return 1;
}
int
mpd_qsetemin(mpd_context_t *ctx, mpd_ssize_t emin)
{
if (emin > 0 || emin < MPD_MIN_EMIN) {
return 0;
}
ctx->emin = emin;
return 1;
}
int
mpd_qsetround(mpd_context_t *ctx, int round)
{
if (!(0 <= round && round < MPD_ROUND_GUARD)) {
return 0;
}
ctx->round = round;
return 1;
}
int
mpd_qsettraps(mpd_context_t *ctx, uint32_t traps)
{
if (traps > MPD_Max_status) {
return 0;
}
ctx->traps = traps;
return 1;
}
int
mpd_qsetstatus(mpd_context_t *ctx, uint32_t flags)
{
if (flags > MPD_Max_status) {
return 0;
}
ctx->status = flags;
return 1;
}
int
mpd_qsetclamp(mpd_context_t *ctx, int c)
{
if (c != 0 && c != 1) {
return 0;
}
ctx->clamp = c;
return 1;
}
int
mpd_qsetcr(mpd_context_t *ctx, int c)
{
if (c != 0 && c != 1) {
return 0;
}
ctx->allcr = c;
return 1;
}
void
mpd_addstatus_raise(mpd_context_t *ctx, uint32_t flags)
{
ctx->status |= flags;
if (flags&ctx->traps) {
ctx->newtrap = (flags&ctx->traps);
mpd_traphandler(ctx);
}
}
| 7,645 | 281 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Modules/_decimal/libmpdec/convolute.h | #ifndef CONVOLUTE_H
#define CONVOLUTE_H
#include "third_party/python/Modules/_decimal/libmpdec/mpdecimal.h"
#define SIX_STEP_THRESHOLD 4096
int fnt_convolute(mpd_uint_t *, mpd_uint_t *, mpd_size_t, int);
int fnt_autoconvolute(mpd_uint_t *, mpd_size_t, int);
#endif
| 268 | 11 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Modules/_decimal/libmpdec/transpose.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:8;coding:utf-8 -*-â
âvi: set net ft=c ts=4 sts=4 sw=4 fenc=utf-8 :viâ
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ¡
â Copyright (c) 2008-2016 Stefan Krah. All rights reserved. â
â â
â Redistribution and use in source and binary forms, with or without â
â modification, are permitted provided that the following conditions â
â are met: â
â â
â 1. Redistributions of source code must retain the above copyright â
â notice, this list of conditions and the following disclaimer. â
â â
â 2. Redistributions in binary form must reproduce the above copyright â
â notice, this list of conditions and the following disclaimer in â
â the documentation and/or other materials provided with the â
â distribution. â
â â
â THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS "AS IS" AND â
â ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE â
â IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR â
â PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS â
â BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, â
â OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT â
â OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR â
â BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, â
â WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE â
â OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, â
â EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
#include "libc/mem/mem.h"
#include "libc/mem/gc.internal.h"
#include "third_party/python/Modules/_decimal/libmpdec/bits.h"
#include "third_party/python/Modules/_decimal/libmpdec/constants.h"
#include "third_party/python/Modules/_decimal/libmpdec/mpdecimal.h"
#include "third_party/python/Modules/_decimal/libmpdec/transpose.h"
#include "third_party/python/Modules/_decimal/libmpdec/typearith.h"
/* clang-format off */
asm(".ident\t\"\\n\\n\
libmpdec (BSD-2)\\n\
Copyright 2008-2016 Stefan Krah\"");
asm(".include \"libc/disclaimer.inc\"");
#define BUFSIZE 4096
#define SIDE 128
/* Bignum: The transpose functions are used for very large transforms
in sixstep.c and fourstep.c. */
/* Definition of the matrix transpose */
void
std_trans(mpd_uint_t dest[], mpd_uint_t src[], mpd_size_t rows, mpd_size_t cols)
{
mpd_size_t idest, isrc;
mpd_size_t r, c;
for (r = 0; r < rows; r++) {
isrc = r * cols;
idest = r;
for (c = 0; c < cols; c++) {
dest[idest] = src[isrc];
isrc += 1;
idest += rows;
}
}
}
/*
* Swap half-rows of 2^n * (2*2^n) matrix.
* FORWARD_CYCLE: even/odd permutation of the halfrows.
* BACKWARD_CYCLE: reverse the even/odd permutation.
*/
static int
swap_halfrows_pow2(mpd_uint_t *matrix, mpd_size_t rows, mpd_size_t cols, int dir)
{
mpd_uint_t *buf1 = gc(malloc(BUFSIZE*sizeof(mpd_uint_t)));
mpd_uint_t *buf2 = gc(malloc(BUFSIZE*sizeof(mpd_uint_t)));
mpd_uint_t *readbuf, *writebuf, *hp;
mpd_size_t *done, dbits;
mpd_size_t b = BUFSIZE, stride;
mpd_size_t hn, hmax; /* halfrow number */
mpd_size_t m, r=0;
mpd_size_t offset;
mpd_size_t next;
assert(cols == mul_size_t(2, rows));
if (dir == FORWARD_CYCLE) {
r = rows;
}
else if (dir == BACKWARD_CYCLE) {
r = 2;
}
else {
abort(); /* GCOV_NOT_REACHED */
}
m = cols - 1;
hmax = rows; /* cycles start at odd halfrows */
dbits = 8 * sizeof *done;
if ((done = mpd_calloc(hmax/(sizeof *done) + 1, sizeof *done)) == NULL) {
return 0;
}
for (hn = 1; hn <= hmax; hn += 2) {
if (done[hn/dbits] & mpd_bits[hn%dbits]) {
continue;
}
readbuf = buf1; writebuf = buf2;
for (offset = 0; offset < cols/2; offset += b) {
stride = (offset + b < cols/2) ? b : cols/2-offset;
hp = matrix + hn*cols/2;
memcpy(readbuf, hp+offset, stride*(sizeof *readbuf));
pointerswap(&readbuf, &writebuf);
next = mulmod_size_t(hn, r, m);
hp = matrix + next*cols/2;
while (next != hn) {
memcpy(readbuf, hp+offset, stride*(sizeof *readbuf));
memcpy(hp+offset, writebuf, stride*(sizeof *writebuf));
pointerswap(&readbuf, &writebuf);
done[next/dbits] |= mpd_bits[next%dbits];
next = mulmod_size_t(next, r, m);
hp = matrix + next*cols/2;
}
memcpy(hp+offset, writebuf, stride*(sizeof *writebuf));
done[hn/dbits] |= mpd_bits[hn%dbits];
}
}
mpd_free(done);
return 1;
}
/* In-place transpose of a square matrix */
static inline void
squaretrans(mpd_uint_t *buf, mpd_size_t cols)
{
mpd_uint_t tmp;
mpd_size_t idest, isrc;
mpd_size_t r, c;
for (r = 0; r < cols; r++) {
c = r+1;
isrc = r*cols + c;
idest = c*cols + r;
for (c = r+1; c < cols; c++) {
tmp = buf[isrc];
buf[isrc] = buf[idest];
buf[idest] = tmp;
isrc += 1;
idest += cols;
}
}
}
/*
* Transpose 2^n * 2^n matrix. For cache efficiency, the matrix is split into
* square blocks with side length 'SIDE'. First, the blocks are transposed,
* then a square transposition is done on each individual block.
*/
static void
squaretrans_pow2(mpd_uint_t *matrix, mpd_size_t size)
{
mpd_uint_t *buf1 = gc(malloc(SIDE*SIDE*sizeof(mpd_uint_t)));
mpd_uint_t *buf2 = gc(malloc(SIDE*SIDE*sizeof(mpd_uint_t)));
mpd_uint_t *to, *from;
mpd_size_t b = size;
mpd_size_t r, c;
mpd_size_t i;
while (b > SIDE) b >>= 1;
for (r = 0; r < size; r += b) {
for (c = r; c < size; c += b) {
from = matrix + r*size + c;
to = buf1;
for (i = 0; i < b; i++) {
memcpy(to, from, b*(sizeof *to));
from += size;
to += b;
}
squaretrans(buf1, b);
if (r == c) {
to = matrix + r*size + c;
from = buf1;
for (i = 0; i < b; i++) {
memcpy(to, from, b*(sizeof *to));
from += b;
to += size;
}
continue;
}
else {
from = matrix + c*size + r;
to = buf2;
for (i = 0; i < b; i++) {
memcpy(to, from, b*(sizeof *to));
from += size;
to += b;
}
squaretrans(buf2, b);
to = matrix + c*size + r;
from = buf1;
for (i = 0; i < b; i++) {
memcpy(to, from, b*(sizeof *to));
from += b;
to += size;
}
to = matrix + r*size + c;
from = buf2;
for (i = 0; i < b; i++) {
memcpy(to, from, b*(sizeof *to));
from += b;
to += size;
}
}
}
}
}
/*
* In-place transposition of a 2^n x 2^n or a 2^n x (2*2^n)
* or a (2*2^n) x 2^n matrix.
*/
int
transpose_pow2(mpd_uint_t *matrix, mpd_size_t rows, mpd_size_t cols)
{
mpd_size_t size = mul_size_t(rows, cols);
assert(ispower2(rows));
assert(ispower2(cols));
if (cols == rows) {
squaretrans_pow2(matrix, rows);
}
else if (cols == mul_size_t(2, rows)) {
if (!swap_halfrows_pow2(matrix, rows, cols, FORWARD_CYCLE)) {
return 0;
}
squaretrans_pow2(matrix, rows);
squaretrans_pow2(matrix+(size/2), rows);
}
else if (rows == mul_size_t(2, cols)) {
squaretrans_pow2(matrix, cols);
squaretrans_pow2(matrix+(size/2), cols);
if (!swap_halfrows_pow2(matrix, cols, rows, BACKWARD_CYCLE)) {
return 0;
}
}
else {
unreachable;
}
return 1;
}
| 9,344 | 244 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Modules/_decimal/libmpdec/mpalloc.h | #ifndef MPALLOC_H
#define MPALLOC_H
#include "third_party/python/Modules/_decimal/libmpdec/mpdecimal.h"
int mpd_switch_to_dyn(mpd_t *, mpd_ssize_t, uint32_t *);
int mpd_switch_to_dyn_zero(mpd_t *, mpd_ssize_t, uint32_t *);
int mpd_realloc_dyn(mpd_t *, mpd_ssize_t, uint32_t *);
#endif
| 287 | 10 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Modules/_decimal/libmpdec/fnt.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:8;coding:utf-8 -*-â
âvi: set net ft=c ts=4 sts=4 sw=4 fenc=utf-8 :viâ
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ¡
â Copyright (c) 2008-2016 Stefan Krah. All rights reserved. â
â â
â Redistribution and use in source and binary forms, with or without â
â modification, are permitted provided that the following conditions â
â are met: â
â â
â 1. Redistributions of source code must retain the above copyright â
â notice, this list of conditions and the following disclaimer. â
â â
â 2. Redistributions in binary form must reproduce the above copyright â
â notice, this list of conditions and the following disclaimer in â
â the documentation and/or other materials provided with the â
â distribution. â
â â
â THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS "AS IS" AND â
â ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE â
â IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR â
â PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS â
â BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, â
â OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT â
â OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR â
â BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, â
â WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE â
â OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, â
â EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
#include "libc/assert.h"
#include "third_party/python/Modules/_decimal/libmpdec/bits.h"
#include "third_party/python/Modules/_decimal/libmpdec/difradix2.h"
#include "third_party/python/Modules/_decimal/libmpdec/fnt.h"
#include "third_party/python/Modules/_decimal/libmpdec/mpdecimal.h"
#include "third_party/python/Modules/_decimal/libmpdec/numbertheory.h"
/* clang-format off */
asm(".ident\t\"\\n\\n\
libmpdec (BSD-2)\\n\
Copyright 2008-2016 Stefan Krah\"");
asm(".include \"libc/disclaimer.inc\"");
/* Bignum: Fast transform for medium-sized coefficients. */
/* forward transform, sign = -1 */
int
std_fnt(mpd_uint_t *a, mpd_size_t n, int modnum)
{
struct fnt_params *tparams;
assert(ispower2(n));
assert(n >= 4);
assert(n <= 3*MPD_MAXTRANSFORM_2N);
if ((tparams = _mpd_init_fnt_params(n, -1, modnum)) == NULL) {
return 0;
}
fnt_dif2(a, n, tparams);
mpd_free(tparams);
return 1;
}
/* reverse transform, sign = 1 */
int
std_inv_fnt(mpd_uint_t *a, mpd_size_t n, int modnum)
{
struct fnt_params *tparams;
assert(ispower2(n));
assert(n >= 4);
assert(n <= 3*MPD_MAXTRANSFORM_2N);
if ((tparams = _mpd_init_fnt_params(n, 1, modnum)) == NULL) {
return 0;
}
fnt_dif2(a, n, tparams);
mpd_free(tparams);
return 1;
}
| 4,071 | 76 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Modules/_decimal/libmpdec/fourstep.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:8;coding:utf-8 -*-â
âvi: set net ft=c ts=4 sts=4 sw=4 fenc=utf-8 :viâ
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ¡
â Copyright (c) 2008-2016 Stefan Krah. All rights reserved. â
â â
â Redistribution and use in source and binary forms, with or without â
â modification, are permitted provided that the following conditions â
â are met: â
â â
â 1. Redistributions of source code must retain the above copyright â
â notice, this list of conditions and the following disclaimer. â
â â
â 2. Redistributions in binary form must reproduce the above copyright â
â notice, this list of conditions and the following disclaimer in â
â the documentation and/or other materials provided with the â
â distribution. â
â â
â THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS "AS IS" AND â
â ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE â
â IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR â
â PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS â
â BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, â
â OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT â
â OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR â
â BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, â
â WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE â
â OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, â
â EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
#include "third_party/python/Modules/_decimal/libmpdec/fourstep.h"
#include "third_party/python/Modules/_decimal/libmpdec/mpdecimal.h"
#include "third_party/python/Modules/_decimal/libmpdec/numbertheory.h"
#include "third_party/python/Modules/_decimal/libmpdec/sixstep.h"
#include "third_party/python/Modules/_decimal/libmpdec/transpose.h"
#include "third_party/python/Modules/_decimal/libmpdec/umodarith.h"
/* clang-format off */
asm(".ident\t\"\\n\\n\
libmpdec (BSD-2)\\n\
Copyright 2008-2016 Stefan Krah\"");
asm(".include \"libc/disclaimer.inc\"");
/*
Cache Efficient Matrix Fourier Transform
for arrays of form 3Ã2â¿
The Matrix Fourier Transform
ââââââââââââââââââââââââââââ
In libmpdec, the Matrix Fourier Transform [1] is called four-step
transform after a variant that appears in [2]. The algorithm requires
that the input array can be viewed as an R*C matrix.
All operations are done modulo p. For readability, the proofs drop all
instances of (mod p).
Algorithm four-step (forward transform)
âââââââââââââââââââââââââââââââââââââââ
a := input array
d := len(a) = R * C
p := prime
w := primitive root of unity of the prime field
r := w**((p-1)/d)
A := output array
1) Apply a length R FNT to each column.
2) Multiply each matrix element (addressed by j*C+m) by r**(j*m).
3) Apply a length C FNT to each row.
4) Transpose the matrix.
Proof (forward transform)
âââââââââââââââââââââââââ
The algorithm can be derived starting from the regular definition of
the finite-field transform of length d:
d-1
,ââââ
\
A[k] = | a[l] à r**(k à l)
/
`ââââ
l = 0
The sum can be rearranged into the sum of the sums of columns:
C-1 R-1
,ââââ ,ââââ
\ \
= | | a[i à C + j] à r**(k à (i à C + j))
/ /
`ââââ `ââââ
j = 0 i = 0
Extracting a constant from the inner sum:
C-1 R-1
,ââââ ,ââââ
\ \
= | ráµÃj à | a[i à C + j] à r**(k à i à C)
/ /
`ââââ `ââââ
j = 0 i = 0
Without any loss of generality, let k = n à R + m,
where n < C and m < R:
C-1 R-1
,ââââ ,ââââ
\ \
A[nÃR+m] = | r**(RÃnÃj) Ã r**(mÃj) Ã | a[iÃC+j] Ã r**(RÃCÃnÃi) Ã r**(CÃmÃi)
/ /
`ââââ `ââââ
j = 0 i = 0
Since r = w ** ((p-1) / (RÃC)):
a) r**(RÃCÃnÃi) = w**((p-1)ÃnÃi) = 1
b) r**(CÃmÃi) = w**((p-1) / R) ** (mÃi) = r_R ** (mÃi)
c) r**(RÃnÃj) = w**((p-1) / C) ** (nÃj) = r_C ** (nÃj)
r_R := root of the subfield of length R.
r_C := root of the subfield of length C.
C-1 R-1
,ââââ ,ââââ
\ \
A[nÃR+m] = | r_C**(nÃj) Ã [ r**(mÃj) Ã | a[iÃC+j] Ã r_R**(mÃi) ]
/ ^ /
`ââââ | `ââââ 1) transform the columns
j = 0 | i = 0
^ |
| `-- 2) multiply
|
`-- 3) transform the rows
Note that the entire RHS is a function of n and m and that the results
for each pair (n, m) are stored in Fortran order.
Let the term in square brackets be ð(m, j). Step 1) and 2) precalculate
the term for all (m, j). After that, the original matrix is now a lookup
table with the mth element in the jth column at location m à C + j.
Let the complete RHS be g(m, n). Step 3) does an in-place transform of
length n on all rows. After that, the original matrix is now a lookup
table with the mth element in the nth column at location m à C + n.
But each (m, n) pair should be written to location n à R + m. Therefore,
step 4) transposes the result of step 3).
Algorithm four-step (inverse transform)
âââââââââââââââââââââââââââââââââââââââ
A := input array
d := len(A) = R Ã C
p := prime
dâ² := dâ½áµâ»Â²â¾ # inverse of d
w := primitive root of unity of the prime field
r := w**((p-1)/d) # root of the subfield
râ² := w**((p-1) - (p-1)/d) # inverse of r
a := output array
0) View the matrix as a CÃR matrix.
1) Transpose the matrix, producing an RÃC matrix.
2) Apply a length C FNT to each row.
3) Multiply each matrix element (addressed by iÃC+n) by r**(iÃn).
4) Apply a length R FNT to each column.
Proof (inverse transform)
âââââââââââââââââââââââââ
The algorithm can be derived starting from the regular definition of
the finite-field inverse transform of length d:
d-1
,ââââ
\
a[k] = dⲠà | A[l] à rⲠ** (k à l)
/
`ââââ
l = 0
The sum can be rearranged into the sum of the sums of columns. Note
that at this stage we still have a C*R matrix, so C denotes the number
of rows:
R-1 C-1
,ââââ ,ââââ
\ \
= dⲠà | | a[j à R + i] à rⲠ** (k à (j à R + i))
/ /
`ââââ `ââââ
i = 0 j = 0
Extracting a constant from the inner sum:
R-1 C-1
,ââââ ,ââââ
\ \
= dâ² Ã | râ² ** (kÃi) à | a[j à R + i] à râ² ** (k à j à R)
/ /
`ââââ `ââââ
i = 0 j = 0
Without any loss of generality, let k = m * C + n,
where m < R and n < C:
R-1 C-1
,ââââ ,ââââ
\ \
A[mÃC+n] = dâ² Ã | râ² ** (CÃmÃi) Ã râ² ** (nÃi) Ã | a[jÃR+i] Ã râ² ** (RÃCÃmÃj) Ã râ² ** (RÃnÃj)
/ /
`ââââ `ââââ
i = 0 j = 0
Since râ² = w**((p-1) - (p-1)/d) and d = RÃC:
a) râ² ** (RÃCÃmÃj) = w**((p-1)ÃRÃCÃmÃj - (p-1)ÃmÃj) = 1
b) râ² ** (CÃmÃi) = w**((p-1)ÃC - (p-1)/R) ** (mÃi) = r_Râ² ** (mÃi)
c) râ² ** (RÃnÃj) = r_Câ² ** (nÃj)
d) dâ² = dâ½áµâ»Â²â¾ = (RÃC)â½áµâ»Â²â¾ = Râ½áµâ»Â²â¾ à Câ½áµâ»Â²â¾ = Râ² Ã Câ²
r_Râ² := inverse of the root of the subfield of length R.
r_Câ² := inverse of the root of the subfield of length C.
Râ² := inverse of R
Câ² := inverse of C
R-1 C-1
,ââââ ,ââââ 2) transform the rows of a^T
\ \
A[mÃC+n] = Râ² Ã | r_Râ² ** (mÃi) Ã [ râ² ** (nÃi) Ã Câ² Ã | a[jÃR+i] Ã r_Câ² ** (nÃj) ]
/ ^ / ^
`ââââ | `ââââ |
i = 0 | j = 0 |
^ | `ââ 1) Transpose input matrix
| `ââ 3) multiply to address elements by
| i à C + j
`ââ 3) transform the columns
Note that the entire RHS is a function of m and n and that the results
for each pair (m, n) are stored in C order.
Let the term in square brackets be ð(n, i). Without step 1), the sum
would perform a length C transform on the columns of the input matrix.
This is a) inefficient and b) the results are needed in C order, so
step 1) exchanges rows and columns.
Step 2) and 3) precalculate ð(n, i) for all (n, i). After that, the
original matrix is now a lookup table with the ith element in the nth
column at location i à C + n.
Let the complete RHS be g(m, n). Step 4) does an in-place transform of
length m on all columns. After that, the original matrix is now a lookup
table with the mth element in the nth column at location m à C + n,
which means that all A[k] = A[m à C + n] are in the correct order.
ââ
[1] Joerg Arndt: "Matters Computational"
http://www.jjj.de/fxt/
[2] David H. Bailey: FFTs in External or Hierarchical Memory
http://crd.lbl.gov/~dhbailey/dhbpapers/
*/
static inline void
std_size3_ntt(mpd_uint_t *x1, mpd_uint_t *x2, mpd_uint_t *x3,
mpd_uint_t w3table[3], mpd_uint_t umod)
{
mpd_uint_t r1, r2;
mpd_uint_t w;
mpd_uint_t s, tmp;
/* k = 0 -> w = 1 */
s = *x1;
s = addmod(s, *x2, umod);
s = addmod(s, *x3, umod);
r1 = s;
/* k = 1 */
s = *x1;
w = w3table[1];
tmp = MULMOD(*x2, w);
s = addmod(s, tmp, umod);
w = w3table[2];
tmp = MULMOD(*x3, w);
s = addmod(s, tmp, umod);
r2 = s;
/* k = 2 */
s = *x1;
w = w3table[2];
tmp = MULMOD(*x2, w);
s = addmod(s, tmp, umod);
w = w3table[1];
tmp = MULMOD(*x3, w);
s = addmod(s, tmp, umod);
*x3 = s;
*x2 = r2;
*x1 = r1;
}
/* forward transform, sign = -1; transform length = 3 * 2**n */
int
four_step_fnt(mpd_uint_t *a, mpd_size_t n, int modnum)
{
mpd_size_t R = 3; /* number of rows */
mpd_size_t C = n / 3; /* number of columns */
mpd_uint_t w3table[3];
mpd_uint_t kernel, w0, w1, wstep;
mpd_uint_t *s, *p0, *p1, *p2;
mpd_uint_t umod;
mpd_size_t i, k;
assert(n >= 48);
assert(n <= 3*MPD_MAXTRANSFORM_2N);
/* Length R transform on the columns. */
SETMODULUS(modnum);
_mpd_init_w3table(w3table, -1, modnum);
for (p0=a, p1=p0+C, p2=p0+2*C; p0<a+C; p0++,p1++,p2++) {
SIZE3_NTT(p0, p1, p2, w3table);
}
/* Multiply each matrix element (addressed by i*C+k) by r**(i*k). */
kernel = _mpd_getkernel(n, -1, modnum);
for (i = 1; i < R; i++) {
w0 = 1; /* r**(i*0): initial value for k=0 */
w1 = POWMOD(kernel, i); /* r**(i*1): initial value for k=1 */
wstep = MULMOD(w1, w1); /* r**(2*i) */
for (k = 0; k < C-1; k += 2) {
mpd_uint_t x0 = a[i*C+k];
mpd_uint_t x1 = a[i*C+k+1];
MULMOD2(&x0, w0, &x1, w1);
MULMOD2C(&w0, &w1, wstep); /* r**(i*(k+2)) = r**(i*k) * r**(2*i) */
a[i*C+k] = x0;
a[i*C+k+1] = x1;
}
}
/* Length C transform on the rows. */
for (s = a; s < a+n; s += C) {
if (!six_step_fnt(s, C, modnum)) {
return 0;
}
}
#if 0
/* An unordered transform is sufficient for convolution. */
/* Transpose the matrix. */
transpose_3xpow2(a, R, C);
#endif
return 1;
}
/* backward transform, sign = 1; transform length = 3 * 2**n */
int
inv_four_step_fnt(mpd_uint_t *a, mpd_size_t n, int modnum)
{
mpd_size_t R = 3; /* number of rows */
mpd_size_t C = n / 3; /* number of columns */
mpd_uint_t w3table[3];
mpd_uint_t kernel, w0, w1, wstep;
mpd_uint_t *s, *p0, *p1, *p2;
mpd_uint_t umod;
mpd_size_t i, k;
assert(n >= 48);
assert(n <= 3*MPD_MAXTRANSFORM_2N);
#if 0
/* An unordered transform is sufficient for convolution. */
/* Transpose the matrix, producing an R*C matrix. */
transpose_3xpow2(a, C, R);
#endif
/* Length C transform on the rows. */
for (s = a; s < a+n; s += C) {
if (!inv_six_step_fnt(s, C, modnum)) {
return 0;
}
}
/* Multiply each matrix element (addressed by i*C+k) by r**(i*k). */
SETMODULUS(modnum);
kernel = _mpd_getkernel(n, 1, modnum);
for (i = 1; i < R; i++) {
w0 = 1;
w1 = POWMOD(kernel, i);
wstep = MULMOD(w1, w1);
for (k = 0; k < C; k += 2) {
mpd_uint_t x0 = a[i*C+k];
mpd_uint_t x1 = a[i*C+k+1];
MULMOD2(&x0, w0, &x1, w1);
MULMOD2C(&w0, &w1, wstep);
a[i*C+k] = x0;
a[i*C+k+1] = x1;
}
}
/* Length R transform on the columns. */
_mpd_init_w3table(w3table, 1, modnum);
for (p0=a, p1=p0+C, p2=p0+2*C; p0<a+C; p0++,p1++,p2++) {
SIZE3_NTT(p0, p1, p2, w3table);
}
return 1;
}
| 16,350 | 427 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Modules/_decimal/libmpdec/numbertheory.h | #ifndef NUMBER_THEORY_H
#define NUMBER_THEORY_H
#include "third_party/python/Modules/_decimal/libmpdec/constants.h"
#include "third_party/python/Modules/_decimal/libmpdec/mpdecimal.h"
struct fnt_params {
int modnum;
mpd_uint_t modulus;
mpd_uint_t kernel;
mpd_uint_t wtable[];
};
mpd_uint_t _mpd_getkernel(mpd_uint_t, int, int);
struct fnt_params *_mpd_init_fnt_params(mpd_size_t, int, int);
void _mpd_init_w3table(mpd_uint_t[3], int, int);
static inline void std_setmodulus(int modnum, mpd_uint_t *umod) {
*umod = mpd_moduli[modnum];
}
#endif
| 557 | 22 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Modules/_decimal/libmpdec/mpdecimal.h | #ifndef MPDECIMAL_H
#define MPDECIMAL_H
#include "libc/fmt/conv.h"
#include "libc/inttypes.h"
#include "libc/limits.h"
#include "libc/runtime/runtime.h"
#include "libc/stdio/stdio.h"
#include "third_party/python/pyconfig.h"
COSMOPOLITAN_C_START_
/* clang-format off */
#define MPD_VERSION "2.4.2"
#define MPD_MAJOR_VERSION 2
#define MPD_MINOR_VERSION 4
#define MPD_MICRO_VERSION 2
#define MPD_VERSION_HEX ((MPD_MAJOR_VERSION << 24) | \
(MPD_MINOR_VERSION << 16) | \
(MPD_MICRO_VERSION << 8))
const char *mpd_version(void);
#define MPD_UINT_MAX UINT64_MAX
#define MPD_BITS_PER_UINT 64
typedef uint64_t mpd_uint_t; /* unsigned mod type */
#define MPD_SIZE_MAX SIZE_MAX
typedef size_t mpd_size_t; /* unsigned size type */
/* type for exp, digits, len, prec */
#define MPD_SSIZE_MAX INT64_MAX
#define MPD_SSIZE_MIN INT64_MIN
typedef int64_t mpd_ssize_t;
#define _mpd_strtossize strtoll
#define MPD_RADIX 10000000000000000000ULL /* 10**19 */
#define MPD_RDIGITS 19
#define MPD_MAX_POW10 19
#define MPD_EXPDIGITS 19 /* MPD_EXPDIGITS <= MPD_RDIGITS+1 */
#define MPD_MAXTRANSFORM_2N 4294967296ULL /* 2**32 */
#define MPD_MAX_PREC 999999999999999999LL
#define MPD_MAX_PREC_LOG2 64
#define MPD_ELIMIT 1000000000000000000LL
#define MPD_MAX_EMAX 999999999999999999LL /* ELIMIT-1 */
#define MPD_MIN_EMIN (-999999999999999999LL) /* -EMAX */
#define MPD_MIN_ETINY (MPD_MIN_EMIN-(MPD_MAX_PREC-1))
#define MPD_EXP_INF 2000000000000000001LL
#define MPD_EXP_CLAMP (-4000000000000000001LL)
#define MPD_MAXIMPORT 105263157894736842L /* ceil((2*MPD_MAX_PREC)/MPD_RDIGITS) */
/* conversion specifiers */
#define PRI_mpd_uint_t PRIu64
#define PRI_mpd_ssize_t PRIi64
#if MPD_SIZE_MAX != MPD_UINT_MAX
#error "unsupported platform: need mpd_size_t == mpd_uint_t"
#endif
/******************************************************************************/
/* Context */
/******************************************************************************/
enum {
MPD_ROUND_UP, /* round away from 0 */
MPD_ROUND_DOWN, /* round toward 0 (truncate) */
MPD_ROUND_CEILING, /* round toward +infinity */
MPD_ROUND_FLOOR, /* round toward -infinity */
MPD_ROUND_HALF_UP, /* 0.5 is rounded up */
MPD_ROUND_HALF_DOWN, /* 0.5 is rounded down */
MPD_ROUND_HALF_EVEN, /* 0.5 is rounded to even */
MPD_ROUND_05UP, /* round zero or five away from 0 */
MPD_ROUND_TRUNC, /* truncate, but set infinity */
MPD_ROUND_GUARD
};
enum { MPD_CLAMP_DEFAULT, MPD_CLAMP_IEEE_754, MPD_CLAMP_GUARD };
extern const char *mpd_round_string[MPD_ROUND_GUARD];
extern const char *mpd_clamp_string[MPD_CLAMP_GUARD];
typedef struct mpd_context_t {
mpd_ssize_t prec; /* precision */
mpd_ssize_t emax; /* max positive exp */
mpd_ssize_t emin; /* min negative exp */
uint32_t traps; /* status events that should be trapped */
uint32_t status; /* status flags */
uint32_t newtrap; /* set by mpd_addstatus_raise() */
int round; /* rounding mode */
int clamp; /* clamp mode */
int allcr; /* all functions correctly rounded */
} mpd_context_t;
/* Status flags */
#define MPD_Clamped 0x00000001U
#define MPD_Conversion_syntax 0x00000002U
#define MPD_Division_by_zero 0x00000004U
#define MPD_Division_impossible 0x00000008U
#define MPD_Division_undefined 0x00000010U
#define MPD_Fpu_error 0x00000020U
#define MPD_Inexact 0x00000040U
#define MPD_Invalid_context 0x00000080U
#define MPD_Invalid_operation 0x00000100U
#define MPD_Malloc_error 0x00000200U
#define MPD_Not_implemented 0x00000400U
#define MPD_Overflow 0x00000800U
#define MPD_Rounded 0x00001000U
#define MPD_Subnormal 0x00002000U
#define MPD_Underflow 0x00004000U
#define MPD_Max_status (0x00008000U-1U)
/* Conditions that result in an IEEE 754 exception */
#define MPD_IEEE_Invalid_operation (MPD_Conversion_syntax | \
MPD_Division_impossible | \
MPD_Division_undefined | \
MPD_Fpu_error | \
MPD_Invalid_context | \
MPD_Invalid_operation | \
MPD_Malloc_error) \
/* Errors that require the result of an operation to be set to NaN */
#define MPD_Errors (MPD_IEEE_Invalid_operation | \
MPD_Division_by_zero)
/* Default traps */
#define MPD_Traps (MPD_IEEE_Invalid_operation | \
MPD_Division_by_zero | \
MPD_Overflow | \
MPD_Underflow)
/* Official name */
#define MPD_Insufficient_storage MPD_Malloc_error
/* IEEE 754 interchange format contexts */
#define MPD_IEEE_CONTEXT_MAX_BITS 512 /* 16*(log2(MPD_MAX_EMAX / 3)-3) */
#define MPD_DECIMAL32 32
#define MPD_DECIMAL64 64
#define MPD_DECIMAL128 128
#define MPD_MINALLOC_MIN 2
#define MPD_MINALLOC_MAX 64
extern mpd_ssize_t MPD_MINALLOC;
extern void (* mpd_traphandler)(mpd_context_t *);
void mpd_dflt_traphandler(mpd_context_t *);
void mpd_setminalloc(mpd_ssize_t);
void mpd_init(mpd_context_t *, mpd_ssize_t);
void mpd_maxcontext(mpd_context_t *);
void mpd_defaultcontext(mpd_context_t *);
void mpd_basiccontext(mpd_context_t *);
int mpd_ieee_context(mpd_context_t *, int);
mpd_ssize_t mpd_getprec(const mpd_context_t *);
mpd_ssize_t mpd_getemax(const mpd_context_t *);
mpd_ssize_t mpd_getemin(const mpd_context_t *);
int mpd_getround(const mpd_context_t *);
uint32_t mpd_gettraps(const mpd_context_t *);
uint32_t mpd_getstatus(const mpd_context_t *);
int mpd_getclamp(const mpd_context_t *);
int mpd_getcr(const mpd_context_t *);
int mpd_qsetprec(mpd_context_t *, mpd_ssize_t);
int mpd_qsetemax(mpd_context_t *, mpd_ssize_t);
int mpd_qsetemin(mpd_context_t *, mpd_ssize_t);
int mpd_qsetround(mpd_context_t *, int);
int mpd_qsettraps(mpd_context_t *, uint32_t);
int mpd_qsetstatus(mpd_context_t *, uint32_t);
int mpd_qsetclamp(mpd_context_t *, int);
int mpd_qsetcr(mpd_context_t *, int);
void mpd_addstatus_raise(mpd_context_t *, uint32_t);
/******************************************************************************/
/* Decimal Arithmetic */
/******************************************************************************/
/* mpd_t flags */
#define MPD_POS ((uint8_t)0)
#define MPD_NEG ((uint8_t)1)
#define MPD_INF ((uint8_t)2)
#define MPD_NAN ((uint8_t)4)
#define MPD_SNAN ((uint8_t)8)
#define MPD_SPECIAL (MPD_INF|MPD_NAN|MPD_SNAN)
#define MPD_STATIC ((uint8_t)16)
#define MPD_STATIC_DATA ((uint8_t)32)
#define MPD_SHARED_DATA ((uint8_t)64)
#define MPD_CONST_DATA ((uint8_t)128)
#define MPD_DATAFLAGS (MPD_STATIC_DATA|MPD_SHARED_DATA|MPD_CONST_DATA)
typedef struct mpd_t {
uint8_t flags;
mpd_ssize_t exp;
mpd_ssize_t digits;
mpd_ssize_t len;
mpd_ssize_t alloc;
mpd_uint_t *data;
} mpd_t;
typedef unsigned char uchar;
/******************************************************************************/
/* Quiet, thread-safe functions */
/******************************************************************************/
/* format specification */
typedef struct mpd_spec_t {
mpd_ssize_t min_width; /* minimum field width */
mpd_ssize_t prec; /* fraction digits or significant digits */
char type; /* conversion specifier */
char align; /* alignment */
char sign; /* sign printing/alignment */
char fill[5]; /* fill character */
const char *dot; /* decimal point */
const char *sep; /* thousands separator */
const char *grouping; /* grouping of digits */
} mpd_spec_t;
/* output to a string */
char *mpd_to_sci(const mpd_t *, int);
char *mpd_to_eng(const mpd_t *, int);
mpd_ssize_t mpd_to_sci_size(char **, const mpd_t *, int);
mpd_ssize_t mpd_to_eng_size(char **, const mpd_t *, int);
int mpd_validate_lconv(mpd_spec_t *);
int mpd_parse_fmt_str(mpd_spec_t *, const char *, int);
char *mpd_qformat_spec(const mpd_t *, const mpd_spec_t *, const mpd_context_t *, uint32_t *);
char *mpd_qformat(const mpd_t *, const char *, const mpd_context_t *, uint32_t *);
#define MPD_NUM_FLAGS 15
#define MPD_MAX_FLAG_STRING 208
#define MPD_MAX_FLAG_LIST (MPD_MAX_FLAG_STRING+18)
#define MPD_MAX_SIGNAL_LIST 121
int mpd_snprint_flags(char *, int, uint32_t);
int mpd_lsnprint_flags(char *, int, uint32_t, const char *[]);
int mpd_lsnprint_signals(char *, int, uint32_t, const char *[]);
/* output to a file */
void mpd_fprint(FILE *, const mpd_t *);
void mpd_print(const mpd_t *);
/* assignment from a string */
void mpd_qset_string(mpd_t *, const char *s, const mpd_context_t *, uint32_t *);
/* set to NaN with error flags */
void mpd_seterror(mpd_t *, uint32_t, uint32_t *);
/* set a special with sign and type */
void mpd_setspecial(mpd_t *, uint8_t, uint8_t);
/* set coefficient to zero or all nines */
void mpd_zerocoeff(mpd_t *);
void mpd_qmaxcoeff(mpd_t *, const mpd_context_t *, uint32_t *);
/* quietly assign a C integer type to an mpd_t */
void mpd_qset_ssize(mpd_t *, mpd_ssize_t, const mpd_context_t *, uint32_t *);
void mpd_qset_i32(mpd_t *, int32_t, const mpd_context_t *, uint32_t *);
void mpd_qset_uint(mpd_t *, mpd_uint_t, const mpd_context_t *, uint32_t *);
void mpd_qset_u32(mpd_t *, uint32_t, const mpd_context_t *, uint32_t *);
void mpd_qset_i64(mpd_t *, int64_t, const mpd_context_t *, uint32_t *);
void mpd_qset_u64(mpd_t *, uint64_t, const mpd_context_t *, uint32_t *);
/* quietly assign a C integer type to an mpd_t with a static coefficient */
void mpd_qsset_ssize(mpd_t *, mpd_ssize_t, const mpd_context_t *, uint32_t *);
void mpd_qsset_i32(mpd_t *, int32_t, const mpd_context_t *, uint32_t *);
void mpd_qsset_uint(mpd_t *, mpd_uint_t, const mpd_context_t *, uint32_t *);
void mpd_qsset_u32(mpd_t *, uint32_t, const mpd_context_t *, uint32_t *);
mpd_ssize_t mpd_qget_ssize(const mpd_t *, uint32_t *);
mpd_uint_t mpd_qget_uint(const mpd_t *, uint32_t *);
mpd_uint_t mpd_qabs_uint(const mpd_t *, uint32_t *);
int32_t mpd_qget_i32(const mpd_t *, uint32_t *);
uint32_t mpd_qget_u32(const mpd_t *, uint32_t *);
int64_t mpd_qget_i64(const mpd_t *, uint32_t *);
uint64_t mpd_qget_u64(const mpd_t *, uint32_t *);
int mpd_qcheck_nan(mpd_t *, const mpd_t *, const mpd_context_t *, uint32_t *);
int mpd_qcheck_nans(mpd_t *, const mpd_t *, const mpd_t *, const mpd_context_t *, uint32_t *);
void mpd_qfinalize(mpd_t *, const mpd_context_t *, uint32_t *);
const char *mpd_class(const mpd_t *, const mpd_context_t *);
mpd_t *mpd_qncopy(const mpd_t *);
int mpd_qcopy(mpd_t *, const mpd_t *, uint32_t *);
int mpd_qcopy_abs(mpd_t *, const mpd_t *, uint32_t *);
int mpd_qcopy_negate(mpd_t *, const mpd_t *, uint32_t *);
int mpd_qcopy_sign(mpd_t *, const mpd_t *, const mpd_t *, uint32_t *);
void mpd_qand(mpd_t *, const mpd_t *, const mpd_t *, const mpd_context_t *, uint32_t *);
void mpd_qinvert(mpd_t *, const mpd_t *, const mpd_context_t *, uint32_t *);
void mpd_qlogb(mpd_t *, const mpd_t *, const mpd_context_t *, uint32_t *);
void mpd_qor(mpd_t *, const mpd_t *, const mpd_t *, const mpd_context_t *, uint32_t *);
void mpd_qscaleb(mpd_t *, const mpd_t *, const mpd_t *, const mpd_context_t *, uint32_t *);
void mpd_qxor(mpd_t *, const mpd_t *, const mpd_t *, const mpd_context_t *, uint32_t *);
int mpd_same_quantum(const mpd_t *, const mpd_t *);
void mpd_qrotate(mpd_t *, const mpd_t *, const mpd_t *, const mpd_context_t *, uint32_t *);
int mpd_qshiftl(mpd_t *, const mpd_t *, mpd_ssize_t, uint32_t *);
mpd_uint_t mpd_qshiftr(mpd_t *, const mpd_t *, mpd_ssize_t, uint32_t *);
mpd_uint_t mpd_qshiftr_inplace(mpd_t *, mpd_ssize_t);
void mpd_qshift(mpd_t *, const mpd_t *, const mpd_t *, const mpd_context_t *, uint32_t *);
void mpd_qshiftn(mpd_t *, const mpd_t *, mpd_ssize_t, const mpd_context_t *, uint32_t *);
int mpd_qcmp(const mpd_t *, const mpd_t *, uint32_t *);
int mpd_qcompare(mpd_t *, const mpd_t *, const mpd_t *, const mpd_context_t *, uint32_t *);
int mpd_qcompare_signal(mpd_t *, const mpd_t *, const mpd_t *, const mpd_context_t *, uint32_t *);
int mpd_cmp_total(const mpd_t *, const mpd_t *);
int mpd_cmp_total_mag(const mpd_t *, const mpd_t *);
int mpd_compare_total(mpd_t *, const mpd_t *, const mpd_t *);
int mpd_compare_total_mag(mpd_t *, const mpd_t *, const mpd_t *);
void mpd_qround_to_intx(mpd_t *, const mpd_t *, const mpd_context_t *, uint32_t *);
void mpd_qround_to_int(mpd_t *, const mpd_t *, const mpd_context_t *, uint32_t *);
void mpd_qtrunc(mpd_t *, const mpd_t *, const mpd_context_t *, uint32_t *);
void mpd_qfloor(mpd_t *, const mpd_t *, const mpd_context_t *, uint32_t *);
void mpd_qceil(mpd_t *, const mpd_t *, const mpd_context_t *, uint32_t *);
void mpd_qabs(mpd_t *, const mpd_t *, const mpd_context_t *, uint32_t *);
void mpd_qmax(mpd_t *, const mpd_t *, const mpd_t *, const mpd_context_t *, uint32_t *);
void mpd_qmax_mag(mpd_t *, const mpd_t *, const mpd_t *, const mpd_context_t *, uint32_t *);
void mpd_qmin(mpd_t *, const mpd_t *, const mpd_t *, const mpd_context_t *, uint32_t *);
void mpd_qmin_mag(mpd_t *, const mpd_t *, const mpd_t *, const mpd_context_t *, uint32_t *);
void mpd_qminus(mpd_t *, const mpd_t *, const mpd_context_t *, uint32_t *);
void mpd_qplus(mpd_t *, const mpd_t *, const mpd_context_t *, uint32_t *);
void mpd_qnext_minus(mpd_t *, const mpd_t *, const mpd_context_t *, uint32_t *);
void mpd_qnext_plus(mpd_t *, const mpd_t *, const mpd_context_t *, uint32_t *);
void mpd_qnext_toward(mpd_t *, const mpd_t *, const mpd_t *, const mpd_context_t *, uint32_t *);
void mpd_qquantize(mpd_t *, const mpd_t *, const mpd_t *, const mpd_context_t *, uint32_t *);
void mpd_qrescale(mpd_t *, const mpd_t *, mpd_ssize_t, const mpd_context_t *, uint32_t *);
void mpd_qrescale_fmt(mpd_t *, const mpd_t *, mpd_ssize_t, const mpd_context_t *, uint32_t *);
void mpd_qreduce(mpd_t *, const mpd_t *, const mpd_context_t *, uint32_t *);
void mpd_qadd(mpd_t *, const mpd_t *, const mpd_t *, const mpd_context_t *, uint32_t *);
void mpd_qadd_ssize(mpd_t *, const mpd_t *, mpd_ssize_t, const mpd_context_t *, uint32_t *);
void mpd_qadd_i32(mpd_t *, const mpd_t *, int32_t, const mpd_context_t *, uint32_t *);
void mpd_qadd_uint(mpd_t *, const mpd_t *, mpd_uint_t, const mpd_context_t *, uint32_t *);
void mpd_qadd_u32(mpd_t *, const mpd_t *, uint32_t, const mpd_context_t *, uint32_t *);
void mpd_qsub(mpd_t *, const mpd_t *, const mpd_t *, const mpd_context_t *, uint32_t *);
void mpd_qsub_ssize(mpd_t *, const mpd_t *, mpd_ssize_t, const mpd_context_t *, uint32_t *);
void mpd_qsub_i32(mpd_t *, const mpd_t *, int32_t, const mpd_context_t *, uint32_t *);
void mpd_qsub_uint(mpd_t *, const mpd_t *, mpd_uint_t, const mpd_context_t *, uint32_t *);
void mpd_qsub_u32(mpd_t *, const mpd_t *, uint32_t, const mpd_context_t *, uint32_t *);
void mpd_qmul(mpd_t *, const mpd_t *, const mpd_t *, const mpd_context_t *, uint32_t *);
void mpd_qmul_ssize(mpd_t *, const mpd_t *, mpd_ssize_t, const mpd_context_t *, uint32_t *);
void mpd_qmul_i32(mpd_t *, const mpd_t *, int32_t, const mpd_context_t *, uint32_t *);
void mpd_qmul_uint(mpd_t *, const mpd_t *, mpd_uint_t, const mpd_context_t *, uint32_t *);
void mpd_qmul_u32(mpd_t *, const mpd_t *, uint32_t, const mpd_context_t *, uint32_t *);
void mpd_qfma(mpd_t *, const mpd_t *, const mpd_t *, const mpd_t *c, const mpd_context_t *, uint32_t *);
void mpd_qdiv(mpd_t *q, const mpd_t *, const mpd_t *, const mpd_context_t *, uint32_t *);
void mpd_qdiv_ssize(mpd_t *, const mpd_t *, mpd_ssize_t, const mpd_context_t *, uint32_t *);
void mpd_qdiv_i32(mpd_t *, const mpd_t *, int32_t, const mpd_context_t *, uint32_t *);
void mpd_qdiv_uint(mpd_t *, const mpd_t *, mpd_uint_t, const mpd_context_t *, uint32_t *);
void mpd_qdiv_u32(mpd_t *, const mpd_t *, uint32_t, const mpd_context_t *, uint32_t *);
void mpd_qdivint(mpd_t *q, const mpd_t *, const mpd_t *, const mpd_context_t *, uint32_t *);
void mpd_qrem(mpd_t *r, const mpd_t *, const mpd_t *, const mpd_context_t *, uint32_t *);
void mpd_qrem_near(mpd_t *r, const mpd_t *, const mpd_t *, const mpd_context_t *, uint32_t *);
void mpd_qdivmod(mpd_t *q, mpd_t *r, const mpd_t *, const mpd_t *, const mpd_context_t *, uint32_t *);
void mpd_qpow(mpd_t *, const mpd_t *, const mpd_t *, const mpd_context_t *, uint32_t *);
void mpd_qpowmod(mpd_t *, const mpd_t *, const mpd_t *, const mpd_t *, const mpd_context_t *, uint32_t *);
void mpd_qexp(mpd_t *, const mpd_t *, const mpd_context_t *, uint32_t *);
void mpd_qln10(mpd_t *, mpd_ssize_t, uint32_t *);
void mpd_qln(mpd_t *, const mpd_t *, const mpd_context_t *, uint32_t *);
void mpd_qlog10(mpd_t *, const mpd_t *, const mpd_context_t *, uint32_t *);
void mpd_qsqrt(mpd_t *, const mpd_t *, const mpd_context_t *, uint32_t *);
void mpd_qinvroot(mpd_t *, const mpd_t *, const mpd_context_t *, uint32_t *);
void mpd_qadd_i64(mpd_t *, const mpd_t *, int64_t, const mpd_context_t *, uint32_t *);
void mpd_qadd_u64(mpd_t *, const mpd_t *, uint64_t, const mpd_context_t *, uint32_t *);
void mpd_qsub_i64(mpd_t *, const mpd_t *, int64_t, const mpd_context_t *, uint32_t *);
void mpd_qsub_u64(mpd_t *, const mpd_t *, uint64_t, const mpd_context_t *, uint32_t *);
void mpd_qmul_i64(mpd_t *, const mpd_t *, int64_t, const mpd_context_t *, uint32_t *);
void mpd_qmul_u64(mpd_t *, const mpd_t *, uint64_t, const mpd_context_t *, uint32_t *);
void mpd_qdiv_i64(mpd_t *, const mpd_t *, int64_t, const mpd_context_t *, uint32_t *);
void mpd_qdiv_u64(mpd_t *, const mpd_t *, uint64_t, const mpd_context_t *, uint32_t *);
size_t mpd_sizeinbase(const mpd_t *, uint32_t);
void mpd_qimport_u16(mpd_t *, const uint16_t *, size_t, uint8_t, uint32_t, const mpd_context_t *, uint32_t *);
void mpd_qimport_u32(mpd_t *, const uint32_t *, size_t, uint8_t, uint32_t, const mpd_context_t *, uint32_t *);
size_t mpd_qexport_u16(uint16_t **, size_t, uint32_t, const mpd_t *, uint32_t *);
size_t mpd_qexport_u32(uint32_t **, size_t, uint32_t, const mpd_t *, uint32_t *);
/******************************************************************************/
/* Signalling functions */
/******************************************************************************/
char *mpd_format(const mpd_t *, const char *, mpd_context_t *);
void mpd_import_u16(mpd_t *, const uint16_t *, size_t, uint8_t, uint32_t, mpd_context_t *);
void mpd_import_u32(mpd_t *, const uint32_t *, size_t, uint8_t, uint32_t, mpd_context_t *);
size_t mpd_export_u16(uint16_t **, size_t, uint32_t, const mpd_t *, mpd_context_t *);
size_t mpd_export_u32(uint32_t **, size_t, uint32_t, const mpd_t *, mpd_context_t *);
void mpd_finalize(mpd_t *, mpd_context_t *);
int mpd_check_nan(mpd_t *, const mpd_t *, mpd_context_t *);
int mpd_check_nans(mpd_t *, const mpd_t *, const mpd_t *, mpd_context_t *);
void mpd_set_string(mpd_t *, const char *s, mpd_context_t *);
void mpd_maxcoeff(mpd_t *, mpd_context_t *);
void mpd_sset_ssize(mpd_t *, mpd_ssize_t, mpd_context_t *);
void mpd_sset_i32(mpd_t *, int32_t, mpd_context_t *);
void mpd_sset_uint(mpd_t *, mpd_uint_t, mpd_context_t *);
void mpd_sset_u32(mpd_t *, uint32_t, mpd_context_t *);
void mpd_set_ssize(mpd_t *, mpd_ssize_t, mpd_context_t *);
void mpd_set_i32(mpd_t *, int32_t, mpd_context_t *);
void mpd_set_uint(mpd_t *, mpd_uint_t, mpd_context_t *);
void mpd_set_u32(mpd_t *, uint32_t, mpd_context_t *);
void mpd_set_i64(mpd_t *, int64_t, mpd_context_t *);
void mpd_set_u64(mpd_t *, uint64_t, mpd_context_t *);
mpd_ssize_t mpd_get_ssize(const mpd_t *, mpd_context_t *);
mpd_uint_t mpd_get_uint(const mpd_t *, mpd_context_t *);
mpd_uint_t mpd_abs_uint(const mpd_t *, mpd_context_t *);
int32_t mpd_get_i32(const mpd_t *, mpd_context_t *);
uint32_t mpd_get_u32(const mpd_t *, mpd_context_t *);
int64_t mpd_get_i64(const mpd_t *, mpd_context_t *);
uint64_t mpd_get_u64(const mpd_t *, mpd_context_t *);
void mpd_and(mpd_t *, const mpd_t *, const mpd_t *, mpd_context_t *);
void mpd_copy(mpd_t *, const mpd_t *, mpd_context_t *);
void mpd_canonical(mpd_t *, const mpd_t *, mpd_context_t *);
void mpd_copy_abs(mpd_t *, const mpd_t *, mpd_context_t *);
void mpd_copy_negate(mpd_t *, const mpd_t *, mpd_context_t *);
void mpd_copy_sign(mpd_t *, const mpd_t *, const mpd_t *, mpd_context_t *);
void mpd_invert(mpd_t *, const mpd_t *, mpd_context_t *);
void mpd_logb(mpd_t *, const mpd_t *, mpd_context_t *);
void mpd_or(mpd_t *, const mpd_t *, const mpd_t *, mpd_context_t *);
void mpd_rotate(mpd_t *, const mpd_t *, const mpd_t *, mpd_context_t *);
void mpd_scaleb(mpd_t *, const mpd_t *, const mpd_t *, mpd_context_t *);
void mpd_shiftl(mpd_t *, const mpd_t *, mpd_ssize_t, mpd_context_t *);
mpd_uint_t mpd_shiftr(mpd_t *, const mpd_t *, mpd_ssize_t, mpd_context_t *);
void mpd_shiftn(mpd_t *, const mpd_t *, mpd_ssize_t, mpd_context_t *);
void mpd_shift(mpd_t *, const mpd_t *, const mpd_t *, mpd_context_t *);
void mpd_xor(mpd_t *, const mpd_t *, const mpd_t *, mpd_context_t *);
void mpd_abs(mpd_t *, const mpd_t *, mpd_context_t *);
int mpd_cmp(const mpd_t *, const mpd_t *, mpd_context_t *);
int mpd_compare(mpd_t *, const mpd_t *, const mpd_t *, mpd_context_t *);
int mpd_compare_signal(mpd_t *, const mpd_t *, const mpd_t *, mpd_context_t *);
void mpd_add(mpd_t *, const mpd_t *, const mpd_t *, mpd_context_t *);
void mpd_add_ssize(mpd_t *, const mpd_t *, mpd_ssize_t, mpd_context_t *);
void mpd_add_i32(mpd_t *, const mpd_t *, int32_t, mpd_context_t *);
void mpd_add_uint(mpd_t *, const mpd_t *, mpd_uint_t, mpd_context_t *);
void mpd_add_u32(mpd_t *, const mpd_t *, uint32_t, mpd_context_t *);
void mpd_sub(mpd_t *, const mpd_t *, const mpd_t *, mpd_context_t *);
void mpd_sub_ssize(mpd_t *, const mpd_t *, mpd_ssize_t, mpd_context_t *);
void mpd_sub_i32(mpd_t *, const mpd_t *, int32_t, mpd_context_t *);
void mpd_sub_uint(mpd_t *, const mpd_t *, mpd_uint_t, mpd_context_t *);
void mpd_sub_u32(mpd_t *, const mpd_t *, uint32_t, mpd_context_t *);
void mpd_div(mpd_t *, const mpd_t *, const mpd_t *, mpd_context_t *);
void mpd_div_ssize(mpd_t *, const mpd_t *, mpd_ssize_t, mpd_context_t *);
void mpd_div_i32(mpd_t *, const mpd_t *, int32_t, mpd_context_t *);
void mpd_div_uint(mpd_t *, const mpd_t *, mpd_uint_t, mpd_context_t *);
void mpd_div_u32(mpd_t *, const mpd_t *, uint32_t, mpd_context_t *);
void mpd_divmod(mpd_t *, mpd_t *r, const mpd_t *, const mpd_t *, mpd_context_t *);
void mpd_divint(mpd_t *, const mpd_t *, const mpd_t *, mpd_context_t *);
void mpd_exp(mpd_t *, const mpd_t *, mpd_context_t *);
void mpd_fma(mpd_t *, const mpd_t *, const mpd_t *, const mpd_t *c, mpd_context_t *);
void mpd_ln(mpd_t *, const mpd_t *, mpd_context_t *);
void mpd_log10(mpd_t *, const mpd_t *, mpd_context_t *);
void mpd_max(mpd_t *, const mpd_t *, const mpd_t *, mpd_context_t *);
void mpd_max_mag(mpd_t *, const mpd_t *, const mpd_t *, mpd_context_t *);
void mpd_min(mpd_t *, const mpd_t *, const mpd_t *, mpd_context_t *);
void mpd_min_mag(mpd_t *, const mpd_t *, const mpd_t *, mpd_context_t *);
void mpd_minus(mpd_t *, const mpd_t *, mpd_context_t *);
void mpd_mul(mpd_t *, const mpd_t *, const mpd_t *, mpd_context_t *);
void mpd_mul_ssize(mpd_t *, const mpd_t *, mpd_ssize_t, mpd_context_t *);
void mpd_mul_i32(mpd_t *, const mpd_t *, int32_t, mpd_context_t *);
void mpd_mul_uint(mpd_t *, const mpd_t *, mpd_uint_t, mpd_context_t *);
void mpd_mul_u32(mpd_t *, const mpd_t *, uint32_t, mpd_context_t *);
void mpd_next_minus(mpd_t *, const mpd_t *, mpd_context_t *);
void mpd_next_plus(mpd_t *, const mpd_t *, mpd_context_t *);
void mpd_next_toward(mpd_t *, const mpd_t *, const mpd_t *, mpd_context_t *);
void mpd_plus(mpd_t *, const mpd_t *, mpd_context_t *);
void mpd_pow(mpd_t *, const mpd_t *, const mpd_t *, mpd_context_t *);
void mpd_powmod(mpd_t *, const mpd_t *, const mpd_t *, const mpd_t *, mpd_context_t *);
void mpd_quantize(mpd_t *, const mpd_t *, const mpd_t *, mpd_context_t *);
void mpd_rescale(mpd_t *, const mpd_t *, mpd_ssize_t, mpd_context_t *);
void mpd_reduce(mpd_t *, const mpd_t *, mpd_context_t *);
void mpd_rem(mpd_t *r, const mpd_t *, const mpd_t *, mpd_context_t *);
void mpd_rem_near(mpd_t *r, const mpd_t *, const mpd_t *, mpd_context_t *);
void mpd_round_to_intx(mpd_t *, const mpd_t *, mpd_context_t *);
void mpd_round_to_int(mpd_t *, const mpd_t *, mpd_context_t *);
void mpd_trunc(mpd_t *, const mpd_t *, mpd_context_t *);
void mpd_floor(mpd_t *, const mpd_t *, mpd_context_t *);
void mpd_ceil(mpd_t *, const mpd_t *, mpd_context_t *);
void mpd_sqrt(mpd_t *, const mpd_t *, mpd_context_t *);
void mpd_invroot(mpd_t *, const mpd_t *, mpd_context_t *);
void mpd_add_i64(mpd_t *, const mpd_t *, int64_t, mpd_context_t *);
void mpd_add_u64(mpd_t *, const mpd_t *, uint64_t, mpd_context_t *);
void mpd_sub_i64(mpd_t *, const mpd_t *, int64_t, mpd_context_t *);
void mpd_sub_u64(mpd_t *, const mpd_t *, uint64_t, mpd_context_t *);
void mpd_div_i64(mpd_t *, const mpd_t *, int64_t, mpd_context_t *);
void mpd_div_u64(mpd_t *, const mpd_t *, uint64_t, mpd_context_t *);
void mpd_mul_i64(mpd_t *, const mpd_t *, int64_t, mpd_context_t *);
void mpd_mul_u64(mpd_t *, const mpd_t *, uint64_t, mpd_context_t *);
/******************************************************************************/
/* Configuration specific */
/******************************************************************************/
void mpd_qsset_i64(mpd_t *, int64_t, const mpd_context_t *, uint32_t *);
void mpd_qsset_u64(mpd_t *, uint64_t, const mpd_context_t *, uint32_t *);
void mpd_sset_i64(mpd_t *, int64_t, mpd_context_t *);
void mpd_sset_u64(mpd_t *, uint64_t, mpd_context_t *);
/******************************************************************************/
/* Get attributes of a decimal */
/******************************************************************************/
mpd_ssize_t mpd_adjexp(const mpd_t *);
mpd_ssize_t mpd_etiny(const mpd_context_t *);
mpd_ssize_t mpd_etop(const mpd_context_t *);
mpd_uint_t mpd_msword(const mpd_t *);
int mpd_word_digits(mpd_uint_t);
/* most significant digit of a word */
mpd_uint_t mpd_msd(mpd_uint_t);
/* least significant digit of a word */
mpd_uint_t mpd_lsd(mpd_uint_t);
/* coefficient size needed to store 'digits' */
mpd_ssize_t mpd_digits_to_size(mpd_ssize_t);
/* number of digits in the exponent, undefined for MPD_SSIZE_MIN */
int mpd_exp_digits(mpd_ssize_t);
int mpd_iscanonical(const mpd_t *);
int mpd_isfinite(const mpd_t *);
int mpd_isinfinite(const mpd_t *);
int mpd_isinteger(const mpd_t *);
int mpd_isnan(const mpd_t *);
int mpd_isnegative(const mpd_t *);
int mpd_ispositive(const mpd_t *);
int mpd_isqnan(const mpd_t *);
int mpd_issigned(const mpd_t *);
int mpd_issnan(const mpd_t *);
int mpd_isspecial(const mpd_t *);
int mpd_iszero(const mpd_t *);
/* undefined for special numbers */
int mpd_iszerocoeff(const mpd_t *);
int mpd_isnormal(const mpd_t *, const mpd_context_t *);
int mpd_issubnormal(const mpd_t *, const mpd_context_t *);
/* odd word */
int mpd_isoddword(mpd_uint_t);
/* odd coefficient */
int mpd_isoddcoeff(const mpd_t *);
/* odd decimal, only defined for integers */
int mpd_isodd(const mpd_t *);
/* even decimal, only defined for integers */
int mpd_iseven(const mpd_t *);
/* 0 if dec is positive, 1 if dec is negative */
uint8_t mpd_sign(const mpd_t *);
/* 1 if dec is positive, -1 if dec is negative */
int mpd_arith_sign(const mpd_t *);
long mpd_radix(void);
int mpd_isdynamic(const mpd_t *);
int mpd_isstatic(const mpd_t *);
int mpd_isdynamic_data(const mpd_t *);
int mpd_isstatic_data(const mpd_t *);
int mpd_isshared_data(const mpd_t *);
int mpd_isconst_data(const mpd_t *);
mpd_ssize_t mpd_trail_zeros(const mpd_t *);
/******************************************************************************/
/* Set attributes of a decimal */
/******************************************************************************/
void mpd_setdigits(mpd_t *);
void mpd_set_sign(mpd_t *, uint8_t);
void mpd_signcpy(mpd_t *, const mpd_t *);
void mpd_set_infinity(mpd_t *);
void mpd_set_qnan(mpd_t *);
void mpd_set_snan(mpd_t *);
void mpd_set_negative(mpd_t *);
void mpd_set_positive(mpd_t *);
void mpd_set_dynamic(mpd_t *);
void mpd_set_static(mpd_t *);
void mpd_set_dynamic_data(mpd_t *);
void mpd_set_static_data(mpd_t *);
void mpd_set_shared_data(mpd_t *);
void mpd_set_const_data(mpd_t *);
void mpd_clear_flags(mpd_t *);
void mpd_set_flags(mpd_t *, uint8_t);
void mpd_copy_flags(mpd_t *, const mpd_t *);
/******************************************************************************/
/* Error Macros */
/******************************************************************************/
#define mpd_err_fatal(...) \
do {fprintf(stderr, "%s:%d: error: ", __FILE__, __LINE__); \
fprintf(stderr, __VA_ARGS__); fputc('\n', stderr); \
abort(); \
} while (0)
#define mpd_err_warn(...) \
do {fprintf(stderr, "%s:%d: warning: ", __FILE__, __LINE__); \
fprintf(stderr, __VA_ARGS__); fputc('\n', stderr); \
} while (0)
/******************************************************************************/
/* Memory handling */
/******************************************************************************/
extern void *(*mpd_mallocfunc)(size_t);
extern void *(*mpd_callocfunc)(size_t, size_t);
extern void *(*mpd_reallocfunc)(void *, size_t);
extern void (*mpd_free)(void *);
void *mpd_callocfunc_em(size_t, size_t);
void *mpd_alloc(mpd_size_t, mpd_size_t);
void *mpd_calloc(mpd_size_t, mpd_size_t);
void *mpd_realloc(void *, mpd_size_t, mpd_size_t, uint8_t *);
void *mpd_sh_alloc(mpd_size_t, mpd_size_t, mpd_size_t);
mpd_t *mpd_qnew(void);
mpd_t *mpd_new(mpd_context_t *);
mpd_t *mpd_qnew_size(mpd_ssize_t);
void mpd_del(mpd_t *);
void mpd_uint_zero(mpd_uint_t *, mpd_size_t);
int mpd_qresize(mpd_t *, mpd_ssize_t, uint32_t *);
int mpd_qresize_zero(mpd_t *, mpd_ssize_t, uint32_t *);
void mpd_minalloc(mpd_t *);
int mpd_resize(mpd_t *, mpd_ssize_t, mpd_context_t *);
int mpd_resize_zero(mpd_t *, mpd_ssize_t, mpd_context_t *);
COSMOPOLITAN_C_END_
#endif /* MPDECIMAL_H */
| 30,778 | 614 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Modules/_decimal/libmpdec/numbertheory.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:8;coding:utf-8 -*-â
âvi: set net ft=c ts=4 sts=4 sw=4 fenc=utf-8 :viâ
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ¡
â Copyright (c) 2008-2016 Stefan Krah. All rights reserved. â
â â
â Redistribution and use in source and binary forms, with or without â
â modification, are permitted provided that the following conditions â
â are met: â
â â
â 1. Redistributions of source code must retain the above copyright â
â notice, this list of conditions and the following disclaimer. â
â â
â 2. Redistributions in binary form must reproduce the above copyright â
â notice, this list of conditions and the following disclaimer in â
â the documentation and/or other materials provided with the â
â distribution. â
â â
â THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS "AS IS" AND â
â ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE â
â IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR â
â PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS â
â BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, â
â OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT â
â OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR â
â BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, â
â WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE â
â OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, â
â EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
#include "third_party/python/Modules/_decimal/libmpdec/bits.h"
#include "third_party/python/Modules/_decimal/libmpdec/mpdecimal.h"
#include "third_party/python/Modules/_decimal/libmpdec/numbertheory.h"
#include "third_party/python/Modules/_decimal/libmpdec/umodarith.h"
/* clang-format off */
asm(".ident\t\"\\n\\n\
libmpdec (BSD-2)\\n\
Copyright 2008-2016 Stefan Krah\"");
asm(".include \"libc/disclaimer.inc\"");
/* Bignum: Initialize the Number Theoretic Transform. */
/*
* Return the nth root of unity in F(p). This corresponds to e**((2*pi*i)/n)
* in the Fourier transform. We have w**n == 1 (mod p).
* n := transform length.
* sign := -1 for forward transform, 1 for backward transform.
* modnum := one of {P1, P2, P3}.
*/
mpd_uint_t
_mpd_getkernel(mpd_uint_t n, int sign, int modnum)
{
mpd_uint_t umod, p, r, xi;
SETMODULUS(modnum);
r = mpd_roots[modnum]; /* primitive root of F(p) */
p = umod;
xi = (p-1) / n;
if (sign == -1)
return POWMOD(r, (p-1-xi));
else
return POWMOD(r, xi);
}
/*
* Initialize and return transform parameters.
* n := transform length.
* sign := -1 for forward transform, 1 for backward transform.
* modnum := one of {P1, P2, P3}.
*/
struct fnt_params *
_mpd_init_fnt_params(mpd_size_t n, int sign, int modnum)
{
struct fnt_params *tparams;
mpd_uint_t umod;
mpd_uint_t kernel, w;
mpd_uint_t i;
mpd_size_t nhalf;
assert(ispower2(n));
assert(sign == -1 || sign == 1);
assert(P1 <= modnum && modnum <= P3);
nhalf = n/2;
tparams = mpd_sh_alloc(sizeof *tparams, nhalf, sizeof (mpd_uint_t));
if (tparams == NULL) {
return NULL;
}
SETMODULUS(modnum);
kernel = _mpd_getkernel(n, sign, modnum);
tparams->modnum = modnum;
tparams->modulus = umod;
tparams->kernel = kernel;
/* wtable[] := w**0, w**1, ..., w**(nhalf-1) */
w = 1;
for (i = 0; i < nhalf; i++) {
tparams->wtable[i] = w;
w = MULMOD(w, kernel);
}
return tparams;
}
/* Initialize wtable of size three. */
void
_mpd_init_w3table(mpd_uint_t w3table[3], int sign, int modnum)
{
mpd_uint_t umod;
mpd_uint_t kernel;
SETMODULUS(modnum);
kernel = _mpd_getkernel(3, sign, modnum);
w3table[0] = 1;
w3table[1] = kernel;
w3table[2] = POWMOD(kernel, 2);
}
| 5,111 | 112 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Modules/_decimal/libmpdec/mpdecimal.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:8;coding:utf-8 -*-â
âvi: set net ft=c ts=4 sts=4 sw=4 fenc=utf-8 :viâ
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ¡
â Copyright (c) 2008-2016 Stefan Krah. All rights reserved. â
â â
â Redistribution and use in source and binary forms, with or without â
â modification, are permitted provided that the following conditions â
â are met: â
â â
â 1. Redistributions of source code must retain the above copyright â
â notice, this list of conditions and the following disclaimer. â
â â
â 2. Redistributions in binary form must reproduce the above copyright â
â notice, this list of conditions and the following disclaimer in â
â the documentation and/or other materials provided with the â
â distribution. â
â â
â THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS "AS IS" AND â
â ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE â
â IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR â
â PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS â
â BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, â
â OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT â
â OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR â
â BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, â
â WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE â
â OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, â
â EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
#include "libc/math.h"
#include "third_party/python/Modules/_decimal/libmpdec/basearith.h"
#include "third_party/python/Modules/_decimal/libmpdec/bits.h"
#include "third_party/python/Modules/_decimal/libmpdec/convolute.h"
#include "third_party/python/Modules/_decimal/libmpdec/crt.h"
#include "third_party/python/Modules/_decimal/libmpdec/mpalloc.h"
#include "third_party/python/Modules/_decimal/libmpdec/mpdecimal.h"
#include "third_party/python/Modules/_decimal/libmpdec/typearith.h"
#include "third_party/python/Modules/_decimal/libmpdec/umodarith.h"
/* clang-format off */
asm(".ident\t\"\\n\\n\
libmpdec (BSD-2)\\n\
Copyright 2008-2016 Stefan Krah\"");
asm(".include \"libc/disclaimer.inc\"");
#define MPD_NEWTONDIV_CUTOFF 1024L
#define MPD_NEW_STATIC(name, flags, exp, digits, len) \
mpd_uint_t name##_data[MPD_MINALLOC_MAX]; \
mpd_t name = {flags|MPD_STATIC|MPD_STATIC_DATA, exp, digits, \
len, MPD_MINALLOC_MAX, name##_data}
#define MPD_NEW_CONST(name, flags, exp, digits, len, alloc, initval) \
mpd_uint_t name##_data[alloc] = {initval}; \
mpd_t name = {flags|MPD_STATIC|MPD_CONST_DATA, exp, digits, \
len, alloc, name##_data}
#define MPD_NEW_SHARED(name, a) \
mpd_t name = {(a->flags&~MPD_DATAFLAGS)|MPD_STATIC|MPD_SHARED_DATA, \
a->exp, a->digits, a->len, a->alloc, a->data}
static mpd_uint_t data_one[1] = {1};
static mpd_uint_t data_zero[1] = {0};
static const mpd_t one = {MPD_STATIC|MPD_CONST_DATA, 0, 1, 1, 1, data_one};
static const mpd_t minus_one = {MPD_NEG|MPD_STATIC|MPD_CONST_DATA, 0, 1, 1, 1,
data_one};
static const mpd_t zero = {MPD_STATIC|MPD_CONST_DATA, 0, 1, 1, 1, data_zero};
static inline void _mpd_check_exp(mpd_t *dec, const mpd_context_t *ctx,
uint32_t *status);
static void _settriple(mpd_t *result, uint8_t sign, mpd_uint_t a,
mpd_ssize_t exp);
static inline mpd_ssize_t _mpd_real_size(mpd_uint_t *data, mpd_ssize_t size);
static int _mpd_cmp_abs(const mpd_t *a, const mpd_t *b);
static void _mpd_qadd(mpd_t *result, const mpd_t *a, const mpd_t *b,
const mpd_context_t *ctx, uint32_t *status);
static inline void _mpd_qmul(mpd_t *result, const mpd_t *a, const mpd_t *b,
const mpd_context_t *ctx, uint32_t *status);
static void _mpd_base_ndivmod(mpd_t *q, mpd_t *r, const mpd_t *a,
const mpd_t *, uint32_t *);
static inline void _mpd_qpow_uint(mpd_t *, const mpd_t *,
mpd_uint_t , uint8_t,
const mpd_context_t *, uint32_t *);
static mpd_uint_t mpd_qsshiftr(mpd_t *, const mpd_t *, mpd_ssize_t);
/******************************************************************************/
/* Version */
/******************************************************************************/
const char *
mpd_version(void)
{
return MPD_VERSION;
}
/******************************************************************************/
/* Performance critical inline functions */
/******************************************************************************/
/* Digits in a word, primarily useful for the most significant word. */
__inline __attribute__((__always_inline__)) int
mpd_word_digits(mpd_uint_t word)
{
if (word < mpd_pow10[9]) {
if (word < mpd_pow10[4]) {
if (word < mpd_pow10[2]) {
return (word < mpd_pow10[1]) ? 1 : 2;
}
return (word < mpd_pow10[3]) ? 3 : 4;
}
if (word < mpd_pow10[6]) {
return (word < mpd_pow10[5]) ? 5 : 6;
}
if (word < mpd_pow10[8]) {
return (word < mpd_pow10[7]) ? 7 : 8;
}
return 9;
}
if (word < mpd_pow10[14]) {
if (word < mpd_pow10[11]) {
return (word < mpd_pow10[10]) ? 10 : 11;
}
if (word < mpd_pow10[13]) {
return (word < mpd_pow10[12]) ? 12 : 13;
}
return 14;
}
if (word < mpd_pow10[18]) {
if (word < mpd_pow10[16]) {
return (word < mpd_pow10[15]) ? 15 : 16;
}
return (word < mpd_pow10[17]) ? 17 : 18;
}
return (word < mpd_pow10[19]) ? 19 : 20;
}
/* Adjusted exponent */
__inline __attribute__((__always_inline__)) mpd_ssize_t
mpd_adjexp(const mpd_t *dec)
{
return (dec->exp + dec->digits) - 1;
}
/* Etiny */
__inline __attribute__((__always_inline__)) mpd_ssize_t
mpd_etiny(const mpd_context_t *ctx)
{
return ctx->emin - (ctx->prec - 1);
}
/* Etop: used for folding down in IEEE clamping */
__inline __attribute__((__always_inline__)) mpd_ssize_t
mpd_etop(const mpd_context_t *ctx)
{
return ctx->emax - (ctx->prec - 1);
}
/* Most significant word */
__inline __attribute__((__always_inline__)) mpd_uint_t
mpd_msword(const mpd_t *dec)
{
assert(dec->len > 0);
return dec->data[dec->len-1];
}
/* Most significant digit of a word */
inline mpd_uint_t
mpd_msd(mpd_uint_t word)
{
int n;
n = mpd_word_digits(word);
return word / mpd_pow10[n-1];
}
/* Least significant digit of a word */
__inline __attribute__((__always_inline__)) mpd_uint_t
mpd_lsd(mpd_uint_t word)
{
return word % 10;
}
/* Coefficient size needed to store 'digits' */
__inline __attribute__((__always_inline__)) mpd_ssize_t
mpd_digits_to_size(mpd_ssize_t digits)
{
mpd_ssize_t q, r;
_mpd_idiv_word(&q, &r, digits, MPD_RDIGITS);
return (r == 0) ? q : q+1;
}
/* Number of digits in the exponent. Not defined for MPD_SSIZE_MIN. */
inline int
mpd_exp_digits(mpd_ssize_t exp)
{
exp = (exp < 0) ? -exp : exp;
return mpd_word_digits(exp);
}
/* Canonical */
__inline __attribute__((__always_inline__)) int
mpd_iscanonical(const mpd_t *dec)
{
(void)dec;
return 1;
}
/* Finite */
__inline __attribute__((__always_inline__)) int
mpd_isfinite(const mpd_t *dec)
{
return !(dec->flags & MPD_SPECIAL);
}
/* Infinite */
__inline __attribute__((__always_inline__)) int
mpd_isinfinite(const mpd_t *dec)
{
return dec->flags & MPD_INF;
}
/* NaN */
__inline __attribute__((__always_inline__)) int
mpd_isnan(const mpd_t *dec)
{
return dec->flags & (MPD_NAN|MPD_SNAN);
}
/* Negative */
__inline __attribute__((__always_inline__)) int
mpd_isnegative(const mpd_t *dec)
{
return dec->flags & MPD_NEG;
}
/* Positive */
__inline __attribute__((__always_inline__)) int
mpd_ispositive(const mpd_t *dec)
{
return !(dec->flags & MPD_NEG);
}
/* qNaN */
__inline __attribute__((__always_inline__)) int
mpd_isqnan(const mpd_t *dec)
{
return dec->flags & MPD_NAN;
}
/* Signed */
__inline __attribute__((__always_inline__)) int
mpd_issigned(const mpd_t *dec)
{
return dec->flags & MPD_NEG;
}
/* sNaN */
__inline __attribute__((__always_inline__)) int
mpd_issnan(const mpd_t *dec)
{
return dec->flags & MPD_SNAN;
}
/* Special */
__inline __attribute__((__always_inline__)) int
mpd_isspecial(const mpd_t *dec)
{
return dec->flags & MPD_SPECIAL;
}
/* Zero */
__inline __attribute__((__always_inline__)) int
mpd_iszero(const mpd_t *dec)
{
return !mpd_isspecial(dec) && mpd_msword(dec) == 0;
}
/* Test for zero when specials have been ruled out already */
__inline __attribute__((__always_inline__)) int
mpd_iszerocoeff(const mpd_t *dec)
{
return mpd_msword(dec) == 0;
}
/* Normal */
inline int
mpd_isnormal(const mpd_t *dec, const mpd_context_t *ctx)
{
if (mpd_isspecial(dec)) return 0;
if (mpd_iszerocoeff(dec)) return 0;
return mpd_adjexp(dec) >= ctx->emin;
}
/* Subnormal */
inline int
mpd_issubnormal(const mpd_t *dec, const mpd_context_t *ctx)
{
if (mpd_isspecial(dec)) return 0;
if (mpd_iszerocoeff(dec)) return 0;
return mpd_adjexp(dec) < ctx->emin;
}
/* Odd word */
__inline __attribute__((__always_inline__)) int
mpd_isoddword(mpd_uint_t word)
{
return word & 1;
}
/* Odd coefficient */
__inline __attribute__((__always_inline__)) int
mpd_isoddcoeff(const mpd_t *dec)
{
return mpd_isoddword(dec->data[0]);
}
/* 0 if dec is positive, 1 if dec is negative */
__inline __attribute__((__always_inline__)) uint8_t
mpd_sign(const mpd_t *dec)
{
return dec->flags & MPD_NEG;
}
/* 1 if dec is positive, -1 if dec is negative */
__inline __attribute__((__always_inline__)) int
mpd_arith_sign(const mpd_t *dec)
{
return 1 - 2 * mpd_isnegative(dec);
}
/* Radix */
__inline __attribute__((__always_inline__)) long
mpd_radix(void)
{
return 10;
}
/* Dynamic decimal */
__inline __attribute__((__always_inline__)) int
mpd_isdynamic(const mpd_t *dec)
{
return !(dec->flags & MPD_STATIC);
}
/* Static decimal */
__inline __attribute__((__always_inline__)) int
mpd_isstatic(const mpd_t *dec)
{
return dec->flags & MPD_STATIC;
}
/* Data of decimal is dynamic */
__inline __attribute__((__always_inline__)) int
mpd_isdynamic_data(const mpd_t *dec)
{
return !(dec->flags & MPD_DATAFLAGS);
}
/* Data of decimal is static */
__inline __attribute__((__always_inline__)) int
mpd_isstatic_data(const mpd_t *dec)
{
return dec->flags & MPD_STATIC_DATA;
}
/* Data of decimal is shared */
__inline __attribute__((__always_inline__)) int
mpd_isshared_data(const mpd_t *dec)
{
return dec->flags & MPD_SHARED_DATA;
}
/* Data of decimal is const */
__inline __attribute__((__always_inline__)) int
mpd_isconst_data(const mpd_t *dec)
{
return dec->flags & MPD_CONST_DATA;
}
/******************************************************************************/
/* Inline memory handling */
/******************************************************************************/
/* Fill destination with zeros */
__inline __attribute__((__always_inline__)) void
mpd_uint_zero(mpd_uint_t *dest, mpd_size_t len)
{
mpd_size_t i;
for (i = 0; i < len; i++) {
dest[i] = 0;
}
}
/* Free a decimal */
__inline __attribute__((__always_inline__)) void
mpd_del(mpd_t *dec)
{
if (mpd_isdynamic_data(dec)) {
mpd_free(dec->data);
}
if (mpd_isdynamic(dec)) {
mpd_free(dec);
}
}
/*
* Resize the coefficient. Existing data up to 'nwords' is left untouched.
* Return 1 on success, 0 otherwise.
*
* Input invariant: MPD_MINALLOC <= result->alloc.
*
* Case nwords == result->alloc:
* 'result' is unchanged. Return 1.
*
* Case nwords > result->alloc:
* Case realloc success:
* The value of 'result' does not change. Return 1.
* Case realloc failure:
* 'result' is NaN, status is updated with MPD_Malloc_error. Return 0.
*
* Case nwords < result->alloc:
* Case is_static_data or realloc failure [1]:
* 'result' is unchanged. Return 1.
* Case realloc success:
* The value of result is undefined (expected). Return 1.
*
*
* [1] In that case the old (now oversized) area is still valid.
*/
__inline __attribute__((__always_inline__)) int
mpd_qresize(mpd_t *result, mpd_ssize_t nwords, uint32_t *status)
{
assert(!mpd_isconst_data(result)); /* illegal operation for a const */
assert(!mpd_isshared_data(result)); /* illegal operation for a shared */
assert(MPD_MINALLOC <= result->alloc);
nwords = (nwords <= MPD_MINALLOC) ? MPD_MINALLOC : nwords;
if (nwords == result->alloc) {
return 1;
}
if (mpd_isstatic_data(result)) {
if (nwords > result->alloc) {
return mpd_switch_to_dyn(result, nwords, status);
}
return 1;
}
return mpd_realloc_dyn(result, nwords, status);
}
/* Same as mpd_qresize, but the complete coefficient (including the old
* memory area!) is initialized to zero. */
__inline __attribute__((__always_inline__)) int
mpd_qresize_zero(mpd_t *result, mpd_ssize_t nwords, uint32_t *status)
{
assert(!mpd_isconst_data(result)); /* illegal operation for a const */
assert(!mpd_isshared_data(result)); /* illegal operation for a shared */
assert(MPD_MINALLOC <= result->alloc);
nwords = (nwords <= MPD_MINALLOC) ? MPD_MINALLOC : nwords;
if (nwords != result->alloc) {
if (mpd_isstatic_data(result)) {
if (nwords > result->alloc) {
return mpd_switch_to_dyn_zero(result, nwords, status);
}
}
else if (!mpd_realloc_dyn(result, nwords, status)) {
return 0;
}
}
mpd_uint_zero(result->data, nwords);
return 1;
}
/*
* Reduce memory size for the coefficient to MPD_MINALLOC. In theory,
* realloc may fail even when reducing the memory size. But in that case
* the old memory area is always big enough, so checking for MPD_Malloc_error
* is not imperative.
*/
__inline __attribute__((__always_inline__)) void
mpd_minalloc(mpd_t *result)
{
assert(!mpd_isconst_data(result)); /* illegal operation for a const */
assert(!mpd_isshared_data(result)); /* illegal operation for a shared */
if (!mpd_isstatic_data(result) && result->alloc > MPD_MINALLOC) {
uint8_t err = 0;
result->data = mpd_realloc(result->data, MPD_MINALLOC,
sizeof *result->data, &err);
if (!err) {
result->alloc = MPD_MINALLOC;
}
}
}
int
mpd_resize(mpd_t *result, mpd_ssize_t nwords, mpd_context_t *ctx)
{
uint32_t status = 0;
if (!mpd_qresize(result, nwords, &status)) {
mpd_addstatus_raise(ctx, status);
return 0;
}
return 1;
}
int
mpd_resize_zero(mpd_t *result, mpd_ssize_t nwords, mpd_context_t *ctx)
{
uint32_t status = 0;
if (!mpd_qresize_zero(result, nwords, &status)) {
mpd_addstatus_raise(ctx, status);
return 0;
}
return 1;
}
/******************************************************************************/
/* Set attributes of a decimal */
/******************************************************************************/
/* Set digits. Assumption: result->len is initialized and > 0. */
inline void
mpd_setdigits(mpd_t *result)
{
mpd_ssize_t wdigits = mpd_word_digits(mpd_msword(result));
result->digits = wdigits + (result->len-1) * MPD_RDIGITS;
}
/* Set sign */
__inline __attribute__((__always_inline__)) void
mpd_set_sign(mpd_t *result, uint8_t sign)
{
result->flags &= ~MPD_NEG;
result->flags |= sign;
}
/* Copy sign from another decimal */
__inline __attribute__((__always_inline__)) void
mpd_signcpy(mpd_t *result, const mpd_t *a)
{
uint8_t sign = a->flags&MPD_NEG;
result->flags &= ~MPD_NEG;
result->flags |= sign;
}
/* Set infinity */
__inline __attribute__((__always_inline__)) void
mpd_set_infinity(mpd_t *result)
{
result->flags &= ~MPD_SPECIAL;
result->flags |= MPD_INF;
}
/* Set qNaN */
__inline __attribute__((__always_inline__)) void
mpd_set_qnan(mpd_t *result)
{
result->flags &= ~MPD_SPECIAL;
result->flags |= MPD_NAN;
}
/* Set sNaN */
__inline __attribute__((__always_inline__)) void
mpd_set_snan(mpd_t *result)
{
result->flags &= ~MPD_SPECIAL;
result->flags |= MPD_SNAN;
}
/* Set to negative */
__inline __attribute__((__always_inline__)) void
mpd_set_negative(mpd_t *result)
{
result->flags |= MPD_NEG;
}
/* Set to positive */
__inline __attribute__((__always_inline__)) void
mpd_set_positive(mpd_t *result)
{
result->flags &= ~MPD_NEG;
}
/* Set to dynamic */
__inline __attribute__((__always_inline__)) void
mpd_set_dynamic(mpd_t *result)
{
result->flags &= ~MPD_STATIC;
}
/* Set to static */
__inline __attribute__((__always_inline__)) void
mpd_set_static(mpd_t *result)
{
result->flags |= MPD_STATIC;
}
/* Set data to dynamic */
__inline __attribute__((__always_inline__)) void
mpd_set_dynamic_data(mpd_t *result)
{
result->flags &= ~MPD_DATAFLAGS;
}
/* Set data to static */
__inline __attribute__((__always_inline__)) void
mpd_set_static_data(mpd_t *result)
{
result->flags &= ~MPD_DATAFLAGS;
result->flags |= MPD_STATIC_DATA;
}
/* Set data to shared */
__inline __attribute__((__always_inline__)) void
mpd_set_shared_data(mpd_t *result)
{
result->flags &= ~MPD_DATAFLAGS;
result->flags |= MPD_SHARED_DATA;
}
/* Set data to const */
__inline __attribute__((__always_inline__)) void
mpd_set_const_data(mpd_t *result)
{
result->flags &= ~MPD_DATAFLAGS;
result->flags |= MPD_CONST_DATA;
}
/* Clear flags, preserving memory attributes. */
__inline __attribute__((__always_inline__)) void
mpd_clear_flags(mpd_t *result)
{
result->flags &= (MPD_STATIC|MPD_DATAFLAGS);
}
/* Set flags, preserving memory attributes. */
__inline __attribute__((__always_inline__)) void
mpd_set_flags(mpd_t *result, uint8_t flags)
{
result->flags &= (MPD_STATIC|MPD_DATAFLAGS);
result->flags |= flags;
}
/* Copy flags, preserving memory attributes of result. */
__inline __attribute__((__always_inline__)) void
mpd_copy_flags(mpd_t *result, const mpd_t *a)
{
uint8_t aflags = a->flags;
result->flags &= (MPD_STATIC|MPD_DATAFLAGS);
result->flags |= (aflags & ~(MPD_STATIC|MPD_DATAFLAGS));
}
/* Initialize a workcontext from ctx. Set traps, flags and newtrap to 0. */
static inline void
mpd_workcontext(mpd_context_t *workctx, const mpd_context_t *ctx)
{
workctx->prec = ctx->prec;
workctx->emax = ctx->emax;
workctx->emin = ctx->emin;
workctx->round = ctx->round;
workctx->traps = 0;
workctx->status = 0;
workctx->newtrap = 0;
workctx->clamp = ctx->clamp;
workctx->allcr = ctx->allcr;
}
/******************************************************************************/
/* Getting and setting parts of decimals */
/******************************************************************************/
/* Flip the sign of a decimal */
static inline void
_mpd_negate(mpd_t *dec)
{
dec->flags ^= MPD_NEG;
}
/* Set coefficient to zero */
void
mpd_zerocoeff(mpd_t *result)
{
mpd_minalloc(result);
result->digits = 1;
result->len = 1;
result->data[0] = 0;
}
/* Set the coefficient to all nines. */
void
mpd_qmaxcoeff(mpd_t *result, const mpd_context_t *ctx, uint32_t *status)
{
mpd_ssize_t len, r;
_mpd_idiv_word(&len, &r, ctx->prec, MPD_RDIGITS);
len = (r == 0) ? len : len+1;
if (!mpd_qresize(result, len, status)) {
return;
}
result->len = len;
result->digits = ctx->prec;
--len;
if (r > 0) {
result->data[len--] = mpd_pow10[r]-1;
}
for (; len >= 0; --len) {
result->data[len] = MPD_RADIX-1;
}
}
/*
* Cut off the most significant digits so that the rest fits in ctx->prec.
* Cannot fail.
*/
static void
_mpd_cap(mpd_t *result, const mpd_context_t *ctx)
{
uint32_t dummy;
mpd_ssize_t len, r;
if (result->len > 0 && result->digits > ctx->prec) {
_mpd_idiv_word(&len, &r, ctx->prec, MPD_RDIGITS);
len = (r == 0) ? len : len+1;
if (r != 0) {
result->data[len-1] %= mpd_pow10[r];
}
len = _mpd_real_size(result->data, len);
/* resize to fewer words cannot fail */
mpd_qresize(result, len, &dummy);
result->len = len;
mpd_setdigits(result);
}
if (mpd_iszero(result)) {
_settriple(result, mpd_sign(result), 0, result->exp);
}
}
/*
* Cut off the most significant digits of a NaN payload so that the rest
* fits in ctx->prec - ctx->clamp. Cannot fail.
*/
static void
_mpd_fix_nan(mpd_t *result, const mpd_context_t *ctx)
{
uint32_t dummy;
mpd_ssize_t prec;
mpd_ssize_t len, r;
prec = ctx->prec - ctx->clamp;
if (result->len > 0 && result->digits > prec) {
if (prec == 0) {
mpd_minalloc(result);
result->len = result->digits = 0;
}
else {
_mpd_idiv_word(&len, &r, prec, MPD_RDIGITS);
len = (r == 0) ? len : len+1;
if (r != 0) {
result->data[len-1] %= mpd_pow10[r];
}
len = _mpd_real_size(result->data, len);
/* resize to fewer words cannot fail */
mpd_qresize(result, len, &dummy);
result->len = len;
mpd_setdigits(result);
if (mpd_iszerocoeff(result)) {
/* NaN0 is not a valid representation */
result->len = result->digits = 0;
}
}
}
}
/*
* Get n most significant digits from a decimal, where 0 < n <= MPD_UINT_DIGITS.
* Assumes MPD_UINT_DIGITS == MPD_RDIGITS+1, which is true for 32 and 64 bit
* machines.
*
* The result of the operation will be in lo. If the operation is impossible,
* hi will be nonzero. This is used to indicate an error.
*/
static inline void
_mpd_get_msdigits(mpd_uint_t *hi, mpd_uint_t *lo, const mpd_t *dec,
unsigned int n)
{
mpd_uint_t r, tmp;
assert(0 < n && n <= MPD_RDIGITS+1);
_mpd_div_word(&tmp, &r, dec->digits, MPD_RDIGITS);
r = (r == 0) ? MPD_RDIGITS : r; /* digits in the most significant word */
*hi = 0;
*lo = dec->data[dec->len-1];
if (n <= r) {
*lo /= mpd_pow10[r-n];
}
else if (dec->len > 1) {
/* at this point 1 <= r < n <= MPD_RDIGITS+1 */
_mpd_mul_words(hi, lo, *lo, mpd_pow10[n-r]);
tmp = dec->data[dec->len-2] / mpd_pow10[MPD_RDIGITS-(n-r)];
*lo = *lo + tmp;
if (*lo < tmp) (*hi)++;
}
}
/******************************************************************************/
/* Gathering information about a decimal */
/******************************************************************************/
/* The real size of the coefficient without leading zero words. */
static inline mpd_ssize_t
_mpd_real_size(mpd_uint_t *data, mpd_ssize_t size)
{
while (size > 1 && data[size-1] == 0) {
size--;
}
return size;
}
/* Return number of trailing zeros. No errors are possible. */
mpd_ssize_t
mpd_trail_zeros(const mpd_t *dec)
{
mpd_uint_t word;
mpd_ssize_t i, tz = 0;
for (i=0; i < dec->len; ++i) {
if (dec->data[i] != 0) {
word = dec->data[i];
tz = i * MPD_RDIGITS;
while (word % 10 == 0) {
word /= 10;
tz++;
}
break;
}
}
return tz;
}
/* Integer: Undefined for specials */
static int
_mpd_isint(const mpd_t *dec)
{
mpd_ssize_t tz;
if (mpd_iszerocoeff(dec)) {
return 1;
}
tz = mpd_trail_zeros(dec);
return (dec->exp + tz >= 0);
}
/* Integer */
int
mpd_isinteger(const mpd_t *dec)
{
if (mpd_isspecial(dec)) {
return 0;
}
return _mpd_isint(dec);
}
/* Word is a power of 10 */
static int
mpd_word_ispow10(mpd_uint_t word)
{
int n;
n = mpd_word_digits(word);
if (word == mpd_pow10[n-1]) {
return 1;
}
return 0;
}
/* Coefficient is a power of 10 */
static int
mpd_coeff_ispow10(const mpd_t *dec)
{
if (mpd_word_ispow10(mpd_msword(dec))) {
if (_mpd_isallzero(dec->data, dec->len-1)) {
return 1;
}
}
return 0;
}
/* All digits of a word are nines */
static int
mpd_word_isallnine(mpd_uint_t word)
{
int n;
n = mpd_word_digits(word);
if (word == mpd_pow10[n]-1) {
return 1;
}
return 0;
}
/* All digits of the coefficient are nines */
static int
mpd_coeff_isallnine(const mpd_t *dec)
{
if (mpd_word_isallnine(mpd_msword(dec))) {
if (_mpd_isallnine(dec->data, dec->len-1)) {
return 1;
}
}
return 0;
}
/* Odd decimal: Undefined for non-integers! */
int
mpd_isodd(const mpd_t *dec)
{
mpd_uint_t q, r;
assert(mpd_isinteger(dec));
if (mpd_iszerocoeff(dec)) return 0;
if (dec->exp < 0) {
_mpd_div_word(&q, &r, -dec->exp, MPD_RDIGITS);
q = dec->data[q] / mpd_pow10[r];
return mpd_isoddword(q);
}
return dec->exp == 0 && mpd_isoddword(dec->data[0]);
}
/* Even: Undefined for non-integers! */
int
mpd_iseven(const mpd_t *dec)
{
return !mpd_isodd(dec);
}
/******************************************************************************/
/* Getting and setting decimals */
/******************************************************************************/
/* Internal function: Set a static decimal from a triple, no error checking. */
static void
_ssettriple(mpd_t *result, uint8_t sign, mpd_uint_t a, mpd_ssize_t exp)
{
mpd_set_flags(result, sign);
result->exp = exp;
_mpd_div_word(&result->data[1], &result->data[0], a, MPD_RADIX);
result->len = (result->data[1] == 0) ? 1 : 2;
mpd_setdigits(result);
}
/* Internal function: Set a decimal from a triple, no error checking. */
static void
_settriple(mpd_t *result, uint8_t sign, mpd_uint_t a, mpd_ssize_t exp)
{
mpd_minalloc(result);
mpd_set_flags(result, sign);
result->exp = exp;
_mpd_div_word(&result->data[1], &result->data[0], a, MPD_RADIX);
result->len = (result->data[1] == 0) ? 1 : 2;
mpd_setdigits(result);
}
/* Set a special number from a triple */
void
mpd_setspecial(mpd_t *result, uint8_t sign, uint8_t type)
{
mpd_minalloc(result);
result->flags &= ~(MPD_NEG|MPD_SPECIAL);
result->flags |= (sign|type);
result->exp = result->digits = result->len = 0;
}
/* Set result of NaN with an error status */
void
mpd_seterror(mpd_t *result, uint32_t flags, uint32_t *status)
{
mpd_minalloc(result);
mpd_set_qnan(result);
mpd_set_positive(result);
result->exp = result->digits = result->len = 0;
*status |= flags;
}
/* quietly set a static decimal from an mpd_ssize_t */
void
mpd_qsset_ssize(mpd_t *result, mpd_ssize_t a, const mpd_context_t *ctx,
uint32_t *status)
{
mpd_uint_t u;
uint8_t sign = MPD_POS;
if (a < 0) {
if (a == MPD_SSIZE_MIN) {
u = (mpd_uint_t)MPD_SSIZE_MAX +
(-(MPD_SSIZE_MIN+MPD_SSIZE_MAX));
}
else {
u = -a;
}
sign = MPD_NEG;
}
else {
u = a;
}
_ssettriple(result, sign, u, 0);
mpd_qfinalize(result, ctx, status);
}
/* quietly set a static decimal from an mpd_uint_t */
void
mpd_qsset_uint(mpd_t *result, mpd_uint_t a, const mpd_context_t *ctx,
uint32_t *status)
{
_ssettriple(result, MPD_POS, a, 0);
mpd_qfinalize(result, ctx, status);
}
/* quietly set a static decimal from an int32_t */
void
mpd_qsset_i32(mpd_t *result, int32_t a, const mpd_context_t *ctx,
uint32_t *status)
{
mpd_qsset_ssize(result, a, ctx, status);
}
/* quietly set a static decimal from a uint32_t */
void
mpd_qsset_u32(mpd_t *result, uint32_t a, const mpd_context_t *ctx,
uint32_t *status)
{
mpd_qsset_uint(result, a, ctx, status);
}
/* quietly set a static decimal from an int64_t */
void
mpd_qsset_i64(mpd_t *result, int64_t a, const mpd_context_t *ctx,
uint32_t *status)
{
mpd_qsset_ssize(result, a, ctx, status);
}
/* quietly set a static decimal from a uint64_t */
void
mpd_qsset_u64(mpd_t *result, uint64_t a, const mpd_context_t *ctx,
uint32_t *status)
{
mpd_qsset_uint(result, a, ctx, status);
}
/* quietly set a decimal from an mpd_ssize_t */
void
mpd_qset_ssize(mpd_t *result, mpd_ssize_t a, const mpd_context_t *ctx,
uint32_t *status)
{
mpd_minalloc(result);
mpd_qsset_ssize(result, a, ctx, status);
}
/* quietly set a decimal from an mpd_uint_t */
void
mpd_qset_uint(mpd_t *result, mpd_uint_t a, const mpd_context_t *ctx,
uint32_t *status)
{
_settriple(result, MPD_POS, a, 0);
mpd_qfinalize(result, ctx, status);
}
/* quietly set a decimal from an int32_t */
void
mpd_qset_i32(mpd_t *result, int32_t a, const mpd_context_t *ctx,
uint32_t *status)
{
mpd_qset_ssize(result, a, ctx, status);
}
/* quietly set a decimal from a uint32_t */
void
mpd_qset_u32(mpd_t *result, uint32_t a, const mpd_context_t *ctx,
uint32_t *status)
{
mpd_qset_uint(result, a, ctx, status);
}
/* quietly set a decimal from an int64_t */
void
mpd_qset_i64(mpd_t *result, int64_t a, const mpd_context_t *ctx,
uint32_t *status)
{
mpd_qset_ssize(result, a, ctx, status);
}
/* quietly set a decimal from a uint64_t */
void
mpd_qset_u64(mpd_t *result, uint64_t a, const mpd_context_t *ctx,
uint32_t *status)
{
mpd_qset_uint(result, a, ctx, status);
}
/*
* Quietly get an mpd_uint_t from a decimal. Assumes
* MPD_UINT_DIGITS == MPD_RDIGITS+1, which is true for
* 32 and 64 bit machines.
*
* If the operation is impossible, MPD_Invalid_operation is set.
*/
static mpd_uint_t
_mpd_qget_uint(int use_sign, const mpd_t *a, uint32_t *status)
{
mpd_t tmp;
mpd_uint_t tmp_data[2];
mpd_uint_t lo, hi;
if (mpd_isspecial(a)) {
*status |= MPD_Invalid_operation;
return MPD_UINT_MAX;
}
if (mpd_iszero(a)) {
return 0;
}
if (use_sign && mpd_isnegative(a)) {
*status |= MPD_Invalid_operation;
return MPD_UINT_MAX;
}
if (a->digits+a->exp > MPD_RDIGITS+1) {
*status |= MPD_Invalid_operation;
return MPD_UINT_MAX;
}
if (a->exp < 0) {
if (!_mpd_isint(a)) {
*status |= MPD_Invalid_operation;
return MPD_UINT_MAX;
}
/* At this point a->digits+a->exp <= MPD_RDIGITS+1,
* so the shift fits. */
tmp.data = tmp_data;
tmp.flags = MPD_STATIC|MPD_STATIC_DATA;
tmp.alloc = 2;
mpd_qsshiftr(&tmp, a, -a->exp);
tmp.exp = 0;
a = &tmp;
}
_mpd_get_msdigits(&hi, &lo, a, MPD_RDIGITS+1);
if (hi) {
*status |= MPD_Invalid_operation;
return MPD_UINT_MAX;
}
if (a->exp > 0) {
_mpd_mul_words(&hi, &lo, lo, mpd_pow10[a->exp]);
if (hi) {
*status |= MPD_Invalid_operation;
return MPD_UINT_MAX;
}
}
return lo;
}
/*
* Sets Invalid_operation for:
* - specials
* - negative numbers (except negative zero)
* - non-integers
* - overflow
*/
mpd_uint_t
mpd_qget_uint(const mpd_t *a, uint32_t *status)
{
return _mpd_qget_uint(1, a, status);
}
/* Same as above, but gets the absolute value, i.e. the sign is ignored. */
mpd_uint_t
mpd_qabs_uint(const mpd_t *a, uint32_t *status)
{
return _mpd_qget_uint(0, a, status);
}
/* quietly get an mpd_ssize_t from a decimal */
mpd_ssize_t
mpd_qget_ssize(const mpd_t *a, uint32_t *status)
{
mpd_uint_t u;
int isneg;
u = mpd_qabs_uint(a, status);
if (*status&MPD_Invalid_operation) {
return MPD_SSIZE_MAX;
}
isneg = mpd_isnegative(a);
if (u <= MPD_SSIZE_MAX) {
return isneg ? -((mpd_ssize_t)u) : (mpd_ssize_t)u;
}
else if (isneg && u+(MPD_SSIZE_MIN+MPD_SSIZE_MAX) == MPD_SSIZE_MAX) {
return MPD_SSIZE_MIN;
}
*status |= MPD_Invalid_operation;
return MPD_SSIZE_MAX;
}
/* quietly get a uint64_t from a decimal */
uint64_t
mpd_qget_u64(const mpd_t *a, uint32_t *status)
{
return mpd_qget_uint(a, status);
}
/* quietly get an int64_t from a decimal */
int64_t
mpd_qget_i64(const mpd_t *a, uint32_t *status)
{
return mpd_qget_ssize(a, status);
}
/* quietly get a uint32_t from a decimal */
uint32_t
mpd_qget_u32(const mpd_t *a, uint32_t *status)
{
uint64_t x = mpd_qget_uint(a, status);
if (*status&MPD_Invalid_operation) {
return UINT32_MAX;
}
if (x > UINT32_MAX) {
*status |= MPD_Invalid_operation;
return UINT32_MAX;
}
return (uint32_t)x;
}
/* quietly get an int32_t from a decimal */
int32_t
mpd_qget_i32(const mpd_t *a, uint32_t *status)
{
int64_t x = mpd_qget_ssize(a, status);
if (*status&MPD_Invalid_operation) {
return INT32_MAX;
}
if (x < INT32_MIN || x > INT32_MAX) {
*status |= MPD_Invalid_operation;
return INT32_MAX;
}
return (int32_t)x;
}
/******************************************************************************/
/* Filtering input of functions, finalizing output of functions */
/******************************************************************************/
/*
* Check if the operand is NaN, copy to result and return 1 if this is
* the case. Copying can fail since NaNs are allowed to have a payload that
* does not fit in MPD_MINALLOC.
*/
int
mpd_qcheck_nan(mpd_t *result, const mpd_t *a, const mpd_context_t *ctx,
uint32_t *status)
{
if (mpd_isnan(a)) {
*status |= mpd_issnan(a) ? MPD_Invalid_operation : 0;
mpd_qcopy(result, a, status);
mpd_set_qnan(result);
_mpd_fix_nan(result, ctx);
return 1;
}
return 0;
}
/*
* Check if either operand is NaN, copy to result and return 1 if this
* is the case. Copying can fail since NaNs are allowed to have a payload
* that does not fit in MPD_MINALLOC.
*/
int
mpd_qcheck_nans(mpd_t *result, const mpd_t *a, const mpd_t *b,
const mpd_context_t *ctx, uint32_t *status)
{
if ((a->flags|b->flags)&(MPD_NAN|MPD_SNAN)) {
const mpd_t *choice = b;
if (mpd_issnan(a)) {
choice = a;
*status |= MPD_Invalid_operation;
}
else if (mpd_issnan(b)) {
*status |= MPD_Invalid_operation;
}
else if (mpd_isqnan(a)) {
choice = a;
}
mpd_qcopy(result, choice, status);
mpd_set_qnan(result);
_mpd_fix_nan(result, ctx);
return 1;
}
return 0;
}
/*
* Check if one of the operands is NaN, copy to result and return 1 if this
* is the case. Copying can fail since NaNs are allowed to have a payload
* that does not fit in MPD_MINALLOC.
*/
static int
mpd_qcheck_3nans(mpd_t *result, const mpd_t *a, const mpd_t *b, const mpd_t *c,
const mpd_context_t *ctx, uint32_t *status)
{
if ((a->flags|b->flags|c->flags)&(MPD_NAN|MPD_SNAN)) {
const mpd_t *choice = c;
if (mpd_issnan(a)) {
choice = a;
*status |= MPD_Invalid_operation;
}
else if (mpd_issnan(b)) {
choice = b;
*status |= MPD_Invalid_operation;
}
else if (mpd_issnan(c)) {
*status |= MPD_Invalid_operation;
}
else if (mpd_isqnan(a)) {
choice = a;
}
else if (mpd_isqnan(b)) {
choice = b;
}
mpd_qcopy(result, choice, status);
mpd_set_qnan(result);
_mpd_fix_nan(result, ctx);
return 1;
}
return 0;
}
/* Check if rounding digit 'rnd' leads to an increment. */
static inline int
_mpd_rnd_incr(const mpd_t *dec, mpd_uint_t rnd, const mpd_context_t *ctx)
{
int ld;
switch (ctx->round) {
case MPD_ROUND_DOWN: case MPD_ROUND_TRUNC:
return 0;
case MPD_ROUND_HALF_UP:
return (rnd >= 5);
case MPD_ROUND_HALF_EVEN:
return (rnd > 5) || ((rnd == 5) && mpd_isoddcoeff(dec));
case MPD_ROUND_CEILING:
return !(rnd == 0 || mpd_isnegative(dec));
case MPD_ROUND_FLOOR:
return !(rnd == 0 || mpd_ispositive(dec));
case MPD_ROUND_HALF_DOWN:
return (rnd > 5);
case MPD_ROUND_UP:
return !(rnd == 0);
case MPD_ROUND_05UP:
ld = (int)mpd_lsd(dec->data[0]);
return (!(rnd == 0) && (ld == 0 || ld == 5));
default:
/* Without a valid context, further results will be undefined. */
return 0; /* GCOV_NOT_REACHED */
}
}
/*
* Apply rounding to a decimal that has been right-shifted into a full
* precision decimal. If an increment leads to an overflow of the precision,
* adjust the coefficient and the exponent and check the new exponent for
* overflow.
*/
static inline void
_mpd_apply_round(mpd_t *dec, mpd_uint_t rnd, const mpd_context_t *ctx,
uint32_t *status)
{
if (_mpd_rnd_incr(dec, rnd, ctx)) {
/* We have a number with exactly ctx->prec digits. The increment
* can only lead to an overflow if the decimal is all nines. In
* that case, the result is a power of ten with prec+1 digits.
*
* If the precision is a multiple of MPD_RDIGITS, this situation is
* detected by _mpd_baseincr returning a carry.
* If the precision is not a multiple of MPD_RDIGITS, we have to
* check if the result has one digit too many.
*/
mpd_uint_t carry = _mpd_baseincr(dec->data, dec->len);
if (carry) {
dec->data[dec->len-1] = mpd_pow10[MPD_RDIGITS-1];
dec->exp += 1;
_mpd_check_exp(dec, ctx, status);
return;
}
mpd_setdigits(dec);
if (dec->digits > ctx->prec) {
mpd_qshiftr_inplace(dec, 1);
dec->exp += 1;
dec->digits = ctx->prec;
_mpd_check_exp(dec, ctx, status);
}
}
}
/*
* Apply rounding to a decimal. Allow overflow of the precision.
*/
static inline void
_mpd_apply_round_excess(mpd_t *dec, mpd_uint_t rnd, const mpd_context_t *ctx,
uint32_t *status)
{
if (_mpd_rnd_incr(dec, rnd, ctx)) {
mpd_uint_t carry = _mpd_baseincr(dec->data, dec->len);
if (carry) {
if (!mpd_qresize(dec, dec->len+1, status)) {
return;
}
dec->data[dec->len] = 1;
dec->len += 1;
}
mpd_setdigits(dec);
}
}
/*
* Apply rounding to a decimal that has been right-shifted into a decimal
* with full precision or less. Return failure if an increment would
* overflow the precision.
*/
static inline int
_mpd_apply_round_fit(mpd_t *dec, mpd_uint_t rnd, const mpd_context_t *ctx,
uint32_t *status)
{
if (_mpd_rnd_incr(dec, rnd, ctx)) {
mpd_uint_t carry = _mpd_baseincr(dec->data, dec->len);
if (carry) {
if (!mpd_qresize(dec, dec->len+1, status)) {
return 0;
}
dec->data[dec->len] = 1;
dec->len += 1;
}
mpd_setdigits(dec);
if (dec->digits > ctx->prec) {
mpd_seterror(dec, MPD_Invalid_operation, status);
return 0;
}
}
return 1;
}
/* Check a normal number for overflow, underflow, clamping. If the operand
is modified, it will be zero, special or (sub)normal with a coefficient
that fits into the current context precision. */
static inline void
_mpd_check_exp(mpd_t *dec, const mpd_context_t *ctx, uint32_t *status)
{
mpd_ssize_t adjexp, etiny, shift;
int rnd;
adjexp = mpd_adjexp(dec);
if (adjexp > ctx->emax) {
if (mpd_iszerocoeff(dec)) {
dec->exp = ctx->emax;
if (ctx->clamp) {
dec->exp -= (ctx->prec-1);
}
mpd_zerocoeff(dec);
*status |= MPD_Clamped;
return;
}
switch (ctx->round) {
case MPD_ROUND_HALF_UP: case MPD_ROUND_HALF_EVEN:
case MPD_ROUND_HALF_DOWN: case MPD_ROUND_UP:
case MPD_ROUND_TRUNC:
mpd_setspecial(dec, mpd_sign(dec), MPD_INF);
break;
case MPD_ROUND_DOWN: case MPD_ROUND_05UP:
mpd_qmaxcoeff(dec, ctx, status);
dec->exp = ctx->emax - ctx->prec + 1;
break;
case MPD_ROUND_CEILING:
if (mpd_isnegative(dec)) {
mpd_qmaxcoeff(dec, ctx, status);
dec->exp = ctx->emax - ctx->prec + 1;
}
else {
mpd_setspecial(dec, MPD_POS, MPD_INF);
}
break;
case MPD_ROUND_FLOOR:
if (mpd_ispositive(dec)) {
mpd_qmaxcoeff(dec, ctx, status);
dec->exp = ctx->emax - ctx->prec + 1;
}
else {
mpd_setspecial(dec, MPD_NEG, MPD_INF);
}
break;
default: /* debug */
abort(); /* GCOV_NOT_REACHED */
}
*status |= MPD_Overflow|MPD_Inexact|MPD_Rounded;
} /* fold down */
else if (ctx->clamp && dec->exp > mpd_etop(ctx)) {
/* At this point adjexp=exp+digits-1 <= emax and exp > etop=emax-prec+1:
* (1) shift = exp -emax+prec-1 > 0
* (2) digits+shift = exp+digits-1 - emax + prec <= prec */
shift = dec->exp - mpd_etop(ctx);
if (!mpd_qshiftl(dec, dec, shift, status)) {
return;
}
dec->exp -= shift;
*status |= MPD_Clamped;
if (!mpd_iszerocoeff(dec) && adjexp < ctx->emin) {
/* Underflow is impossible, since exp < etiny=emin-prec+1
* and exp > etop=emax-prec+1 would imply emax < emin. */
*status |= MPD_Subnormal;
}
}
else if (adjexp < ctx->emin) {
etiny = mpd_etiny(ctx);
if (mpd_iszerocoeff(dec)) {
if (dec->exp < etiny) {
dec->exp = etiny;
mpd_zerocoeff(dec);
*status |= MPD_Clamped;
}
return;
}
*status |= MPD_Subnormal;
if (dec->exp < etiny) {
/* At this point adjexp=exp+digits-1 < emin and exp < etiny=emin-prec+1:
* (1) shift = emin-prec+1 - exp > 0
* (2) digits-shift = exp+digits-1 - emin + prec < prec */
shift = etiny - dec->exp;
rnd = (int)mpd_qshiftr_inplace(dec, shift);
dec->exp = etiny;
/* We always have a spare digit in case of an increment. */
_mpd_apply_round_excess(dec, rnd, ctx, status);
*status |= MPD_Rounded;
if (rnd) {
*status |= (MPD_Inexact|MPD_Underflow);
if (mpd_iszerocoeff(dec)) {
mpd_zerocoeff(dec);
*status |= MPD_Clamped;
}
}
}
/* Case exp >= etiny=emin-prec+1:
* (1) adjexp=exp+digits-1 < emin
* (2) digits < emin-exp+1 <= prec */
}
}
/* Transcendental functions do not always set Underflow reliably,
* since they only use as much precision as is necessary for correct
* rounding. If a result like 1.0000000000e-101 is finalized, there
* is no rounding digit that would trigger Underflow. But we can
* assume Inexact, so a short check suffices. */
static inline void
mpd_check_underflow(mpd_t *dec, const mpd_context_t *ctx, uint32_t *status)
{
if (mpd_adjexp(dec) < ctx->emin && !mpd_iszero(dec) &&
dec->exp < mpd_etiny(ctx)) {
*status |= MPD_Underflow;
}
}
/* Check if a normal number must be rounded after the exponent has been checked. */
static inline void
_mpd_check_round(mpd_t *dec, const mpd_context_t *ctx, uint32_t *status)
{
mpd_uint_t rnd;
mpd_ssize_t shift;
/* must handle specials: _mpd_check_exp() can produce infinities or NaNs */
if (mpd_isspecial(dec)) {
return;
}
if (dec->digits > ctx->prec) {
shift = dec->digits - ctx->prec;
rnd = mpd_qshiftr_inplace(dec, shift);
dec->exp += shift;
_mpd_apply_round(dec, rnd, ctx, status);
*status |= MPD_Rounded;
if (rnd) {
*status |= MPD_Inexact;
}
}
}
/* Finalize all operations. */
void
mpd_qfinalize(mpd_t *result, const mpd_context_t *ctx, uint32_t *status)
{
if (mpd_isspecial(result)) {
if (mpd_isnan(result)) {
_mpd_fix_nan(result, ctx);
}
return;
}
_mpd_check_exp(result, ctx, status);
_mpd_check_round(result, ctx, status);
}
/******************************************************************************/
/* Copying */
/******************************************************************************/
/* Internal function: Copy a decimal, share data with src: USE WITH CARE! */
static inline void
_mpd_copy_shared(mpd_t *dest, const mpd_t *src)
{
dest->flags = src->flags;
dest->exp = src->exp;
dest->digits = src->digits;
dest->len = src->len;
dest->alloc = src->alloc;
dest->data = src->data;
mpd_set_shared_data(dest);
}
/*
* Copy a decimal. In case of an error, status is set to MPD_Malloc_error.
*/
int
mpd_qcopy(mpd_t *result, const mpd_t *a, uint32_t *status)
{
if (result == a) return 1;
if (!mpd_qresize(result, a->len, status)) {
return 0;
}
mpd_copy_flags(result, a);
result->exp = a->exp;
result->digits = a->digits;
result->len = a->len;
memcpy(result->data, a->data, a->len * (sizeof *result->data));
return 1;
}
/*
* Copy to a decimal with a static buffer. The caller has to make sure that
* the buffer is big enough. Cannot fail.
*/
static void
mpd_qcopy_static(mpd_t *result, const mpd_t *a)
{
if (result == a) return;
memcpy(result->data, a->data, a->len * (sizeof *result->data));
mpd_copy_flags(result, a);
result->exp = a->exp;
result->digits = a->digits;
result->len = a->len;
}
/*
* Return a newly allocated copy of the operand. In case of an error,
* status is set to MPD_Malloc_error and the return value is NULL.
*/
mpd_t *
mpd_qncopy(const mpd_t *a)
{
mpd_t *result;
if ((result = mpd_qnew_size(a->len)) == NULL) {
return NULL;
}
memcpy(result->data, a->data, a->len * (sizeof *result->data));
mpd_copy_flags(result, a);
result->exp = a->exp;
result->digits = a->digits;
result->len = a->len;
return result;
}
/*
* Copy a decimal and set the sign to positive. In case of an error, the
* status is set to MPD_Malloc_error.
*/
int
mpd_qcopy_abs(mpd_t *result, const mpd_t *a, uint32_t *status)
{
if (!mpd_qcopy(result, a, status)) {
return 0;
}
mpd_set_positive(result);
return 1;
}
/*
* Copy a decimal and negate the sign. In case of an error, the
* status is set to MPD_Malloc_error.
*/
int
mpd_qcopy_negate(mpd_t *result, const mpd_t *a, uint32_t *status)
{
if (!mpd_qcopy(result, a, status)) {
return 0;
}
_mpd_negate(result);
return 1;
}
/*
* Copy a decimal, setting the sign of the first operand to the sign of the
* second operand. In case of an error, the status is set to MPD_Malloc_error.
*/
int
mpd_qcopy_sign(mpd_t *result, const mpd_t *a, const mpd_t *b, uint32_t *status)
{
uint8_t sign_b = mpd_sign(b); /* result may equal b! */
if (!mpd_qcopy(result, a, status)) {
return 0;
}
mpd_set_sign(result, sign_b);
return 1;
}
/******************************************************************************/
/* Comparisons */
/******************************************************************************/
/*
* For all functions that compare two operands and return an int the usual
* convention applies to the return value:
*
* -1 if op1 < op2
* 0 if op1 == op2
* 1 if op1 > op2
*
* INT_MAX for error
*/
/* Convenience macro. If a and b are not equal, return from the calling
* function with the correct comparison value. */
#define CMP_EQUAL_OR_RETURN(a, b) \
if (a != b) { \
if (a < b) { \
return -1; \
} \
return 1; \
}
/*
* Compare the data of big and small. This function does the equivalent
* of first shifting small to the left and then comparing the data of
* big and small, except that no allocation for the left shift is needed.
*/
static int
_mpd_basecmp(mpd_uint_t *big, mpd_uint_t *small, mpd_size_t n, mpd_size_t m,
mpd_size_t shift)
{
/* spurious uninitialized warnings */
mpd_uint_t l=l, lprev=lprev, h=h;
mpd_uint_t q, r;
mpd_uint_t ph, x;
assert(m > 0 && n >= m && shift > 0);
_mpd_div_word(&q, &r, (mpd_uint_t)shift, MPD_RDIGITS);
if (r != 0) {
ph = mpd_pow10[r];
--m; --n;
_mpd_divmod_pow10(&h, &lprev, small[m--], MPD_RDIGITS-r);
if (h != 0) {
CMP_EQUAL_OR_RETURN(big[n], h)
--n;
}
for (; m != MPD_SIZE_MAX; m--,n--) {
_mpd_divmod_pow10(&h, &l, small[m], MPD_RDIGITS-r);
x = ph * lprev + h;
CMP_EQUAL_OR_RETURN(big[n], x)
lprev = l;
}
x = ph * lprev;
CMP_EQUAL_OR_RETURN(big[q], x)
}
else {
while (--m != MPD_SIZE_MAX) {
CMP_EQUAL_OR_RETURN(big[m+q], small[m])
}
}
return !_mpd_isallzero(big, q);
}
/* Compare two decimals with the same adjusted exponent. */
static int
_mpd_cmp_same_adjexp(const mpd_t *a, const mpd_t *b)
{
mpd_ssize_t shift, i;
if (a->exp != b->exp) {
/* Cannot wrap: a->exp + a->digits = b->exp + b->digits, so
* a->exp - b->exp = b->digits - a->digits. */
shift = a->exp - b->exp;
if (shift > 0) {
return -1 * _mpd_basecmp(b->data, a->data, b->len, a->len, shift);
}
else {
return _mpd_basecmp(a->data, b->data, a->len, b->len, -shift);
}
}
/*
* At this point adjexp(a) == adjexp(b) and a->exp == b->exp,
* so a->digits == b->digits, therefore a->len == b->len.
*/
for (i = a->len-1; i >= 0; --i) {
CMP_EQUAL_OR_RETURN(a->data[i], b->data[i])
}
return 0;
}
/* Compare two numerical values. */
static int
_mpd_cmp(const mpd_t *a, const mpd_t *b)
{
mpd_ssize_t adjexp_a, adjexp_b;
/* equal pointers */
if (a == b) {
return 0;
}
/* infinities */
if (mpd_isinfinite(a)) {
if (mpd_isinfinite(b)) {
return mpd_isnegative(b) - mpd_isnegative(a);
}
return mpd_arith_sign(a);
}
if (mpd_isinfinite(b)) {
return -mpd_arith_sign(b);
}
/* zeros */
if (mpd_iszerocoeff(a)) {
if (mpd_iszerocoeff(b)) {
return 0;
}
return -mpd_arith_sign(b);
}
if (mpd_iszerocoeff(b)) {
return mpd_arith_sign(a);
}
/* different signs */
if (mpd_sign(a) != mpd_sign(b)) {
return mpd_sign(b) - mpd_sign(a);
}
/* different adjusted exponents */
adjexp_a = mpd_adjexp(a);
adjexp_b = mpd_adjexp(b);
if (adjexp_a != adjexp_b) {
if (adjexp_a < adjexp_b) {
return -1 * mpd_arith_sign(a);
}
return mpd_arith_sign(a);
}
/* same adjusted exponents */
return _mpd_cmp_same_adjexp(a, b) * mpd_arith_sign(a);
}
/* Compare the absolutes of two numerical values. */
static int
_mpd_cmp_abs(const mpd_t *a, const mpd_t *b)
{
mpd_ssize_t adjexp_a, adjexp_b;
/* equal pointers */
if (a == b) {
return 0;
}
/* infinities */
if (mpd_isinfinite(a)) {
if (mpd_isinfinite(b)) {
return 0;
}
return 1;
}
if (mpd_isinfinite(b)) {
return -1;
}
/* zeros */
if (mpd_iszerocoeff(a)) {
if (mpd_iszerocoeff(b)) {
return 0;
}
return -1;
}
if (mpd_iszerocoeff(b)) {
return 1;
}
/* different adjusted exponents */
adjexp_a = mpd_adjexp(a);
adjexp_b = mpd_adjexp(b);
if (adjexp_a != adjexp_b) {
if (adjexp_a < adjexp_b) {
return -1;
}
return 1;
}
/* same adjusted exponents */
return _mpd_cmp_same_adjexp(a, b);
}
/* Compare two values and return an integer result. */
int
mpd_qcmp(const mpd_t *a, const mpd_t *b, uint32_t *status)
{
if (mpd_isspecial(a) || mpd_isspecial(b)) {
if (mpd_isnan(a) || mpd_isnan(b)) {
*status |= MPD_Invalid_operation;
return INT_MAX;
}
}
return _mpd_cmp(a, b);
}
/*
* Compare a and b, convert the usual integer result to a decimal and
* store it in 'result'. For convenience, the integer result of the comparison
* is returned. Comparisons involving NaNs return NaN/INT_MAX.
*/
int
mpd_qcompare(mpd_t *result, const mpd_t *a, const mpd_t *b,
const mpd_context_t *ctx, uint32_t *status)
{
int c;
if (mpd_isspecial(a) || mpd_isspecial(b)) {
if (mpd_qcheck_nans(result, a, b, ctx, status)) {
return INT_MAX;
}
}
c = _mpd_cmp(a, b);
_settriple(result, (c < 0), (c != 0), 0);
return c;
}
/* Same as mpd_compare(), but signal for all NaNs, i.e. also for quiet NaNs. */
int
mpd_qcompare_signal(mpd_t *result, const mpd_t *a, const mpd_t *b,
const mpd_context_t *ctx, uint32_t *status)
{
int c;
if (mpd_isspecial(a) || mpd_isspecial(b)) {
if (mpd_qcheck_nans(result, a, b, ctx, status)) {
*status |= MPD_Invalid_operation;
return INT_MAX;
}
}
c = _mpd_cmp(a, b);
_settriple(result, (c < 0), (c != 0), 0);
return c;
}
/* Compare the operands using a total order. */
int
mpd_cmp_total(const mpd_t *a, const mpd_t *b)
{
mpd_t aa, bb;
int nan_a, nan_b;
int c;
if (mpd_sign(a) != mpd_sign(b)) {
return mpd_sign(b) - mpd_sign(a);
}
if (mpd_isnan(a)) {
c = 1;
if (mpd_isnan(b)) {
nan_a = (mpd_isqnan(a)) ? 1 : 0;
nan_b = (mpd_isqnan(b)) ? 1 : 0;
if (nan_b == nan_a) {
if (a->len > 0 && b->len > 0) {
_mpd_copy_shared(&aa, a);
_mpd_copy_shared(&bb, b);
aa.exp = bb.exp = 0;
/* compare payload */
c = _mpd_cmp_abs(&aa, &bb);
}
else {
c = (a->len > 0) - (b->len > 0);
}
}
else {
c = nan_a - nan_b;
}
}
}
else if (mpd_isnan(b)) {
c = -1;
}
else {
c = _mpd_cmp_abs(a, b);
if (c == 0 && a->exp != b->exp) {
c = (a->exp < b->exp) ? -1 : 1;
}
}
return c * mpd_arith_sign(a);
}
/*
* Compare a and b according to a total order, convert the usual integer result
* to a decimal and store it in 'result'. For convenience, the integer result
* of the comparison is returned.
*/
int
mpd_compare_total(mpd_t *result, const mpd_t *a, const mpd_t *b)
{
int c;
c = mpd_cmp_total(a, b);
_settriple(result, (c < 0), (c != 0), 0);
return c;
}
/* Compare the magnitude of the operands using a total order. */
int
mpd_cmp_total_mag(const mpd_t *a, const mpd_t *b)
{
mpd_t aa, bb;
_mpd_copy_shared(&aa, a);
_mpd_copy_shared(&bb, b);
mpd_set_positive(&aa);
mpd_set_positive(&bb);
return mpd_cmp_total(&aa, &bb);
}
/*
* Compare the magnitude of a and b according to a total order, convert the
* the usual integer result to a decimal and store it in 'result'.
* For convenience, the integer result of the comparison is returned.
*/
int
mpd_compare_total_mag(mpd_t *result, const mpd_t *a, const mpd_t *b)
{
int c;
c = mpd_cmp_total_mag(a, b);
_settriple(result, (c < 0), (c != 0), 0);
return c;
}
/* Determine an ordering for operands that are numerically equal. */
static inline int
_mpd_cmp_numequal(const mpd_t *a, const mpd_t *b)
{
int sign_a, sign_b;
int c;
sign_a = mpd_sign(a);
sign_b = mpd_sign(b);
if (sign_a != sign_b) {
c = sign_b - sign_a;
}
else {
c = (a->exp < b->exp) ? -1 : 1;
c *= mpd_arith_sign(a);
}
return c;
}
/******************************************************************************/
/* Shifting the coefficient */
/******************************************************************************/
/*
* Shift the coefficient of the operand to the left, no check for specials.
* Both operands may be the same pointer. If the result length has to be
* increased, mpd_qresize() might fail with MPD_Malloc_error.
*/
int
mpd_qshiftl(mpd_t *result, const mpd_t *a, mpd_ssize_t n, uint32_t *status)
{
mpd_ssize_t size;
assert(!mpd_isspecial(a));
assert(n >= 0);
if (mpd_iszerocoeff(a) || n == 0) {
return mpd_qcopy(result, a, status);
}
size = mpd_digits_to_size(a->digits+n);
if (!mpd_qresize(result, size, status)) {
return 0; /* result is NaN */
}
_mpd_baseshiftl(result->data, a->data, size, a->len, n);
mpd_copy_flags(result, a);
result->exp = a->exp;
result->digits = a->digits+n;
result->len = size;
return 1;
}
/* Determine the rounding indicator if all digits of the coefficient are shifted
* out of the picture. */
static mpd_uint_t
_mpd_get_rnd(const mpd_uint_t *data, mpd_ssize_t len, int use_msd)
{
mpd_uint_t rnd = 0, rest = 0, word;
word = data[len-1];
/* special treatment for the most significant digit if shift == digits */
if (use_msd) {
_mpd_divmod_pow10(&rnd, &rest, word, mpd_word_digits(word)-1);
if (len > 1 && rest == 0) {
rest = !_mpd_isallzero(data, len-1);
}
}
else {
rest = !_mpd_isallzero(data, len);
}
return (rnd == 0 || rnd == 5) ? rnd + !!rest : rnd;
}
/*
* Same as mpd_qshiftr(), but 'result' is an mpd_t with a static coefficient.
* It is the caller's responsibility to ensure that the coefficient is big
* enough. The function cannot fail.
*/
static mpd_uint_t
mpd_qsshiftr(mpd_t *result, const mpd_t *a, mpd_ssize_t n)
{
mpd_uint_t rnd;
mpd_ssize_t size;
assert(!mpd_isspecial(a));
assert(n >= 0);
if (mpd_iszerocoeff(a) || n == 0) {
mpd_qcopy_static(result, a);
return 0;
}
if (n >= a->digits) {
rnd = _mpd_get_rnd(a->data, a->len, (n==a->digits));
mpd_zerocoeff(result);
}
else {
result->digits = a->digits-n;
size = mpd_digits_to_size(result->digits);
rnd = _mpd_baseshiftr(result->data, a->data, a->len, n);
result->len = size;
}
mpd_copy_flags(result, a);
result->exp = a->exp;
return rnd;
}
/*
* Inplace shift of the coefficient to the right, no check for specials.
* Returns the rounding indicator for mpd_rnd_incr().
* The function cannot fail.
*/
mpd_uint_t
mpd_qshiftr_inplace(mpd_t *result, mpd_ssize_t n)
{
uint32_t dummy;
mpd_uint_t rnd;
mpd_ssize_t size;
assert(!mpd_isspecial(result));
assert(n >= 0);
if (mpd_iszerocoeff(result) || n == 0) {
return 0;
}
if (n >= result->digits) {
rnd = _mpd_get_rnd(result->data, result->len, (n==result->digits));
mpd_zerocoeff(result);
}
else {
rnd = _mpd_baseshiftr(result->data, result->data, result->len, n);
result->digits -= n;
size = mpd_digits_to_size(result->digits);
/* reducing the size cannot fail */
mpd_qresize(result, size, &dummy);
result->len = size;
}
return rnd;
}
/*
* Shift the coefficient of the operand to the right, no check for specials.
* Both operands may be the same pointer. Returns the rounding indicator to
* be used by mpd_rnd_incr(). If the result length has to be increased,
* mpd_qcopy() or mpd_qresize() might fail with MPD_Malloc_error. In those
* cases, MPD_UINT_MAX is returned.
*/
mpd_uint_t
mpd_qshiftr(mpd_t *result, const mpd_t *a, mpd_ssize_t n, uint32_t *status)
{
mpd_uint_t rnd;
mpd_ssize_t size;
assert(!mpd_isspecial(a));
assert(n >= 0);
if (mpd_iszerocoeff(a) || n == 0) {
if (!mpd_qcopy(result, a, status)) {
return MPD_UINT_MAX;
}
return 0;
}
if (n >= a->digits) {
rnd = _mpd_get_rnd(a->data, a->len, (n==a->digits));
mpd_zerocoeff(result);
}
else {
result->digits = a->digits-n;
size = mpd_digits_to_size(result->digits);
if (result == a) {
rnd = _mpd_baseshiftr(result->data, a->data, a->len, n);
/* reducing the size cannot fail */
mpd_qresize(result, size, status);
}
else {
if (!mpd_qresize(result, size, status)) {
return MPD_UINT_MAX;
}
rnd = _mpd_baseshiftr(result->data, a->data, a->len, n);
}
result->len = size;
}
mpd_copy_flags(result, a);
result->exp = a->exp;
return rnd;
}
/******************************************************************************/
/* Miscellaneous operations */
/******************************************************************************/
/* Logical And */
void
mpd_qand(mpd_t *result, const mpd_t *a, const mpd_t *b,
const mpd_context_t *ctx, uint32_t *status)
{
const mpd_t *big = a, *small = b;
mpd_uint_t x, y, z, xbit, ybit;
int k, mswdigits;
mpd_ssize_t i;
if (mpd_isspecial(a) || mpd_isspecial(b) ||
mpd_isnegative(a) || mpd_isnegative(b) ||
a->exp != 0 || b->exp != 0) {
mpd_seterror(result, MPD_Invalid_operation, status);
return;
}
if (b->digits > a->digits) {
big = b;
small = a;
}
if (!mpd_qresize(result, big->len, status)) {
return;
}
/* full words */
for (i = 0; i < small->len-1; i++) {
x = small->data[i];
y = big->data[i];
z = 0;
for (k = 0; k < MPD_RDIGITS; k++) {
xbit = x % 10;
x /= 10;
ybit = y % 10;
y /= 10;
if (xbit > 1 || ybit > 1) {
goto invalid_operation;
}
z += (xbit&ybit) ? mpd_pow10[k] : 0;
}
result->data[i] = z;
}
/* most significant word of small */
x = small->data[i];
y = big->data[i];
z = 0;
mswdigits = mpd_word_digits(x);
for (k = 0; k < mswdigits; k++) {
xbit = x % 10;
x /= 10;
ybit = y % 10;
y /= 10;
if (xbit > 1 || ybit > 1) {
goto invalid_operation;
}
z += (xbit&ybit) ? mpd_pow10[k] : 0;
}
result->data[i++] = z;
/* scan the rest of y for digits > 1 */
for (; k < MPD_RDIGITS; k++) {
ybit = y % 10;
y /= 10;
if (ybit > 1) {
goto invalid_operation;
}
}
/* scan the rest of big for digits > 1 */
for (; i < big->len; i++) {
y = big->data[i];
for (k = 0; k < MPD_RDIGITS; k++) {
ybit = y % 10;
y /= 10;
if (ybit > 1) {
goto invalid_operation;
}
}
}
mpd_clear_flags(result);
result->exp = 0;
result->len = _mpd_real_size(result->data, small->len);
mpd_qresize(result, result->len, status);
mpd_setdigits(result);
_mpd_cap(result, ctx);
return;
invalid_operation:
mpd_seterror(result, MPD_Invalid_operation, status);
}
/* Class of an operand. Returns a pointer to the constant name. */
const char *
mpd_class(const mpd_t *a, const mpd_context_t *ctx)
{
if (mpd_isnan(a)) {
if (mpd_isqnan(a))
return "NaN";
else
return "sNaN";
}
else if (mpd_ispositive(a)) {
if (mpd_isinfinite(a))
return "+Infinity";
else if (mpd_iszero(a))
return "+Zero";
else if (mpd_isnormal(a, ctx))
return "+Normal";
else
return "+Subnormal";
}
else {
if (mpd_isinfinite(a))
return "-Infinity";
else if (mpd_iszero(a))
return "-Zero";
else if (mpd_isnormal(a, ctx))
return "-Normal";
else
return "-Subnormal";
}
}
/* Logical Xor */
void
mpd_qinvert(mpd_t *result, const mpd_t *a, const mpd_context_t *ctx,
uint32_t *status)
{
mpd_uint_t x, z, xbit;
mpd_ssize_t i, digits, len;
mpd_ssize_t q, r;
int k;
if (mpd_isspecial(a) || mpd_isnegative(a) || a->exp != 0) {
mpd_seterror(result, MPD_Invalid_operation, status);
return;
}
digits = (a->digits < ctx->prec) ? ctx->prec : a->digits;
_mpd_idiv_word(&q, &r, digits, MPD_RDIGITS);
len = (r == 0) ? q : q+1;
if (!mpd_qresize(result, len, status)) {
return;
}
for (i = 0; i < len; i++) {
x = (i < a->len) ? a->data[i] : 0;
z = 0;
for (k = 0; k < MPD_RDIGITS; k++) {
xbit = x % 10;
x /= 10;
if (xbit > 1) {
goto invalid_operation;
}
z += !xbit ? mpd_pow10[k] : 0;
}
result->data[i] = z;
}
mpd_clear_flags(result);
result->exp = 0;
result->len = _mpd_real_size(result->data, len);
mpd_qresize(result, result->len, status);
mpd_setdigits(result);
_mpd_cap(result, ctx);
return;
invalid_operation:
mpd_seterror(result, MPD_Invalid_operation, status);
}
/* Exponent of the magnitude of the most significant digit of the operand. */
void
mpd_qlogb(mpd_t *result, const mpd_t *a, const mpd_context_t *ctx,
uint32_t *status)
{
if (mpd_isspecial(a)) {
if (mpd_qcheck_nan(result, a, ctx, status)) {
return;
}
mpd_setspecial(result, MPD_POS, MPD_INF);
}
else if (mpd_iszerocoeff(a)) {
mpd_setspecial(result, MPD_NEG, MPD_INF);
*status |= MPD_Division_by_zero;
}
else {
mpd_qset_ssize(result, mpd_adjexp(a), ctx, status);
}
}
/* Logical Or */
void
mpd_qor(mpd_t *result, const mpd_t *a, const mpd_t *b,
const mpd_context_t *ctx, uint32_t *status)
{
const mpd_t *big = a, *small = b;
mpd_uint_t x, y, z, xbit, ybit;
int k, mswdigits;
mpd_ssize_t i;
if (mpd_isspecial(a) || mpd_isspecial(b) ||
mpd_isnegative(a) || mpd_isnegative(b) ||
a->exp != 0 || b->exp != 0) {
mpd_seterror(result, MPD_Invalid_operation, status);
return;
}
if (b->digits > a->digits) {
big = b;
small = a;
}
if (!mpd_qresize(result, big->len, status)) {
return;
}
/* full words */
for (i = 0; i < small->len-1; i++) {
x = small->data[i];
y = big->data[i];
z = 0;
for (k = 0; k < MPD_RDIGITS; k++) {
xbit = x % 10;
x /= 10;
ybit = y % 10;
y /= 10;
if (xbit > 1 || ybit > 1) {
goto invalid_operation;
}
z += (xbit|ybit) ? mpd_pow10[k] : 0;
}
result->data[i] = z;
}
/* most significant word of small */
x = small->data[i];
y = big->data[i];
z = 0;
mswdigits = mpd_word_digits(x);
for (k = 0; k < mswdigits; k++) {
xbit = x % 10;
x /= 10;
ybit = y % 10;
y /= 10;
if (xbit > 1 || ybit > 1) {
goto invalid_operation;
}
z += (xbit|ybit) ? mpd_pow10[k] : 0;
}
/* scan for digits > 1 and copy the rest of y */
for (; k < MPD_RDIGITS; k++) {
ybit = y % 10;
y /= 10;
if (ybit > 1) {
goto invalid_operation;
}
z += ybit*mpd_pow10[k];
}
result->data[i++] = z;
/* scan for digits > 1 and copy the rest of big */
for (; i < big->len; i++) {
y = big->data[i];
for (k = 0; k < MPD_RDIGITS; k++) {
ybit = y % 10;
y /= 10;
if (ybit > 1) {
goto invalid_operation;
}
}
result->data[i] = big->data[i];
}
mpd_clear_flags(result);
result->exp = 0;
result->len = _mpd_real_size(result->data, big->len);
mpd_qresize(result, result->len, status);
mpd_setdigits(result);
_mpd_cap(result, ctx);
return;
invalid_operation:
mpd_seterror(result, MPD_Invalid_operation, status);
}
/*
* Rotate the coefficient of 'a' by 'b' digits. 'b' must be an integer with
* exponent 0.
*/
void
mpd_qrotate(mpd_t *result, const mpd_t *a, const mpd_t *b,
const mpd_context_t *ctx, uint32_t *status)
{
uint32_t workstatus = 0;
MPD_NEW_STATIC(tmp,0,0,0,0);
MPD_NEW_STATIC(big,0,0,0,0);
MPD_NEW_STATIC(small,0,0,0,0);
mpd_ssize_t n, lshift, rshift;
if (mpd_isspecial(a) || mpd_isspecial(b)) {
if (mpd_qcheck_nans(result, a, b, ctx, status)) {
return;
}
}
if (b->exp != 0 || mpd_isinfinite(b)) {
mpd_seterror(result, MPD_Invalid_operation, status);
return;
}
n = mpd_qget_ssize(b, &workstatus);
if (workstatus&MPD_Invalid_operation) {
mpd_seterror(result, MPD_Invalid_operation, status);
return;
}
if (n > ctx->prec || n < -ctx->prec) {
mpd_seterror(result, MPD_Invalid_operation, status);
return;
}
if (mpd_isinfinite(a)) {
mpd_qcopy(result, a, status);
return;
}
if (n >= 0) {
lshift = n;
rshift = ctx->prec-n;
}
else {
lshift = ctx->prec+n;
rshift = -n;
}
if (a->digits > ctx->prec) {
if (!mpd_qcopy(&tmp, a, status)) {
mpd_seterror(result, MPD_Malloc_error, status);
goto finish;
}
_mpd_cap(&tmp, ctx);
a = &tmp;
}
if (!mpd_qshiftl(&big, a, lshift, status)) {
mpd_seterror(result, MPD_Malloc_error, status);
goto finish;
}
_mpd_cap(&big, ctx);
if (mpd_qshiftr(&small, a, rshift, status) == MPD_UINT_MAX) {
mpd_seterror(result, MPD_Malloc_error, status);
goto finish;
}
_mpd_qadd(result, &big, &small, ctx, status);
finish:
mpd_del(&tmp);
mpd_del(&big);
mpd_del(&small);
}
/*
* b must be an integer with exponent 0 and in the range +-2*(emax + prec).
* XXX: In my opinion +-(2*emax + prec) would be more sensible.
* The result is a with the value of b added to its exponent.
*/
void
mpd_qscaleb(mpd_t *result, const mpd_t *a, const mpd_t *b,
const mpd_context_t *ctx, uint32_t *status)
{
uint32_t workstatus = 0;
mpd_uint_t n, maxjump;
int64_t exp;
if (mpd_isspecial(a) || mpd_isspecial(b)) {
if (mpd_qcheck_nans(result, a, b, ctx, status)) {
return;
}
}
if (b->exp != 0 || mpd_isinfinite(b)) {
mpd_seterror(result, MPD_Invalid_operation, status);
return;
}
n = mpd_qabs_uint(b, &workstatus);
/* the spec demands this */
maxjump = 2 * (mpd_uint_t)(ctx->emax + ctx->prec);
if (n > maxjump || workstatus&MPD_Invalid_operation) {
mpd_seterror(result, MPD_Invalid_operation, status);
return;
}
if (mpd_isinfinite(a)) {
mpd_qcopy(result, a, status);
return;
}
exp = a->exp + (int64_t)n * mpd_arith_sign(b);
exp = (exp > MPD_EXP_INF) ? MPD_EXP_INF : exp;
exp = (exp < MPD_EXP_CLAMP) ? MPD_EXP_CLAMP : exp;
mpd_qcopy(result, a, status);
result->exp = (mpd_ssize_t)exp;
mpd_qfinalize(result, ctx, status);
}
/*
* Shift the coefficient by n digits, positive n is a left shift. In the case
* of a left shift, the result is decapitated to fit the context precision. If
* you don't want that, use mpd_shiftl().
*/
void
mpd_qshiftn(mpd_t *result, const mpd_t *a, mpd_ssize_t n, const mpd_context_t *ctx,
uint32_t *status)
{
if (mpd_isspecial(a)) {
if (mpd_qcheck_nan(result, a, ctx, status)) {
return;
}
mpd_qcopy(result, a, status);
return;
}
if (n >= 0 && n <= ctx->prec) {
mpd_qshiftl(result, a, n, status);
_mpd_cap(result, ctx);
}
else if (n < 0 && n >= -ctx->prec) {
if (!mpd_qcopy(result, a, status)) {
return;
}
_mpd_cap(result, ctx);
mpd_qshiftr_inplace(result, -n);
}
else {
mpd_seterror(result, MPD_Invalid_operation, status);
}
}
/*
* Same as mpd_shiftn(), but the shift is specified by the decimal b, which
* must be an integer with a zero exponent. Infinities remain infinities.
*/
void
mpd_qshift(mpd_t *result, const mpd_t *a, const mpd_t *b, const mpd_context_t *ctx,
uint32_t *status)
{
uint32_t workstatus = 0;
mpd_ssize_t n;
if (mpd_isspecial(a) || mpd_isspecial(b)) {
if (mpd_qcheck_nans(result, a, b, ctx, status)) {
return;
}
}
if (b->exp != 0 || mpd_isinfinite(b)) {
mpd_seterror(result, MPD_Invalid_operation, status);
return;
}
n = mpd_qget_ssize(b, &workstatus);
if (workstatus&MPD_Invalid_operation) {
mpd_seterror(result, MPD_Invalid_operation, status);
return;
}
if (n > ctx->prec || n < -ctx->prec) {
mpd_seterror(result, MPD_Invalid_operation, status);
return;
}
if (mpd_isinfinite(a)) {
mpd_qcopy(result, a, status);
return;
}
if (n >= 0) {
mpd_qshiftl(result, a, n, status);
_mpd_cap(result, ctx);
}
else {
if (!mpd_qcopy(result, a, status)) {
return;
}
_mpd_cap(result, ctx);
mpd_qshiftr_inplace(result, -n);
}
}
/* Logical Xor */
void
mpd_qxor(mpd_t *result, const mpd_t *a, const mpd_t *b,
const mpd_context_t *ctx, uint32_t *status)
{
const mpd_t *big = a, *small = b;
mpd_uint_t x, y, z, xbit, ybit;
int k, mswdigits;
mpd_ssize_t i;
if (mpd_isspecial(a) || mpd_isspecial(b) ||
mpd_isnegative(a) || mpd_isnegative(b) ||
a->exp != 0 || b->exp != 0) {
mpd_seterror(result, MPD_Invalid_operation, status);
return;
}
if (b->digits > a->digits) {
big = b;
small = a;
}
if (!mpd_qresize(result, big->len, status)) {
return;
}
/* full words */
for (i = 0; i < small->len-1; i++) {
x = small->data[i];
y = big->data[i];
z = 0;
for (k = 0; k < MPD_RDIGITS; k++) {
xbit = x % 10;
x /= 10;
ybit = y % 10;
y /= 10;
if (xbit > 1 || ybit > 1) {
goto invalid_operation;
}
z += (xbit^ybit) ? mpd_pow10[k] : 0;
}
result->data[i] = z;
}
/* most significant word of small */
x = small->data[i];
y = big->data[i];
z = 0;
mswdigits = mpd_word_digits(x);
for (k = 0; k < mswdigits; k++) {
xbit = x % 10;
x /= 10;
ybit = y % 10;
y /= 10;
if (xbit > 1 || ybit > 1) {
goto invalid_operation;
}
z += (xbit^ybit) ? mpd_pow10[k] : 0;
}
/* scan for digits > 1 and copy the rest of y */
for (; k < MPD_RDIGITS; k++) {
ybit = y % 10;
y /= 10;
if (ybit > 1) {
goto invalid_operation;
}
z += ybit*mpd_pow10[k];
}
result->data[i++] = z;
/* scan for digits > 1 and copy the rest of big */
for (; i < big->len; i++) {
y = big->data[i];
for (k = 0; k < MPD_RDIGITS; k++) {
ybit = y % 10;
y /= 10;
if (ybit > 1) {
goto invalid_operation;
}
}
result->data[i] = big->data[i];
}
mpd_clear_flags(result);
result->exp = 0;
result->len = _mpd_real_size(result->data, big->len);
mpd_qresize(result, result->len, status);
mpd_setdigits(result);
_mpd_cap(result, ctx);
return;
invalid_operation:
mpd_seterror(result, MPD_Invalid_operation, status);
}
/******************************************************************************/
/* Arithmetic operations */
/******************************************************************************/
/*
* The absolute value of a. If a is negative, the result is the same
* as the result of the minus operation. Otherwise, the result is the
* result of the plus operation.
*/
void
mpd_qabs(mpd_t *result, const mpd_t *a, const mpd_context_t *ctx,
uint32_t *status)
{
if (mpd_isspecial(a)) {
if (mpd_qcheck_nan(result, a, ctx, status)) {
return;
}
}
if (mpd_isnegative(a)) {
mpd_qminus(result, a, ctx, status);
}
else {
mpd_qplus(result, a, ctx, status);
}
}
static inline void
_mpd_ptrswap(const mpd_t **a, const mpd_t **b)
{
const mpd_t *t = *a;
*a = *b;
*b = t;
}
/* Add or subtract infinities. */
static void
_mpd_qaddsub_inf(mpd_t *result, const mpd_t *a, const mpd_t *b, uint8_t sign_b,
uint32_t *status)
{
if (mpd_isinfinite(a)) {
if (mpd_sign(a) != sign_b && mpd_isinfinite(b)) {
mpd_seterror(result, MPD_Invalid_operation, status);
}
else {
mpd_setspecial(result, mpd_sign(a), MPD_INF);
}
return;
}
assert(mpd_isinfinite(b));
mpd_setspecial(result, sign_b, MPD_INF);
}
/* Add or subtract non-special numbers. */
static void
_mpd_qaddsub(mpd_t *result, const mpd_t *a, const mpd_t *b, uint8_t sign_b,
const mpd_context_t *ctx, uint32_t *status)
{
const mpd_t *big, *small;
MPD_NEW_STATIC(big_aligned,0,0,0,0);
MPD_NEW_CONST(tiny,0,0,1,1,1,1);
mpd_uint_t carry;
mpd_ssize_t newsize, shift;
mpd_ssize_t exp, i;
int swap = 0;
/* compare exponents */
big = a; small = b;
if (big->exp != small->exp) {
if (small->exp > big->exp) {
_mpd_ptrswap(&big, &small);
swap++;
}
/* align the coefficients */
if (!mpd_iszerocoeff(big)) {
exp = big->exp - 1;
exp += (big->digits > ctx->prec) ? 0 : big->digits-ctx->prec-1;
if (mpd_adjexp(small) < exp) {
/*
* Avoid huge shifts by substituting a value for small that is
* guaranteed to produce the same results.
*
* adjexp(small) < exp if and only if:
*
* bdigits <= prec AND
* bdigits+shift >= prec+2+sdigits AND
* exp = bexp+bdigits-prec-2
*
* 1234567000000000 -> bdigits + shift
* ----------XX1234 -> sdigits
* ----------X1 -> tiny-digits
* |- prec -|
*
* OR
*
* bdigits > prec AND
* shift > sdigits AND
* exp = bexp-1
*
* 1234567892100000 -> bdigits + shift
* ----------XX1234 -> sdigits
* ----------X1 -> tiny-digits
* |- prec -|
*
* If tiny is zero, adding or subtracting is a no-op.
* Otherwise, adding tiny generates a non-zero digit either
* below the rounding digit or the least significant digit
* of big. When subtracting, tiny is in the same position as
* the carry that would be generated by subtracting sdigits.
*/
mpd_copy_flags(&tiny, small);
tiny.exp = exp;
tiny.digits = 1;
tiny.len = 1;
tiny.data[0] = mpd_iszerocoeff(small) ? 0 : 1;
small = &tiny;
}
/* This cannot wrap: the difference is positive and <= maxprec */
shift = big->exp - small->exp;
if (!mpd_qshiftl(&big_aligned, big, shift, status)) {
mpd_seterror(result, MPD_Malloc_error, status);
goto finish;
}
big = &big_aligned;
}
}
result->exp = small->exp;
/* compare length of coefficients */
if (big->len < small->len) {
_mpd_ptrswap(&big, &small);
swap++;
}
newsize = big->len;
if (!mpd_qresize(result, newsize, status)) {
goto finish;
}
if (mpd_sign(a) == sign_b) {
carry = _mpd_baseadd(result->data, big->data, small->data,
big->len, small->len);
if (carry) {
newsize = big->len + 1;
if (!mpd_qresize(result, newsize, status)) {
goto finish;
}
result->data[newsize-1] = carry;
}
result->len = newsize;
mpd_set_flags(result, sign_b);
}
else {
if (big->len == small->len) {
for (i=big->len-1; i >= 0; --i) {
if (big->data[i] != small->data[i]) {
if (big->data[i] < small->data[i]) {
_mpd_ptrswap(&big, &small);
swap++;
}
break;
}
}
}
_mpd_basesub(result->data, big->data, small->data,
big->len, small->len);
newsize = _mpd_real_size(result->data, big->len);
/* resize to smaller cannot fail */
(void)mpd_qresize(result, newsize, status);
result->len = newsize;
sign_b = (swap & 1) ? sign_b : mpd_sign(a);
mpd_set_flags(result, sign_b);
if (mpd_iszerocoeff(result)) {
mpd_set_positive(result);
if (ctx->round == MPD_ROUND_FLOOR) {
mpd_set_negative(result);
}
}
}
mpd_setdigits(result);
finish:
mpd_del(&big_aligned);
}
/* Add a and b. No specials, no finalizing. */
static void
_mpd_qadd(mpd_t *result, const mpd_t *a, const mpd_t *b,
const mpd_context_t *ctx, uint32_t *status)
{
_mpd_qaddsub(result, a, b, mpd_sign(b), ctx, status);
}
/* Subtract b from a. No specials, no finalizing. */
static void
_mpd_qsub(mpd_t *result, const mpd_t *a, const mpd_t *b,
const mpd_context_t *ctx, uint32_t *status)
{
_mpd_qaddsub(result, a, b, !mpd_sign(b), ctx, status);
}
/* Add a and b. */
void
mpd_qadd(mpd_t *result, const mpd_t *a, const mpd_t *b,
const mpd_context_t *ctx, uint32_t *status)
{
if (mpd_isspecial(a) || mpd_isspecial(b)) {
if (mpd_qcheck_nans(result, a, b, ctx, status)) {
return;
}
_mpd_qaddsub_inf(result, a, b, mpd_sign(b), status);
return;
}
_mpd_qaddsub(result, a, b, mpd_sign(b), ctx, status);
mpd_qfinalize(result, ctx, status);
}
/* Add a and b. Set NaN/Invalid_operation if the result is inexact. */
static void
_mpd_qadd_exact(mpd_t *result, const mpd_t *a, const mpd_t *b,
const mpd_context_t *ctx, uint32_t *status)
{
uint32_t workstatus = 0;
mpd_qadd(result, a, b, ctx, &workstatus);
*status |= workstatus;
if (workstatus & (MPD_Inexact|MPD_Rounded|MPD_Clamped)) {
mpd_seterror(result, MPD_Invalid_operation, status);
}
}
/* Subtract b from a. */
void
mpd_qsub(mpd_t *result, const mpd_t *a, const mpd_t *b,
const mpd_context_t *ctx, uint32_t *status)
{
if (mpd_isspecial(a) || mpd_isspecial(b)) {
if (mpd_qcheck_nans(result, a, b, ctx, status)) {
return;
}
_mpd_qaddsub_inf(result, a, b, !mpd_sign(b), status);
return;
}
_mpd_qaddsub(result, a, b, !mpd_sign(b), ctx, status);
mpd_qfinalize(result, ctx, status);
}
/* Subtract b from a. Set NaN/Invalid_operation if the result is inexact. */
static void
_mpd_qsub_exact(mpd_t *result, const mpd_t *a, const mpd_t *b,
const mpd_context_t *ctx, uint32_t *status)
{
uint32_t workstatus = 0;
mpd_qsub(result, a, b, ctx, &workstatus);
*status |= workstatus;
if (workstatus & (MPD_Inexact|MPD_Rounded|MPD_Clamped)) {
mpd_seterror(result, MPD_Invalid_operation, status);
}
}
/* Add decimal and mpd_ssize_t. */
void
mpd_qadd_ssize(mpd_t *result, const mpd_t *a, mpd_ssize_t b,
const mpd_context_t *ctx, uint32_t *status)
{
mpd_context_t maxcontext;
MPD_NEW_STATIC(bb,0,0,0,0);
mpd_maxcontext(&maxcontext);
mpd_qsset_ssize(&bb, b, &maxcontext, status);
mpd_qadd(result, a, &bb, ctx, status);
mpd_del(&bb);
}
/* Add decimal and mpd_uint_t. */
void
mpd_qadd_uint(mpd_t *result, const mpd_t *a, mpd_uint_t b,
const mpd_context_t *ctx, uint32_t *status)
{
mpd_context_t maxcontext;
MPD_NEW_STATIC(bb,0,0,0,0);
mpd_maxcontext(&maxcontext);
mpd_qsset_uint(&bb, b, &maxcontext, status);
mpd_qadd(result, a, &bb, ctx, status);
mpd_del(&bb);
}
/* Subtract mpd_ssize_t from decimal. */
void
mpd_qsub_ssize(mpd_t *result, const mpd_t *a, mpd_ssize_t b,
const mpd_context_t *ctx, uint32_t *status)
{
mpd_context_t maxcontext;
MPD_NEW_STATIC(bb,0,0,0,0);
mpd_maxcontext(&maxcontext);
mpd_qsset_ssize(&bb, b, &maxcontext, status);
mpd_qsub(result, a, &bb, ctx, status);
mpd_del(&bb);
}
/* Subtract mpd_uint_t from decimal. */
void
mpd_qsub_uint(mpd_t *result, const mpd_t *a, mpd_uint_t b,
const mpd_context_t *ctx, uint32_t *status)
{
mpd_context_t maxcontext;
MPD_NEW_STATIC(bb,0,0,0,0);
mpd_maxcontext(&maxcontext);
mpd_qsset_uint(&bb, b, &maxcontext, status);
mpd_qsub(result, a, &bb, ctx, status);
mpd_del(&bb);
}
/* Add decimal and int32_t. */
void
mpd_qadd_i32(mpd_t *result, const mpd_t *a, int32_t b,
const mpd_context_t *ctx, uint32_t *status)
{
mpd_qadd_ssize(result, a, b, ctx, status);
}
/* Add decimal and uint32_t. */
void
mpd_qadd_u32(mpd_t *result, const mpd_t *a, uint32_t b,
const mpd_context_t *ctx, uint32_t *status)
{
mpd_qadd_uint(result, a, b, ctx, status);
}
/* Add decimal and int64_t. */
void
mpd_qadd_i64(mpd_t *result, const mpd_t *a, int64_t b,
const mpd_context_t *ctx, uint32_t *status)
{
mpd_qadd_ssize(result, a, b, ctx, status);
}
/* Add decimal and uint64_t. */
void
mpd_qadd_u64(mpd_t *result, const mpd_t *a, uint64_t b,
const mpd_context_t *ctx, uint32_t *status)
{
mpd_qadd_uint(result, a, b, ctx, status);
}
/* Subtract int32_t from decimal. */
void
mpd_qsub_i32(mpd_t *result, const mpd_t *a, int32_t b,
const mpd_context_t *ctx, uint32_t *status)
{
mpd_qsub_ssize(result, a, b, ctx, status);
}
/* Subtract uint32_t from decimal. */
void
mpd_qsub_u32(mpd_t *result, const mpd_t *a, uint32_t b,
const mpd_context_t *ctx, uint32_t *status)
{
mpd_qsub_uint(result, a, b, ctx, status);
}
/* Subtract int64_t from decimal. */
void
mpd_qsub_i64(mpd_t *result, const mpd_t *a, int64_t b,
const mpd_context_t *ctx, uint32_t *status)
{
mpd_qsub_ssize(result, a, b, ctx, status);
}
/* Subtract uint64_t from decimal. */
void
mpd_qsub_u64(mpd_t *result, const mpd_t *a, uint64_t b,
const mpd_context_t *ctx, uint32_t *status)
{
mpd_qsub_uint(result, a, b, ctx, status);
}
/* Divide infinities. */
static void
_mpd_qdiv_inf(mpd_t *result, const mpd_t *a, const mpd_t *b,
const mpd_context_t *ctx, uint32_t *status)
{
if (mpd_isinfinite(a)) {
if (mpd_isinfinite(b)) {
mpd_seterror(result, MPD_Invalid_operation, status);
return;
}
mpd_setspecial(result, mpd_sign(a)^mpd_sign(b), MPD_INF);
return;
}
assert(mpd_isinfinite(b));
_settriple(result, mpd_sign(a)^mpd_sign(b), 0, mpd_etiny(ctx));
*status |= MPD_Clamped;
}
enum {NO_IDEAL_EXP, SET_IDEAL_EXP};
/* Divide a by b. */
static void
_mpd_qdiv(int action, mpd_t *q, const mpd_t *a, const mpd_t *b,
const mpd_context_t *ctx, uint32_t *status)
{
MPD_NEW_STATIC(aligned,0,0,0,0);
mpd_uint_t ld;
mpd_ssize_t shift, exp, tz;
mpd_ssize_t newsize;
mpd_ssize_t ideal_exp;
mpd_uint_t rem;
uint8_t sign_a = mpd_sign(a);
uint8_t sign_b = mpd_sign(b);
if (mpd_isspecial(a) || mpd_isspecial(b)) {
if (mpd_qcheck_nans(q, a, b, ctx, status)) {
return;
}
_mpd_qdiv_inf(q, a, b, ctx, status);
return;
}
if (mpd_iszerocoeff(b)) {
if (mpd_iszerocoeff(a)) {
mpd_seterror(q, MPD_Division_undefined, status);
}
else {
mpd_setspecial(q, sign_a^sign_b, MPD_INF);
*status |= MPD_Division_by_zero;
}
return;
}
if (mpd_iszerocoeff(a)) {
exp = a->exp - b->exp;
_settriple(q, sign_a^sign_b, 0, exp);
mpd_qfinalize(q, ctx, status);
return;
}
shift = (b->digits - a->digits) + ctx->prec + 1;
ideal_exp = a->exp - b->exp;
exp = ideal_exp - shift;
if (shift > 0) {
if (!mpd_qshiftl(&aligned, a, shift, status)) {
mpd_seterror(q, MPD_Malloc_error, status);
goto finish;
}
a = &aligned;
}
else if (shift < 0) {
shift = -shift;
if (!mpd_qshiftl(&aligned, b, shift, status)) {
mpd_seterror(q, MPD_Malloc_error, status);
goto finish;
}
b = &aligned;
}
newsize = a->len - b->len + 1;
if ((q != b && q != a) || (q == b && newsize > b->len)) {
if (!mpd_qresize(q, newsize, status)) {
mpd_seterror(q, MPD_Malloc_error, status);
goto finish;
}
}
if (b->len == 1) {
rem = _mpd_shortdiv(q->data, a->data, a->len, b->data[0]);
}
else if (b->len <= MPD_NEWTONDIV_CUTOFF) {
int ret = _mpd_basedivmod(q->data, NULL, a->data, b->data,
a->len, b->len);
if (ret < 0) {
mpd_seterror(q, MPD_Malloc_error, status);
goto finish;
}
rem = ret;
}
else {
MPD_NEW_STATIC(r,0,0,0,0);
_mpd_base_ndivmod(q, &r, a, b, status);
if (mpd_isspecial(q) || mpd_isspecial(&r)) {
mpd_setspecial(q, MPD_POS, MPD_NAN);
mpd_del(&r);
goto finish;
}
rem = !mpd_iszerocoeff(&r);
mpd_del(&r);
newsize = q->len;
}
newsize = _mpd_real_size(q->data, newsize);
/* resize to smaller cannot fail */
mpd_qresize(q, newsize, status);
mpd_set_flags(q, sign_a^sign_b);
q->len = newsize;
mpd_setdigits(q);
shift = ideal_exp - exp;
if (rem) {
ld = mpd_lsd(q->data[0]);
if (ld == 0 || ld == 5) {
q->data[0] += 1;
}
}
else if (action == SET_IDEAL_EXP && shift > 0) {
tz = mpd_trail_zeros(q);
shift = (tz > shift) ? shift : tz;
mpd_qshiftr_inplace(q, shift);
exp += shift;
}
q->exp = exp;
finish:
mpd_del(&aligned);
mpd_qfinalize(q, ctx, status);
}
/* Divide a by b. */
void
mpd_qdiv(mpd_t *q, const mpd_t *a, const mpd_t *b,
const mpd_context_t *ctx, uint32_t *status)
{
_mpd_qdiv(SET_IDEAL_EXP, q, a, b, ctx, status);
}
/* Internal function. */
static void
_mpd_qdivmod(mpd_t *q, mpd_t *r, const mpd_t *a, const mpd_t *b,
const mpd_context_t *ctx, uint32_t *status)
{
MPD_NEW_STATIC(aligned,0,0,0,0);
mpd_ssize_t qsize, rsize;
mpd_ssize_t ideal_exp, expdiff, shift;
uint8_t sign_a = mpd_sign(a);
uint8_t sign_ab = mpd_sign(a)^mpd_sign(b);
ideal_exp = (a->exp > b->exp) ? b->exp : a->exp;
if (mpd_iszerocoeff(a)) {
if (!mpd_qcopy(r, a, status)) {
goto nanresult; /* GCOV_NOT_REACHED */
}
r->exp = ideal_exp;
_settriple(q, sign_ab, 0, 0);
return;
}
expdiff = mpd_adjexp(a) - mpd_adjexp(b);
if (expdiff < 0) {
if (a->exp > b->exp) {
/* positive and less than b->digits - a->digits */
shift = a->exp - b->exp;
if (!mpd_qshiftl(r, a, shift, status)) {
goto nanresult;
}
r->exp = ideal_exp;
}
else {
if (!mpd_qcopy(r, a, status)) {
goto nanresult;
}
}
_settriple(q, sign_ab, 0, 0);
return;
}
if (expdiff > ctx->prec) {
*status |= MPD_Division_impossible;
goto nanresult;
}
/*
* At this point we have:
* (1) 0 <= a->exp + a->digits - b->exp - b->digits <= prec
* (2) a->exp - b->exp >= b->digits - a->digits
* (3) a->exp - b->exp <= prec + b->digits - a->digits
*/
if (a->exp != b->exp) {
shift = a->exp - b->exp;
if (shift > 0) {
/* by (3), after the shift a->digits <= prec + b->digits */
if (!mpd_qshiftl(&aligned, a, shift, status)) {
goto nanresult;
}
a = &aligned;
}
else {
shift = -shift;
/* by (2), after the shift b->digits <= a->digits */
if (!mpd_qshiftl(&aligned, b, shift, status)) {
goto nanresult;
}
b = &aligned;
}
}
qsize = a->len - b->len + 1;
if (!(q == a && qsize < a->len) && !(q == b && qsize < b->len)) {
if (!mpd_qresize(q, qsize, status)) {
goto nanresult;
}
}
rsize = b->len;
if (!(r == a && rsize < a->len)) {
if (!mpd_qresize(r, rsize, status)) {
goto nanresult;
}
}
if (b->len == 1) {
if (a->len == 1) {
_mpd_div_word(&q->data[0], &r->data[0], a->data[0], b->data[0]);
}
else {
r->data[0] = _mpd_shortdiv(q->data, a->data, a->len, b->data[0]);
}
}
else if (b->len <= MPD_NEWTONDIV_CUTOFF) {
int ret;
ret = _mpd_basedivmod(q->data, r->data, a->data, b->data,
a->len, b->len);
if (ret == -1) {
*status |= MPD_Malloc_error;
goto nanresult;
}
}
else {
_mpd_base_ndivmod(q, r, a, b, status);
if (mpd_isspecial(q) || mpd_isspecial(r)) {
goto nanresult;
}
qsize = q->len;
rsize = r->len;
}
qsize = _mpd_real_size(q->data, qsize);
/* resize to smaller cannot fail */
mpd_qresize(q, qsize, status);
q->len = qsize;
mpd_setdigits(q);
mpd_set_flags(q, sign_ab);
q->exp = 0;
if (q->digits > ctx->prec) {
*status |= MPD_Division_impossible;
goto nanresult;
}
rsize = _mpd_real_size(r->data, rsize);
/* resize to smaller cannot fail */
mpd_qresize(r, rsize, status);
r->len = rsize;
mpd_setdigits(r);
mpd_set_flags(r, sign_a);
r->exp = ideal_exp;
out:
mpd_del(&aligned);
return;
nanresult:
mpd_setspecial(q, MPD_POS, MPD_NAN);
mpd_setspecial(r, MPD_POS, MPD_NAN);
goto out;
}
/* Integer division with remainder. */
void
mpd_qdivmod(mpd_t *q, mpd_t *r, const mpd_t *a, const mpd_t *b,
const mpd_context_t *ctx, uint32_t *status)
{
uint8_t sign = mpd_sign(a)^mpd_sign(b);
if (mpd_isspecial(a) || mpd_isspecial(b)) {
if (mpd_qcheck_nans(q, a, b, ctx, status)) {
mpd_qcopy(r, q, status);
return;
}
if (mpd_isinfinite(a)) {
if (mpd_isinfinite(b)) {
mpd_setspecial(q, MPD_POS, MPD_NAN);
}
else {
mpd_setspecial(q, sign, MPD_INF);
}
mpd_setspecial(r, MPD_POS, MPD_NAN);
*status |= MPD_Invalid_operation;
return;
}
if (mpd_isinfinite(b)) {
if (!mpd_qcopy(r, a, status)) {
mpd_seterror(q, MPD_Malloc_error, status);
return;
}
mpd_qfinalize(r, ctx, status);
_settriple(q, sign, 0, 0);
return;
}
/* debug */
abort(); /* GCOV_NOT_REACHED */
}
if (mpd_iszerocoeff(b)) {
if (mpd_iszerocoeff(a)) {
mpd_setspecial(q, MPD_POS, MPD_NAN);
mpd_setspecial(r, MPD_POS, MPD_NAN);
*status |= MPD_Division_undefined;
}
else {
mpd_setspecial(q, sign, MPD_INF);
mpd_setspecial(r, MPD_POS, MPD_NAN);
*status |= (MPD_Division_by_zero|MPD_Invalid_operation);
}
return;
}
_mpd_qdivmod(q, r, a, b, ctx, status);
mpd_qfinalize(q, ctx, status);
mpd_qfinalize(r, ctx, status);
}
void
mpd_qdivint(mpd_t *q, const mpd_t *a, const mpd_t *b,
const mpd_context_t *ctx, uint32_t *status)
{
MPD_NEW_STATIC(r,0,0,0,0);
uint8_t sign = mpd_sign(a)^mpd_sign(b);
if (mpd_isspecial(a) || mpd_isspecial(b)) {
if (mpd_qcheck_nans(q, a, b, ctx, status)) {
return;
}
if (mpd_isinfinite(a) && mpd_isinfinite(b)) {
mpd_seterror(q, MPD_Invalid_operation, status);
return;
}
if (mpd_isinfinite(a)) {
mpd_setspecial(q, sign, MPD_INF);
return;
}
if (mpd_isinfinite(b)) {
_settriple(q, sign, 0, 0);
return;
}
unreachable;
}
if (mpd_iszerocoeff(b)) {
if (mpd_iszerocoeff(a)) {
mpd_seterror(q, MPD_Division_undefined, status);
}
else {
mpd_setspecial(q, sign, MPD_INF);
*status |= MPD_Division_by_zero;
}
return;
}
_mpd_qdivmod(q, &r, a, b, ctx, status);
mpd_del(&r);
mpd_qfinalize(q, ctx, status);
}
/* Divide decimal by mpd_ssize_t. */
void
mpd_qdiv_ssize(mpd_t *result, const mpd_t *a, mpd_ssize_t b,
const mpd_context_t *ctx, uint32_t *status)
{
mpd_context_t maxcontext;
MPD_NEW_STATIC(bb,0,0,0,0);
mpd_maxcontext(&maxcontext);
mpd_qsset_ssize(&bb, b, &maxcontext, status);
mpd_qdiv(result, a, &bb, ctx, status);
mpd_del(&bb);
}
/* Divide decimal by mpd_uint_t. */
void
mpd_qdiv_uint(mpd_t *result, const mpd_t *a, mpd_uint_t b,
const mpd_context_t *ctx, uint32_t *status)
{
mpd_context_t maxcontext;
MPD_NEW_STATIC(bb,0,0,0,0);
mpd_maxcontext(&maxcontext);
mpd_qsset_uint(&bb, b, &maxcontext, status);
mpd_qdiv(result, a, &bb, ctx, status);
mpd_del(&bb);
}
/* Divide decimal by int32_t. */
void
mpd_qdiv_i32(mpd_t *result, const mpd_t *a, int32_t b,
const mpd_context_t *ctx, uint32_t *status)
{
mpd_qdiv_ssize(result, a, b, ctx, status);
}
/* Divide decimal by uint32_t. */
void
mpd_qdiv_u32(mpd_t *result, const mpd_t *a, uint32_t b,
const mpd_context_t *ctx, uint32_t *status)
{
mpd_qdiv_uint(result, a, b, ctx, status);
}
/* Divide decimal by int64_t. */
void
mpd_qdiv_i64(mpd_t *result, const mpd_t *a, int64_t b,
const mpd_context_t *ctx, uint32_t *status)
{
mpd_qdiv_ssize(result, a, b, ctx, status);
}
/* Divide decimal by uint64_t. */
void
mpd_qdiv_u64(mpd_t *result, const mpd_t *a, uint64_t b,
const mpd_context_t *ctx, uint32_t *status)
{
mpd_qdiv_uint(result, a, b, ctx, status);
}
/* Pad the result with trailing zeros if it has fewer digits than prec. */
static void
_mpd_zeropad(mpd_t *result, const mpd_context_t *ctx, uint32_t *status)
{
if (!mpd_isspecial(result) && !mpd_iszero(result) &&
result->digits < ctx->prec) {
mpd_ssize_t shift = ctx->prec - result->digits;
mpd_qshiftl(result, result, shift, status);
result->exp -= shift;
}
}
/* Check if the result is guaranteed to be one. */
static int
_mpd_qexp_check_one(mpd_t *result, const mpd_t *a, const mpd_context_t *ctx,
uint32_t *status)
{
MPD_NEW_CONST(lim,0,-(ctx->prec+1),1,1,1,9);
MPD_NEW_SHARED(aa, a);
mpd_set_positive(&aa);
/* abs(a) <= 9 * 10**(-prec-1) */
if (_mpd_cmp(&aa, &lim) <= 0) {
_settriple(result, 0, 1, 0);
*status |= MPD_Rounded|MPD_Inexact;
return 1;
}
return 0;
}
/*
* Get the number of iterations for the Horner scheme in _mpd_qexp().
*/
static inline mpd_ssize_t
_mpd_get_exp_iterations(const mpd_t *r, mpd_ssize_t p)
{
mpd_ssize_t log10pbyr; /* lower bound for log10(p / abs(r)) */
mpd_ssize_t n;
assert(p >= 10);
assert(!mpd_iszero(r));
assert(-p < mpd_adjexp(r) && mpd_adjexp(r) <= -1);
if (p > (mpd_ssize_t)(1ULL<<52)) {
return MPD_SSIZE_MAX;
}
/*
* Lower bound for log10(p / abs(r)): adjexp(p) - (adjexp(r) + 1)
* At this point (for CONFIG_64, CONFIG_32 is not problematic):
* 1) 10 <= p <= 2**52
* 2) -p < adjexp(r) <= -1
* 3) 1 <= log10pbyr <= 2**52 + 14
*/
log10pbyr = (mpd_word_digits(p)-1) - (mpd_adjexp(r)+1);
/*
* The numerator in the paper is 1.435 * p - 1.182, calculated
* exactly. We compensate for rounding errors by using 1.43503.
* ACL2 proofs:
* 1) exp-iter-approx-lower-bound: The term below evaluated
* in 53-bit floating point arithmetic is greater than or
* equal to the exact term used in the paper.
* 2) exp-iter-approx-upper-bound: The term below is less than
* or equal to 3/2 * p <= 3/2 * 2**52.
*/
n = (mpd_ssize_t)ceil((1.43503*(double)p - 1.182) / (double)log10pbyr);
return n >= 3 ? n : 3;
}
/*
* Internal function, specials have been dealt with. Apart from Overflow
* and Underflow, two cases must be considered for the error of the result:
*
* 1) abs(a) <= 9 * 10**(-prec-1) ==> result == 1
*
* Absolute error: abs(1 - e**x) < 10**(-prec)
* -------------------------------------------
*
* 2) abs(a) > 9 * 10**(-prec-1)
*
* Relative error: abs(result - e**x) < 0.5 * 10**(-prec) * e**x
* -------------------------------------------------------------
*
* The algorithm is from Hull&Abrham, Variable Precision Exponential Function,
* ACM Transactions on Mathematical Software, Vol. 12, No. 2, June 1986.
*
* Main differences:
*
* - The number of iterations for the Horner scheme is calculated using
* 53-bit floating point arithmetic.
*
* - In the error analysis for ER (relative error accumulated in the
* evaluation of the truncated series) the reduced operand r may
* have any number of digits.
* ACL2 proof: exponent-relative-error
*
* - The analysis for early abortion has been adapted for the mpd_t
* ranges.
*/
static void
_mpd_qexp(mpd_t *result, const mpd_t *a, const mpd_context_t *ctx,
uint32_t *status)
{
mpd_context_t workctx;
MPD_NEW_STATIC(tmp,0,0,0,0);
MPD_NEW_STATIC(sum,0,0,0,0);
MPD_NEW_CONST(word,0,0,1,1,1,1);
mpd_ssize_t j, n, t;
assert(!mpd_isspecial(a));
if (mpd_iszerocoeff(a)) {
_settriple(result, MPD_POS, 1, 0);
return;
}
/*
* We are calculating e^x = e^(r*10^t) = (e^r)^(10^t), where abs(r) < 1 and t >= 0.
*
* If t > 0, we have:
*
* (1) 0.1 <= r < 1, so e^0.1 <= e^r. If t > MAX_T, overflow occurs:
*
* MAX-EMAX+1 < log10(e^(0.1*10*t)) <= log10(e^(r*10^t)) < adjexp(e^(r*10^t))+1
*
* (2) -1 < r <= -0.1, so e^r <= e^-0.1. If t > MAX_T, underflow occurs:
*
* adjexp(e^(r*10^t)) <= log10(e^(r*10^t)) <= log10(e^(-0.1*10^t)) < MIN-ETINY
*/
#define MPD_EXP_MAX_T 19
t = a->digits + a->exp;
t = (t > 0) ? t : 0;
if (t > MPD_EXP_MAX_T) {
if (mpd_ispositive(a)) {
mpd_setspecial(result, MPD_POS, MPD_INF);
*status |= MPD_Overflow|MPD_Inexact|MPD_Rounded;
}
else {
_settriple(result, MPD_POS, 0, mpd_etiny(ctx));
*status |= (MPD_Inexact|MPD_Rounded|MPD_Subnormal|
MPD_Underflow|MPD_Clamped);
}
return;
}
/* abs(a) <= 9 * 10**(-prec-1) */
if (_mpd_qexp_check_one(result, a, ctx, status)) {
return;
}
mpd_maxcontext(&workctx);
workctx.prec = ctx->prec + t + 2;
workctx.prec = (workctx.prec < 10) ? 10 : workctx.prec;
workctx.round = MPD_ROUND_HALF_EVEN;
if (!mpd_qcopy(result, a, status)) {
return;
}
result->exp -= t;
/*
* At this point:
* 1) 9 * 10**(-prec-1) < abs(a)
* 2) 9 * 10**(-prec-t-1) < abs(r)
* 3) log10(9) - prec - t - 1 < log10(abs(r)) < adjexp(abs(r)) + 1
* 4) - prec - t - 2 < adjexp(abs(r)) <= -1
*/
n = _mpd_get_exp_iterations(result, workctx.prec);
if (n == MPD_SSIZE_MAX) {
mpd_seterror(result, MPD_Invalid_operation, status); /* GCOV_UNLIKELY */
return; /* GCOV_UNLIKELY */
}
_settriple(&sum, MPD_POS, 1, 0);
for (j = n-1; j >= 1; j--) {
word.data[0] = j;
mpd_setdigits(&word);
mpd_qdiv(&tmp, result, &word, &workctx, &workctx.status);
mpd_qfma(&sum, &sum, &tmp, &one, &workctx, &workctx.status);
}
_mpd_qpow_uint(result, &sum, mpd_pow10[t], MPD_POS, &workctx, status);
mpd_del(&tmp);
mpd_del(&sum);
*status |= (workctx.status&MPD_Errors);
*status |= (MPD_Inexact|MPD_Rounded);
}
/* exp(a) */
void
mpd_qexp(mpd_t *result, const mpd_t *a, const mpd_context_t *ctx,
uint32_t *status)
{
mpd_context_t workctx;
if (mpd_isspecial(a)) {
if (mpd_qcheck_nan(result, a, ctx, status)) {
return;
}
if (mpd_isnegative(a)) {
_settriple(result, MPD_POS, 0, 0);
}
else {
mpd_setspecial(result, MPD_POS, MPD_INF);
}
return;
}
if (mpd_iszerocoeff(a)) {
_settriple(result, MPD_POS, 1, 0);
return;
}
workctx = *ctx;
workctx.round = MPD_ROUND_HALF_EVEN;
if (ctx->allcr) {
MPD_NEW_STATIC(t1, 0,0,0,0);
MPD_NEW_STATIC(t2, 0,0,0,0);
MPD_NEW_STATIC(ulp, 0,0,0,0);
MPD_NEW_STATIC(aa, 0,0,0,0);
mpd_ssize_t prec;
mpd_ssize_t ulpexp;
uint32_t workstatus;
if (result == a) {
if (!mpd_qcopy(&aa, a, status)) {
mpd_seterror(result, MPD_Malloc_error, status);
return;
}
a = &aa;
}
workctx.clamp = 0;
prec = ctx->prec + 3;
while (1) {
workctx.prec = prec;
workstatus = 0;
_mpd_qexp(result, a, &workctx, &workstatus);
*status |= workstatus;
ulpexp = result->exp + result->digits - workctx.prec;
if (workstatus & MPD_Underflow) {
/* The effective work precision is result->digits. */
ulpexp = result->exp;
}
_ssettriple(&ulp, MPD_POS, 1, ulpexp);
/*
* At this point [1]:
* 1) abs(result - e**x) < 0.5 * 10**(-prec) * e**x
* 2) result - ulp < e**x < result + ulp
* 3) result - ulp < result < result + ulp
*
* If round(result-ulp)==round(result+ulp), then
* round(result)==round(e**x). Therefore the result
* is correctly rounded.
*
* [1] If abs(a) <= 9 * 10**(-prec-1), use the absolute
* error for a similar argument.
*/
workctx.prec = ctx->prec;
mpd_qadd(&t1, result, &ulp, &workctx, &workctx.status);
mpd_qsub(&t2, result, &ulp, &workctx, &workctx.status);
if (mpd_isspecial(result) || mpd_iszerocoeff(result) ||
mpd_qcmp(&t1, &t2, status) == 0) {
workctx.clamp = ctx->clamp;
_mpd_zeropad(result, &workctx, status);
mpd_check_underflow(result, &workctx, status);
mpd_qfinalize(result, &workctx, status);
break;
}
prec += MPD_RDIGITS;
}
mpd_del(&t1);
mpd_del(&t2);
mpd_del(&ulp);
mpd_del(&aa);
}
else {
_mpd_qexp(result, a, &workctx, status);
_mpd_zeropad(result, &workctx, status);
mpd_check_underflow(result, &workctx, status);
mpd_qfinalize(result, &workctx, status);
}
}
/* Fused multiply-add: (a * b) + c, with a single final rounding. */
void
mpd_qfma(mpd_t *result, const mpd_t *a, const mpd_t *b, const mpd_t *c,
const mpd_context_t *ctx, uint32_t *status)
{
uint32_t workstatus = 0;
mpd_t *cc = NULL;
if (result == c) {
if ((cc = mpd_qncopy(c)) == NULL) {
mpd_seterror(result, MPD_Malloc_error, status);
return;
}
c = cc;
}
_mpd_qmul(result, a, b, ctx, &workstatus);
if (!(workstatus&MPD_Invalid_operation)) {
mpd_qadd(result, result, c, ctx, &workstatus);
}
if (cc) mpd_del(cc);
*status |= workstatus;
}
/*
* Schedule the optimal precision increase for the Newton iteration.
* v := input operand
* z_0 := initial approximation
* initprec := natural number such that abs(log(v) - z_0) < 10**-initprec
* maxprec := target precision
*
* For convenience the output klist contains the elements in reverse order:
* klist := [k_n-1, ..., k_0], where
* 1) k_0 <= initprec and
* 2) abs(log(v) - result) < 10**(-2*k_n-1 + 1) <= 10**-maxprec.
*/
static inline int
ln_schedule_prec(mpd_ssize_t klist[MPD_MAX_PREC_LOG2], mpd_ssize_t maxprec,
mpd_ssize_t initprec)
{
mpd_ssize_t k;
int i;
assert(maxprec >= 2 && initprec >= 2);
if (maxprec <= initprec) return -1;
i = 0; k = maxprec;
do {
k = (k+2) / 2;
klist[i++] = k;
} while (k > initprec);
return i-1;
}
#if MPD_RDIGITS != 19
#error "mpdecimal.c: MPD_RDIGITS must be 19."
#endif
/* The constants have been verified with both decimal.py and mpfr. */
static const mpd_uint_t mpd_ln10_data[MPD_MINALLOC_MAX] = {
6983716328982174407ULL, 9089704281976336583ULL, 1515961135648465461ULL,
4416816335727555703ULL, 2900988039194170265ULL, 2307925037472986509ULL,
107598438319191292ULL, 3466624107184669231ULL, 4450099781311469159ULL,
9807828059751193854ULL, 7713456862091670584ULL, 1492198849978748873ULL,
6528728696511086257ULL, 2385392051446341972ULL, 8692180205189339507ULL,
6518769751037497088ULL, 2375253577097505395ULL, 9095610299291824318ULL,
982748238504564801ULL, 5438635917781170543ULL, 7547331541421808427ULL,
752371033310119785ULL, 3171643095059950878ULL, 9785265383207606726ULL,
2932258279850258550ULL, 5497347726624257094ULL, 2976979522110718264ULL,
9221477656763693866ULL, 1979650047149510504ULL, 6674183485704422507ULL,
9702766860595249671ULL, 9278096762712757753ULL, 9314848524948644871ULL,
6826928280848118428ULL, 754403708474699401ULL, 230105703089634572ULL,
1929203337658714166ULL, 7589402567763113569ULL, 4208241314695689016ULL,
2922455440575892572ULL, 9356734206705811364ULL, 2684916746550586856ULL,
644507064800027750ULL, 9476834636167921018ULL, 5659121373450747856ULL,
2835522011480466371ULL, 6470806855677432162ULL, 7141748003688084012ULL,
9619404400222105101ULL, 5504893431493939147ULL, 6674744042432743651ULL,
2287698219886746543ULL, 7773262884616336622ULL, 1985283935053089653ULL,
4680843799894826233ULL, 8168948290720832555ULL, 8067566662873690987ULL,
6248633409525465082ULL, 9829834196778404228ULL, 3524802359972050895ULL,
3327900967572609677ULL, 110148862877297603ULL, 179914546843642076ULL,
2302585092994045684ULL
};
/* _mpd_ln10 is used directly for precisions smaller than MINALLOC_MAX*RDIGITS.
Otherwise, it serves as the initial approximation for calculating ln(10). */
static const mpd_t _mpd_ln10 = {
MPD_STATIC|MPD_CONST_DATA, -(MPD_MINALLOC_MAX*MPD_RDIGITS-1),
MPD_MINALLOC_MAX*MPD_RDIGITS, MPD_MINALLOC_MAX, MPD_MINALLOC_MAX,
(mpd_uint_t *)mpd_ln10_data
};
/*
* Set 'result' to log(10).
* Ulp error: abs(result - log(10)) < ulp(log(10))
* Relative error: abs(result - log(10)) < 5 * 10**-prec * log(10)
*
* NOTE: The relative error is not derived from the ulp error, but
* calculated separately using the fact that 23/10 < log(10) < 24/10.
*/
void
mpd_qln10(mpd_t *result, mpd_ssize_t prec, uint32_t *status)
{
mpd_context_t varcontext, maxcontext;
MPD_NEW_STATIC(tmp, 0,0,0,0);
MPD_NEW_CONST(static10, 0,0,2,1,1,10);
mpd_ssize_t klist[MPD_MAX_PREC_LOG2];
mpd_uint_t rnd;
mpd_ssize_t shift;
int i;
assert(prec >= 1);
shift = MPD_MINALLOC_MAX*MPD_RDIGITS-prec;
shift = shift < 0 ? 0 : shift;
rnd = mpd_qshiftr(result, &_mpd_ln10, shift, status);
if (rnd == MPD_UINT_MAX) {
mpd_seterror(result, MPD_Malloc_error, status);
return;
}
result->exp = -(result->digits-1);
mpd_maxcontext(&maxcontext);
if (prec < MPD_MINALLOC_MAX*MPD_RDIGITS) {
maxcontext.prec = prec;
_mpd_apply_round_excess(result, rnd, &maxcontext, status);
*status |= (MPD_Inexact|MPD_Rounded);
return;
}
mpd_maxcontext(&varcontext);
varcontext.round = MPD_ROUND_TRUNC;
i = ln_schedule_prec(klist, prec+2, -result->exp);
for (; i >= 0; i--) {
varcontext.prec = 2*klist[i]+3;
result->flags ^= MPD_NEG;
_mpd_qexp(&tmp, result, &varcontext, status);
result->flags ^= MPD_NEG;
mpd_qmul(&tmp, &static10, &tmp, &varcontext, status);
mpd_qsub(&tmp, &tmp, &one, &maxcontext, status);
mpd_qadd(result, result, &tmp, &maxcontext, status);
if (mpd_isspecial(result)) {
break;
}
}
mpd_del(&tmp);
maxcontext.prec = prec;
mpd_qfinalize(result, &maxcontext, status);
}
/*
* Initial approximations for the ln() iteration. The values have the
* following properties (established with both decimal.py and mpfr):
*
* Index 0 - 400, logarithms of x in [1.00, 5.00]:
* abs(lnapprox[i] * 10**-3 - log((i+100)/100)) < 10**-2
* abs(lnapprox[i] * 10**-3 - log((i+1+100)/100)) < 10**-2
*
* Index 401 - 899, logarithms of x in (0.500, 0.999]:
* abs(-lnapprox[i] * 10**-3 - log((i+100)/1000)) < 10**-2
* abs(-lnapprox[i] * 10**-3 - log((i+1+100)/1000)) < 10**-2
*/
static const uint16_t lnapprox[900] = {
/* index 0 - 400: log((i+100)/100) * 1000 */
0, 10, 20, 30, 39, 49, 58, 68, 77, 86, 95, 104, 113, 122, 131, 140, 148, 157,
166, 174, 182, 191, 199, 207, 215, 223, 231, 239, 247, 255, 262, 270, 278,
285, 293, 300, 308, 315, 322, 329, 336, 344, 351, 358, 365, 372, 378, 385,
392, 399, 406, 412, 419, 425, 432, 438, 445, 451, 457, 464, 470, 476, 482,
489, 495, 501, 507, 513, 519, 525, 531, 536, 542, 548, 554, 560, 565, 571,
577, 582, 588, 593, 599, 604, 610, 615, 621, 626, 631, 637, 642, 647, 652,
658, 663, 668, 673, 678, 683, 688, 693, 698, 703, 708, 713, 718, 723, 728,
732, 737, 742, 747, 751, 756, 761, 766, 770, 775, 779, 784, 788, 793, 798,
802, 806, 811, 815, 820, 824, 829, 833, 837, 842, 846, 850, 854, 859, 863,
867, 871, 876, 880, 884, 888, 892, 896, 900, 904, 908, 912, 916, 920, 924,
928, 932, 936, 940, 944, 948, 952, 956, 959, 963, 967, 971, 975, 978, 982,
986, 990, 993, 997, 1001, 1004, 1008, 1012, 1015, 1019, 1022, 1026, 1030,
1033, 1037, 1040, 1044, 1047, 1051, 1054, 1058, 1061, 1065, 1068, 1072, 1075,
1078, 1082, 1085, 1089, 1092, 1095, 1099, 1102, 1105, 1109, 1112, 1115, 1118,
1122, 1125, 1128, 1131, 1135, 1138, 1141, 1144, 1147, 1151, 1154, 1157, 1160,
1163, 1166, 1169, 1172, 1176, 1179, 1182, 1185, 1188, 1191, 1194, 1197, 1200,
1203, 1206, 1209, 1212, 1215, 1218, 1221, 1224, 1227, 1230, 1233, 1235, 1238,
1241, 1244, 1247, 1250, 1253, 1256, 1258, 1261, 1264, 1267, 1270, 1273, 1275,
1278, 1281, 1284, 1286, 1289, 1292, 1295, 1297, 1300, 1303, 1306, 1308, 1311,
1314, 1316, 1319, 1322, 1324, 1327, 1330, 1332, 1335, 1338, 1340, 1343, 1345,
1348, 1351, 1353, 1356, 1358, 1361, 1364, 1366, 1369, 1371, 1374, 1376, 1379,
1381, 1384, 1386, 1389, 1391, 1394, 1396, 1399, 1401, 1404, 1406, 1409, 1411,
1413, 1416, 1418, 1421, 1423, 1426, 1428, 1430, 1433, 1435, 1437, 1440, 1442,
1445, 1447, 1449, 1452, 1454, 1456, 1459, 1461, 1463, 1466, 1468, 1470, 1472,
1475, 1477, 1479, 1482, 1484, 1486, 1488, 1491, 1493, 1495, 1497, 1500, 1502,
1504, 1506, 1509, 1511, 1513, 1515, 1517, 1520, 1522, 1524, 1526, 1528, 1530,
1533, 1535, 1537, 1539, 1541, 1543, 1545, 1548, 1550, 1552, 1554, 1556, 1558,
1560, 1562, 1564, 1567, 1569, 1571, 1573, 1575, 1577, 1579, 1581, 1583, 1585,
1587, 1589, 1591, 1593, 1595, 1597, 1599, 1601, 1603, 1605, 1607, 1609,
/* index 401 - 899: -log((i+100)/1000) * 1000 */
691, 689, 687, 685, 683, 681, 679, 677, 675, 673, 671, 669, 668, 666, 664,
662, 660, 658, 656, 654, 652, 650, 648, 646, 644, 642, 641, 639, 637, 635,
633, 631, 629, 627, 626, 624, 622, 620, 618, 616, 614, 612, 611, 609, 607,
605, 603, 602, 600, 598, 596, 594, 592, 591, 589, 587, 585, 583, 582, 580,
578, 576, 574, 573, 571, 569, 567, 566, 564, 562, 560, 559, 557, 555, 553,
552, 550, 548, 546, 545, 543, 541, 540, 538, 536, 534, 533, 531, 529, 528,
526, 524, 523, 521, 519, 518, 516, 514, 512, 511, 509, 508, 506, 504, 502,
501, 499, 498, 496, 494, 493, 491, 489, 488, 486, 484, 483, 481, 480, 478,
476, 475, 473, 472, 470, 468, 467, 465, 464, 462, 460, 459, 457, 456, 454,
453, 451, 449, 448, 446, 445, 443, 442, 440, 438, 437, 435, 434, 432, 431,
429, 428, 426, 425, 423, 422, 420, 419, 417, 416, 414, 412, 411, 410, 408,
406, 405, 404, 402, 400, 399, 398, 396, 394, 393, 392, 390, 389, 387, 386,
384, 383, 381, 380, 378, 377, 375, 374, 372, 371, 370, 368, 367, 365, 364,
362, 361, 360, 358, 357, 355, 354, 352, 351, 350, 348, 347, 345, 344, 342,
341, 340, 338, 337, 336, 334, 333, 331, 330, 328, 327, 326, 324, 323, 322,
320, 319, 318, 316, 315, 313, 312, 311, 309, 308, 306, 305, 304, 302, 301,
300, 298, 297, 296, 294, 293, 292, 290, 289, 288, 286, 285, 284, 282, 281,
280, 278, 277, 276, 274, 273, 272, 270, 269, 268, 267, 265, 264, 263, 261,
260, 259, 258, 256, 255, 254, 252, 251, 250, 248, 247, 246, 245, 243, 242,
241, 240, 238, 237, 236, 234, 233, 232, 231, 229, 228, 227, 226, 224, 223,
222, 221, 219, 218, 217, 216, 214, 213, 212, 211, 210, 208, 207, 206, 205,
203, 202, 201, 200, 198, 197, 196, 195, 194, 192, 191, 190, 189, 188, 186,
185, 184, 183, 182, 180, 179, 178, 177, 176, 174, 173, 172, 171, 170, 168,
167, 166, 165, 164, 162, 161, 160, 159, 158, 157, 156, 154, 153, 152, 151,
150, 148, 147, 146, 145, 144, 143, 142, 140, 139, 138, 137, 136, 135, 134,
132, 131, 130, 129, 128, 127, 126, 124, 123, 122, 121, 120, 119, 118, 116,
115, 114, 113, 112, 111, 110, 109, 108, 106, 105, 104, 103, 102, 101, 100,
99, 98, 97, 95, 94, 93, 92, 91, 90, 89, 88, 87, 86, 84, 83, 82, 81, 80, 79,
78, 77, 76, 75, 74, 73, 72, 70, 69, 68, 67, 66, 65, 64, 63, 62, 61, 60, 59,
58, 57, 56, 54, 53, 52, 51, 50, 49, 48, 47, 46, 45, 44, 43, 42, 41, 40, 39,
38, 37, 36, 35, 34, 33, 31, 30, 29, 28, 27, 26, 25, 24, 23, 22, 21, 20, 19,
18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1
};
/*
* Internal ln() function that does not check for specials, zero or one.
* Relative error: abs(result - log(a)) < 0.1 * 10**-prec * abs(log(a))
*/
static void
_mpd_qln(mpd_t *result, const mpd_t *a, const mpd_context_t *ctx,
uint32_t *status)
{
mpd_context_t varcontext, maxcontext;
mpd_t *z = (mpd_t *) result;
MPD_NEW_STATIC(v,0,0,0,0);
MPD_NEW_STATIC(vtmp,0,0,0,0);
MPD_NEW_STATIC(tmp,0,0,0,0);
mpd_ssize_t klist[MPD_MAX_PREC_LOG2];
mpd_ssize_t maxprec, shift, t;
mpd_ssize_t a_digits, a_exp;
mpd_uint_t dummy, x;
int i;
assert(!mpd_isspecial(a) && !mpd_iszerocoeff(a));
/*
* We are calculating ln(a) = ln(v * 10^t) = ln(v) + t*ln(10),
* where 0.5 < v <= 5.
*/
if (!mpd_qcopy(&v, a, status)) {
mpd_seterror(result, MPD_Malloc_error, status);
goto finish;
}
/* Initial approximation: we have at least one non-zero digit */
_mpd_get_msdigits(&dummy, &x, &v, 3);
if (x < 10) x *= 10;
if (x < 100) x *= 10;
x -= 100;
/* a may equal z */
a_digits = a->digits;
a_exp = a->exp;
mpd_minalloc(z);
mpd_clear_flags(z);
z->data[0] = lnapprox[x];
z->len = 1;
z->exp = -3;
mpd_setdigits(z);
if (x <= 400) {
/* Reduce the input operand to 1.00 <= v <= 5.00. Let y = x + 100,
* so 100 <= y <= 500. Since y contains the most significant digits
* of v, y/100 <= v < (y+1)/100 and abs(z - log(v)) < 10**-2. */
v.exp = -(a_digits - 1);
t = a_exp + a_digits - 1;
}
else {
/* Reduce the input operand to 0.500 < v <= 0.999. Let y = x + 100,
* so 500 < y <= 999. Since y contains the most significant digits
* of v, y/1000 <= v < (y+1)/1000 and abs(z - log(v)) < 10**-2. */
v.exp = -a_digits;
t = a_exp + a_digits;
mpd_set_negative(z);
}
mpd_maxcontext(&maxcontext);
mpd_maxcontext(&varcontext);
varcontext.round = MPD_ROUND_TRUNC;
maxprec = ctx->prec + 2;
if (t == 0 && (x <= 15 || x >= 800)) {
/* 0.900 <= v <= 1.15: Estimate the magnitude of the logarithm.
* If ln(v) will underflow, skip the loop. Otherwise, adjust the
* precision upwards in order to obtain a sufficient number of
* significant digits.
*
* Case v > 1:
* abs((v-1)/10) < abs((v-1)/v) < abs(ln(v)) < abs(v-1)
* Case v < 1:
* abs(v-1) < abs(ln(v)) < abs((v-1)/v) < abs((v-1)*10)
*/
int cmp = _mpd_cmp(&v, &one);
/* Upper bound (assume v > 1): abs(v-1), unrounded */
_mpd_qsub(&tmp, &v, &one, &maxcontext, &maxcontext.status);
if (maxcontext.status & MPD_Errors) {
mpd_seterror(result, MPD_Malloc_error, status);
goto finish;
}
if (cmp < 0) {
/* v < 1: abs((v-1)*10) */
tmp.exp += 1;
}
if (mpd_adjexp(&tmp) < mpd_etiny(ctx)) {
/* The upper bound is less than etiny: Underflow to zero */
_settriple(result, (cmp<0), 1, mpd_etiny(ctx)-1);
goto finish;
}
/* Lower bound: abs((v-1)/10) or abs(v-1) */
tmp.exp -= 1;
if (mpd_adjexp(&tmp) < 0) {
/* Absolute error of the loop: abs(z - log(v)) < 10**-p. If
* p = ctx->prec+2-adjexp(lower), then the relative error of
* the result is (using 10**adjexp(x) <= abs(x)):
*
* abs(z - log(v)) / abs(log(v)) < 10**-p / abs(log(v))
* <= 10**(-ctx->prec-2)
*/
maxprec = maxprec - mpd_adjexp(&tmp);
}
}
i = ln_schedule_prec(klist, maxprec, 2);
for (; i >= 0; i--) {
varcontext.prec = 2*klist[i]+3;
z->flags ^= MPD_NEG;
_mpd_qexp(&tmp, z, &varcontext, status);
z->flags ^= MPD_NEG;
if (v.digits > varcontext.prec) {
shift = v.digits - varcontext.prec;
mpd_qshiftr(&vtmp, &v, shift, status);
vtmp.exp += shift;
mpd_qmul(&tmp, &vtmp, &tmp, &varcontext, status);
}
else {
mpd_qmul(&tmp, &v, &tmp, &varcontext, status);
}
mpd_qsub(&tmp, &tmp, &one, &maxcontext, status);
mpd_qadd(z, z, &tmp, &maxcontext, status);
if (mpd_isspecial(z)) {
break;
}
}
/*
* Case t == 0:
* t * log(10) == 0, the result does not change and the analysis
* above applies. If v < 0.900 or v > 1.15, the relative error is
* less than 10**(-ctx.prec-1).
* Case t != 0:
* z := approx(log(v))
* y := approx(log(10))
* p := maxprec = ctx->prec + 2
* Absolute errors:
* 1) abs(z - log(v)) < 10**-p
* 2) abs(y - log(10)) < 10**-p
* The multiplication is exact, so:
* 3) abs(t*y - t*log(10)) < t*10**-p
* The sum is exact, so:
* 4) abs((z + t*y) - (log(v) + t*log(10))) < (abs(t) + 1) * 10**-p
* Bounds for log(v) and log(10):
* 5) -7/10 < log(v) < 17/10
* 6) 23/10 < log(10) < 24/10
* Using 4), 5), 6) and t != 0, the relative error is:
*
* 7) relerr < ((abs(t) + 1)*10**-p) / abs(log(v) + t*log(10))
* < 0.5 * 10**(-p + 1) = 0.5 * 10**(-ctx->prec-1)
*/
mpd_qln10(&v, maxprec+1, status);
mpd_qmul_ssize(&tmp, &v, t, &maxcontext, status);
mpd_qadd(result, &tmp, z, &maxcontext, status);
finish:
*status |= (MPD_Inexact|MPD_Rounded);
mpd_del(&v);
mpd_del(&vtmp);
mpd_del(&tmp);
}
/* ln(a) */
void
mpd_qln(mpd_t *result, const mpd_t *a, const mpd_context_t *ctx,
uint32_t *status)
{
mpd_context_t workctx;
mpd_ssize_t adjexp, t;
if (mpd_isspecial(a)) {
if (mpd_qcheck_nan(result, a, ctx, status)) {
return;
}
if (mpd_isnegative(a)) {
mpd_seterror(result, MPD_Invalid_operation, status);
return;
}
mpd_setspecial(result, MPD_POS, MPD_INF);
return;
}
if (mpd_iszerocoeff(a)) {
mpd_setspecial(result, MPD_NEG, MPD_INF);
return;
}
if (mpd_isnegative(a)) {
mpd_seterror(result, MPD_Invalid_operation, status);
return;
}
if (_mpd_cmp(a, &one) == 0) {
_settriple(result, MPD_POS, 0, 0);
return;
}
/*
* Check if the result will overflow (0 < x, x != 1):
* 1) log10(x) < 0 iff adjexp(x) < 0
* 2) 0 < x /\ x <= y ==> adjexp(x) <= adjexp(y)
* 3) 0 < x /\ x != 1 ==> 2 * abs(log10(x)) < abs(log(x))
* 4) adjexp(x) <= log10(x) < adjexp(x) + 1
*
* Case adjexp(x) >= 0:
* 5) 2 * adjexp(x) < abs(log(x))
* Case adjexp(x) > 0:
* 6) adjexp(2 * adjexp(x)) <= adjexp(abs(log(x)))
* Case adjexp(x) == 0:
* mpd_exp_digits(t)-1 == 0 <= emax (the shortcut is not triggered)
*
* Case adjexp(x) < 0:
* 7) 2 * (-adjexp(x) - 1) < abs(log(x))
* Case adjexp(x) < -1:
* 8) adjexp(2 * (-adjexp(x) - 1)) <= adjexp(abs(log(x)))
* Case adjexp(x) == -1:
* mpd_exp_digits(t)-1 == 0 <= emax (the shortcut is not triggered)
*/
adjexp = mpd_adjexp(a);
t = (adjexp < 0) ? -adjexp-1 : adjexp;
t *= 2;
if (mpd_exp_digits(t)-1 > ctx->emax) {
*status |= MPD_Overflow|MPD_Inexact|MPD_Rounded;
mpd_setspecial(result, (adjexp<0), MPD_INF);
return;
}
workctx = *ctx;
workctx.round = MPD_ROUND_HALF_EVEN;
if (ctx->allcr) {
MPD_NEW_STATIC(t1, 0,0,0,0);
MPD_NEW_STATIC(t2, 0,0,0,0);
MPD_NEW_STATIC(ulp, 0,0,0,0);
MPD_NEW_STATIC(aa, 0,0,0,0);
mpd_ssize_t prec;
if (result == a) {
if (!mpd_qcopy(&aa, a, status)) {
mpd_seterror(result, MPD_Malloc_error, status);
return;
}
a = &aa;
}
workctx.clamp = 0;
prec = ctx->prec + 3;
while (1) {
workctx.prec = prec;
_mpd_qln(result, a, &workctx, status);
_ssettriple(&ulp, MPD_POS, 1,
result->exp + result->digits-workctx.prec);
workctx.prec = ctx->prec;
mpd_qadd(&t1, result, &ulp, &workctx, &workctx.status);
mpd_qsub(&t2, result, &ulp, &workctx, &workctx.status);
if (mpd_isspecial(result) || mpd_iszerocoeff(result) ||
mpd_qcmp(&t1, &t2, status) == 0) {
workctx.clamp = ctx->clamp;
mpd_check_underflow(result, &workctx, status);
mpd_qfinalize(result, &workctx, status);
break;
}
prec += MPD_RDIGITS;
}
mpd_del(&t1);
mpd_del(&t2);
mpd_del(&ulp);
mpd_del(&aa);
}
else {
_mpd_qln(result, a, &workctx, status);
mpd_check_underflow(result, &workctx, status);
mpd_qfinalize(result, &workctx, status);
}
}
/*
* Internal log10() function that does not check for specials, zero or one.
* Case SKIP_FINALIZE:
* Relative error: abs(result - log10(a)) < 0.1 * 10**-prec * abs(log10(a))
* Case DO_FINALIZE:
* Ulp error: abs(result - log10(a)) < ulp(log10(a))
*/
enum {SKIP_FINALIZE, DO_FINALIZE};
static void
_mpd_qlog10(int action, mpd_t *result, const mpd_t *a,
const mpd_context_t *ctx, uint32_t *status)
{
mpd_context_t workctx;
MPD_NEW_STATIC(ln10,0,0,0,0);
mpd_maxcontext(&workctx);
workctx.prec = ctx->prec + 3;
/* relative error: 0.1 * 10**(-p-3). The specific underflow shortcut
* in _mpd_qln() does not change the final result. */
_mpd_qln(result, a, &workctx, status);
/* relative error: 5 * 10**(-p-3) */
mpd_qln10(&ln10, workctx.prec, status);
if (action == DO_FINALIZE) {
workctx = *ctx;
workctx.round = MPD_ROUND_HALF_EVEN;
}
/* SKIP_FINALIZE: relative error: 5 * 10**(-p-3) */
_mpd_qdiv(NO_IDEAL_EXP, result, result, &ln10, &workctx, status);
mpd_del(&ln10);
}
/* log10(a) */
void
mpd_qlog10(mpd_t *result, const mpd_t *a, const mpd_context_t *ctx,
uint32_t *status)
{
mpd_context_t workctx;
mpd_ssize_t adjexp, t;
workctx = *ctx;
workctx.round = MPD_ROUND_HALF_EVEN;
if (mpd_isspecial(a)) {
if (mpd_qcheck_nan(result, a, ctx, status)) {
return;
}
if (mpd_isnegative(a)) {
mpd_seterror(result, MPD_Invalid_operation, status);
return;
}
mpd_setspecial(result, MPD_POS, MPD_INF);
return;
}
if (mpd_iszerocoeff(a)) {
mpd_setspecial(result, MPD_NEG, MPD_INF);
return;
}
if (mpd_isnegative(a)) {
mpd_seterror(result, MPD_Invalid_operation, status);
return;
}
if (mpd_coeff_ispow10(a)) {
uint8_t sign = 0;
adjexp = mpd_adjexp(a);
if (adjexp < 0) {
sign = 1;
adjexp = -adjexp;
}
_settriple(result, sign, adjexp, 0);
mpd_qfinalize(result, &workctx, status);
return;
}
/*
* Check if the result will overflow (0 < x, x != 1):
* 1) log10(x) < 0 iff adjexp(x) < 0
* 2) 0 < x /\ x <= y ==> adjexp(x) <= adjexp(y)
* 3) adjexp(x) <= log10(x) < adjexp(x) + 1
*
* Case adjexp(x) >= 0:
* 4) adjexp(x) <= abs(log10(x))
* Case adjexp(x) > 0:
* 5) adjexp(adjexp(x)) <= adjexp(abs(log10(x)))
* Case adjexp(x) == 0:
* mpd_exp_digits(t)-1 == 0 <= emax (the shortcut is not triggered)
*
* Case adjexp(x) < 0:
* 6) -adjexp(x) - 1 < abs(log10(x))
* Case adjexp(x) < -1:
* 7) adjexp(-adjexp(x) - 1) <= adjexp(abs(log(x)))
* Case adjexp(x) == -1:
* mpd_exp_digits(t)-1 == 0 <= emax (the shortcut is not triggered)
*/
adjexp = mpd_adjexp(a);
t = (adjexp < 0) ? -adjexp-1 : adjexp;
if (mpd_exp_digits(t)-1 > ctx->emax) {
*status |= MPD_Overflow|MPD_Inexact|MPD_Rounded;
mpd_setspecial(result, (adjexp<0), MPD_INF);
return;
}
if (ctx->allcr) {
MPD_NEW_STATIC(t1, 0,0,0,0);
MPD_NEW_STATIC(t2, 0,0,0,0);
MPD_NEW_STATIC(ulp, 0,0,0,0);
MPD_NEW_STATIC(aa, 0,0,0,0);
mpd_ssize_t prec;
if (result == a) {
if (!mpd_qcopy(&aa, a, status)) {
mpd_seterror(result, MPD_Malloc_error, status);
return;
}
a = &aa;
}
workctx.clamp = 0;
prec = ctx->prec + 3;
while (1) {
workctx.prec = prec;
_mpd_qlog10(SKIP_FINALIZE, result, a, &workctx, status);
_ssettriple(&ulp, MPD_POS, 1,
result->exp + result->digits-workctx.prec);
workctx.prec = ctx->prec;
mpd_qadd(&t1, result, &ulp, &workctx, &workctx.status);
mpd_qsub(&t2, result, &ulp, &workctx, &workctx.status);
if (mpd_isspecial(result) || mpd_iszerocoeff(result) ||
mpd_qcmp(&t1, &t2, status) == 0) {
workctx.clamp = ctx->clamp;
mpd_check_underflow(result, &workctx, status);
mpd_qfinalize(result, &workctx, status);
break;
}
prec += MPD_RDIGITS;
}
mpd_del(&t1);
mpd_del(&t2);
mpd_del(&ulp);
mpd_del(&aa);
}
else {
_mpd_qlog10(DO_FINALIZE, result, a, &workctx, status);
mpd_check_underflow(result, &workctx, status);
}
}
/*
* Maximum of the two operands. Attention: If one operand is a quiet NaN and the
* other is numeric, the numeric operand is returned. This may not be what one
* expects.
*/
void
mpd_qmax(mpd_t *result, const mpd_t *a, const mpd_t *b,
const mpd_context_t *ctx, uint32_t *status)
{
int c;
if (mpd_isqnan(a) && !mpd_isnan(b)) {
mpd_qcopy(result, b, status);
}
else if (mpd_isqnan(b) && !mpd_isnan(a)) {
mpd_qcopy(result, a, status);
}
else if (mpd_qcheck_nans(result, a, b, ctx, status)) {
return;
}
else {
c = _mpd_cmp(a, b);
if (c == 0) {
c = _mpd_cmp_numequal(a, b);
}
if (c < 0) {
mpd_qcopy(result, b, status);
}
else {
mpd_qcopy(result, a, status);
}
}
mpd_qfinalize(result, ctx, status);
}
/*
* Maximum magnitude: Same as mpd_max(), but compares the operands with their
* sign ignored.
*/
void
mpd_qmax_mag(mpd_t *result, const mpd_t *a, const mpd_t *b,
const mpd_context_t *ctx, uint32_t *status)
{
int c;
if (mpd_isqnan(a) && !mpd_isnan(b)) {
mpd_qcopy(result, b, status);
}
else if (mpd_isqnan(b) && !mpd_isnan(a)) {
mpd_qcopy(result, a, status);
}
else if (mpd_qcheck_nans(result, a, b, ctx, status)) {
return;
}
else {
c = _mpd_cmp_abs(a, b);
if (c == 0) {
c = _mpd_cmp_numequal(a, b);
}
if (c < 0) {
mpd_qcopy(result, b, status);
}
else {
mpd_qcopy(result, a, status);
}
}
mpd_qfinalize(result, ctx, status);
}
/*
* Minimum of the two operands. Attention: If one operand is a quiet NaN and the
* other is numeric, the numeric operand is returned. This may not be what one
* expects.
*/
void
mpd_qmin(mpd_t *result, const mpd_t *a, const mpd_t *b,
const mpd_context_t *ctx, uint32_t *status)
{
int c;
if (mpd_isqnan(a) && !mpd_isnan(b)) {
mpd_qcopy(result, b, status);
}
else if (mpd_isqnan(b) && !mpd_isnan(a)) {
mpd_qcopy(result, a, status);
}
else if (mpd_qcheck_nans(result, a, b, ctx, status)) {
return;
}
else {
c = _mpd_cmp(a, b);
if (c == 0) {
c = _mpd_cmp_numequal(a, b);
}
if (c < 0) {
mpd_qcopy(result, a, status);
}
else {
mpd_qcopy(result, b, status);
}
}
mpd_qfinalize(result, ctx, status);
}
/*
* Minimum magnitude: Same as mpd_min(), but compares the operands with
* their sign ignored.
*/
void
mpd_qmin_mag(mpd_t *result, const mpd_t *a, const mpd_t *b,
const mpd_context_t *ctx, uint32_t *status)
{
int c;
if (mpd_isqnan(a) && !mpd_isnan(b)) {
mpd_qcopy(result, b, status);
}
else if (mpd_isqnan(b) && !mpd_isnan(a)) {
mpd_qcopy(result, a, status);
}
else if (mpd_qcheck_nans(result, a, b, ctx, status)) {
return;
}
else {
c = _mpd_cmp_abs(a, b);
if (c == 0) {
c = _mpd_cmp_numequal(a, b);
}
if (c < 0) {
mpd_qcopy(result, a, status);
}
else {
mpd_qcopy(result, b, status);
}
}
mpd_qfinalize(result, ctx, status);
}
/* Minimum space needed for the result array in _karatsuba_rec(). */
static inline mpd_size_t
_kmul_resultsize(mpd_size_t la, mpd_size_t lb)
{
mpd_size_t n, m;
n = add_size_t(la, lb);
n = add_size_t(n, 1);
m = (la+1)/2 + 1;
m = mul_size_t(m, 3);
return (m > n) ? m : n;
}
/* Work space needed in _karatsuba_rec(). lim >= 4 */
static inline mpd_size_t
_kmul_worksize(mpd_size_t n, mpd_size_t lim)
{
mpd_size_t m;
if (n <= lim) {
return 0;
}
m = (n+1)/2 + 1;
return add_size_t(mul_size_t(m, 2), _kmul_worksize(m, lim));
}
#define MPD_KARATSUBA_BASECASE 16 /* must be >= 4 */
/*
* Add the product of a and b to c.
* c must be _kmul_resultsize(la, lb) in size.
* w is used as a work array and must be _kmul_worksize(a, lim) in size.
* Roman E. Maeder, Storage Allocation for the Karatsuba Integer Multiplication
* Algorithm. In "Design and implementation of symbolic computation systems",
* Springer, 1993, ISBN 354057235X, 9783540572350.
*/
static void
_karatsuba_rec(mpd_uint_t *c, const mpd_uint_t *a, const mpd_uint_t *b,
mpd_uint_t *w, mpd_size_t la, mpd_size_t lb)
{
mpd_size_t m, lt;
assert(la >= lb && lb > 0);
assert(la <= MPD_KARATSUBA_BASECASE || w != NULL);
if (la <= MPD_KARATSUBA_BASECASE) {
_mpd_basemul(c, a, b, la, lb);
return;
}
m = (la+1)/2; /* ceil(la/2) */
/* lb <= m < la */
if (lb <= m) {
/* lb can now be larger than la-m */
if (lb > la-m) {
lt = lb + lb + 1; /* space needed for result array */
mpd_uint_zero(w, lt); /* clear result array */
_karatsuba_rec(w, b, a+m, w+lt, lb, la-m); /* b*ah */
}
else {
lt = (la-m) + (la-m) + 1; /* space needed for result array */
mpd_uint_zero(w, lt); /* clear result array */
_karatsuba_rec(w, a+m, b, w+lt, la-m, lb); /* ah*b */
}
_mpd_baseaddto(c+m, w, (la-m)+lb); /* add ah*b*B**m */
lt = m + m + 1; /* space needed for the result array */
mpd_uint_zero(w, lt); /* clear result array */
_karatsuba_rec(w, a, b, w+lt, m, lb); /* al*b */
_mpd_baseaddto(c, w, m+lb); /* add al*b */
return;
}
/* la >= lb > m */
memcpy(w, a, m * sizeof *w);
w[m] = 0;
_mpd_baseaddto(w, a+m, la-m);
memcpy(w+(m+1), b, m * sizeof *w);
w[m+1+m] = 0;
_mpd_baseaddto(w+(m+1), b+m, lb-m);
_karatsuba_rec(c+m, w, w+(m+1), w+2*(m+1), m+1, m+1);
lt = (la-m) + (la-m) + 1;
mpd_uint_zero(w, lt);
_karatsuba_rec(w, a+m, b+m, w+lt, la-m, lb-m);
_mpd_baseaddto(c+2*m, w, (la-m) + (lb-m));
_mpd_basesubfrom(c+m, w, (la-m) + (lb-m));
lt = m + m + 1;
mpd_uint_zero(w, lt);
_karatsuba_rec(w, a, b, w+lt, m, m);
_mpd_baseaddto(c, w, m+m);
_mpd_basesubfrom(c+m, w, m+m);
return;
}
/*
* Multiply u and v, using Karatsuba multiplication. Returns a pointer
* to the result or NULL in case of failure (malloc error).
* Conditions: ulen >= vlen, ulen >= 4
*/
static mpd_uint_t *
_mpd_kmul(const mpd_uint_t *u, const mpd_uint_t *v,
mpd_size_t ulen, mpd_size_t vlen,
mpd_size_t *rsize)
{
mpd_uint_t *result = NULL, *w = NULL;
mpd_size_t m;
assert(ulen >= 4);
assert(ulen >= vlen);
*rsize = _kmul_resultsize(ulen, vlen);
if ((result = mpd_calloc(*rsize, sizeof *result)) == NULL) {
return NULL;
}
m = _kmul_worksize(ulen, MPD_KARATSUBA_BASECASE);
if (m && ((w = mpd_calloc(m, sizeof *w)) == NULL)) {
mpd_free(result);
return NULL;
}
_karatsuba_rec(result, u, v, w, ulen, vlen);
if (w) mpd_free(w);
return result;
}
/*
* Determine the minimum length for the number theoretic transform. Valid
* transform lengths are 2**n or 3*2**n, where 2**n <= MPD_MAXTRANSFORM_2N.
* The function finds the shortest length m such that rsize <= m.
*/
static inline mpd_size_t
_mpd_get_transform_len(mpd_size_t rsize)
{
mpd_size_t log2rsize;
mpd_size_t x, step;
assert(rsize >= 4);
log2rsize = mpd_bsr(rsize);
if (rsize <= 1024) {
/* 2**n is faster in this range. */
x = ((mpd_size_t)1)<<log2rsize;
return (rsize == x) ? x : x<<1;
}
else if (rsize <= MPD_MAXTRANSFORM_2N) {
x = ((mpd_size_t)1)<<log2rsize;
if (rsize == x) return x;
step = x>>1;
x += step;
return (rsize <= x) ? x : x + step;
}
else if (rsize <= MPD_MAXTRANSFORM_2N+MPD_MAXTRANSFORM_2N/2) {
return MPD_MAXTRANSFORM_2N+MPD_MAXTRANSFORM_2N/2;
}
else if (rsize <= 3*MPD_MAXTRANSFORM_2N) {
return 3*MPD_MAXTRANSFORM_2N;
}
else {
return MPD_SIZE_MAX;
}
}
/*
* Multiply u and v, using the fast number theoretic transform. Returns
* a pointer to the result or NULL in case of failure (malloc error).
*/
static mpd_uint_t *
_mpd_fntmul(const mpd_uint_t *u, const mpd_uint_t *v,
mpd_size_t ulen, mpd_size_t vlen,
mpd_size_t *rsize)
{
mpd_uint_t *c1 = NULL, *c2 = NULL, *c3 = NULL, *vtmp = NULL;
mpd_size_t n;
*rsize = add_size_t(ulen, vlen);
if ((n = _mpd_get_transform_len(*rsize)) == MPD_SIZE_MAX) {
goto malloc_error;
}
if ((c1 = mpd_calloc(n, sizeof *c1)) == NULL) {
goto malloc_error;
}
if ((c2 = mpd_calloc(n, sizeof *c2)) == NULL) {
goto malloc_error;
}
if ((c3 = mpd_calloc(n, sizeof *c3)) == NULL) {
goto malloc_error;
}
memcpy(c1, u, ulen * (sizeof *c1));
memcpy(c2, u, ulen * (sizeof *c2));
memcpy(c3, u, ulen * (sizeof *c3));
if (u == v) {
if (!fnt_autoconvolute(c1, n, P1) ||
!fnt_autoconvolute(c2, n, P2) ||
!fnt_autoconvolute(c3, n, P3)) {
goto malloc_error;
}
}
else {
if ((vtmp = mpd_calloc(n, sizeof *vtmp)) == NULL) {
goto malloc_error;
}
memcpy(vtmp, v, vlen * (sizeof *vtmp));
if (!fnt_convolute(c1, vtmp, n, P1)) {
mpd_free(vtmp);
goto malloc_error;
}
memcpy(vtmp, v, vlen * (sizeof *vtmp));
mpd_uint_zero(vtmp+vlen, n-vlen);
if (!fnt_convolute(c2, vtmp, n, P2)) {
mpd_free(vtmp);
goto malloc_error;
}
memcpy(vtmp, v, vlen * (sizeof *vtmp));
mpd_uint_zero(vtmp+vlen, n-vlen);
if (!fnt_convolute(c3, vtmp, n, P3)) {
mpd_free(vtmp);
goto malloc_error;
}
mpd_free(vtmp);
}
crt3(c1, c2, c3, *rsize);
out:
if (c2) mpd_free(c2);
if (c3) mpd_free(c3);
return c1;
malloc_error:
if (c1) mpd_free(c1);
c1 = NULL;
goto out;
}
/*
* Karatsuba multiplication with FNT/basemul as the base case.
*/
static int
_karatsuba_rec_fnt(mpd_uint_t *c, const mpd_uint_t *a, const mpd_uint_t *b,
mpd_uint_t *w, mpd_size_t la, mpd_size_t lb)
{
mpd_size_t m, lt;
assert(la >= lb && lb > 0);
assert(la <= 3*(MPD_MAXTRANSFORM_2N/2) || w != NULL);
if (la <= 3*(MPD_MAXTRANSFORM_2N/2)) {
if (lb <= 192) {
_mpd_basemul(c, b, a, lb, la);
}
else {
mpd_uint_t *result;
mpd_size_t dummy;
if ((result = _mpd_fntmul(a, b, la, lb, &dummy)) == NULL) {
return 0;
}
memcpy(c, result, (la+lb) * (sizeof *result));
mpd_free(result);
}
return 1;
}
m = (la+1)/2; /* ceil(la/2) */
/* lb <= m < la */
if (lb <= m) {
/* lb can now be larger than la-m */
if (lb > la-m) {
lt = lb + lb + 1; /* space needed for result array */
mpd_uint_zero(w, lt); /* clear result array */
if (!_karatsuba_rec_fnt(w, b, a+m, w+lt, lb, la-m)) { /* b*ah */
return 0; /* GCOV_UNLIKELY */
}
}
else {
lt = (la-m) + (la-m) + 1; /* space needed for result array */
mpd_uint_zero(w, lt); /* clear result array */
if (!_karatsuba_rec_fnt(w, a+m, b, w+lt, la-m, lb)) { /* ah*b */
return 0; /* GCOV_UNLIKELY */
}
}
_mpd_baseaddto(c+m, w, (la-m)+lb); /* add ah*b*B**m */
lt = m + m + 1; /* space needed for the result array */
mpd_uint_zero(w, lt); /* clear result array */
if (!_karatsuba_rec_fnt(w, a, b, w+lt, m, lb)) { /* al*b */
return 0; /* GCOV_UNLIKELY */
}
_mpd_baseaddto(c, w, m+lb); /* add al*b */
return 1;
}
/* la >= lb > m */
memcpy(w, a, m * sizeof *w);
w[m] = 0;
_mpd_baseaddto(w, a+m, la-m);
memcpy(w+(m+1), b, m * sizeof *w);
w[m+1+m] = 0;
_mpd_baseaddto(w+(m+1), b+m, lb-m);
if (!_karatsuba_rec_fnt(c+m, w, w+(m+1), w+2*(m+1), m+1, m+1)) {
return 0; /* GCOV_UNLIKELY */
}
lt = (la-m) + (la-m) + 1;
mpd_uint_zero(w, lt);
if (!_karatsuba_rec_fnt(w, a+m, b+m, w+lt, la-m, lb-m)) {
return 0; /* GCOV_UNLIKELY */
}
_mpd_baseaddto(c+2*m, w, (la-m) + (lb-m));
_mpd_basesubfrom(c+m, w, (la-m) + (lb-m));
lt = m + m + 1;
mpd_uint_zero(w, lt);
if (!_karatsuba_rec_fnt(w, a, b, w+lt, m, m)) {
return 0; /* GCOV_UNLIKELY */
}
_mpd_baseaddto(c, w, m+m);
_mpd_basesubfrom(c+m, w, m+m);
return 1;
}
/*
* Multiply u and v, using Karatsuba multiplication with the FNT as the
* base case. Returns a pointer to the result or NULL in case of failure
* (malloc error). Conditions: ulen >= vlen, ulen >= 4.
*/
static mpd_uint_t *
_mpd_kmul_fnt(const mpd_uint_t *u, const mpd_uint_t *v,
mpd_size_t ulen, mpd_size_t vlen,
mpd_size_t *rsize)
{
mpd_uint_t *result = NULL, *w = NULL;
mpd_size_t m;
assert(ulen >= 4);
assert(ulen >= vlen);
*rsize = _kmul_resultsize(ulen, vlen);
if ((result = mpd_calloc(*rsize, sizeof *result)) == NULL) {
return NULL;
}
m = _kmul_worksize(ulen, 3*(MPD_MAXTRANSFORM_2N/2));
if (m && ((w = mpd_calloc(m, sizeof *w)) == NULL)) {
mpd_free(result); /* GCOV_UNLIKELY */
return NULL; /* GCOV_UNLIKELY */
}
if (!_karatsuba_rec_fnt(result, u, v, w, ulen, vlen)) {
mpd_free(result);
result = NULL;
}
if (w) mpd_free(w);
return result;
}
/* Deal with the special cases of multiplying infinities. */
static void
_mpd_qmul_inf(mpd_t *result, const mpd_t *a, const mpd_t *b, uint32_t *status)
{
if (mpd_isinfinite(a)) {
if (mpd_iszero(b)) {
mpd_seterror(result, MPD_Invalid_operation, status);
}
else {
mpd_setspecial(result, mpd_sign(a)^mpd_sign(b), MPD_INF);
}
return;
}
assert(mpd_isinfinite(b));
if (mpd_iszero(a)) {
mpd_seterror(result, MPD_Invalid_operation, status);
}
else {
mpd_setspecial(result, mpd_sign(a)^mpd_sign(b), MPD_INF);
}
}
/*
* Internal function: Multiply a and b. _mpd_qmul deals with specials but
* does NOT finalize the result. This is for use in mpd_fma().
*/
static inline void
_mpd_qmul(mpd_t *result, const mpd_t *a, const mpd_t *b,
const mpd_context_t *ctx, uint32_t *status)
{
const mpd_t *big = a, *small = b;
mpd_uint_t *rdata = NULL;
mpd_uint_t rbuf[MPD_MINALLOC_MAX];
mpd_size_t rsize, i;
if (mpd_isspecial(a) || mpd_isspecial(b)) {
if (mpd_qcheck_nans(result, a, b, ctx, status)) {
return;
}
_mpd_qmul_inf(result, a, b, status);
return;
}
if (small->len > big->len) {
_mpd_ptrswap(&big, &small);
}
rsize = big->len + small->len;
if (big->len == 1) {
_mpd_singlemul(result->data, big->data[0], small->data[0]);
goto finish;
}
if (rsize <= (mpd_size_t)MPD_MINALLOC_MAX) {
if (big->len == 2) {
_mpd_mul_2_le2(rbuf, big->data, small->data, small->len);
}
else {
mpd_uint_zero(rbuf, rsize);
if (small->len == 1) {
_mpd_shortmul(rbuf, big->data, big->len, small->data[0]);
}
else {
_mpd_basemul(rbuf, small->data, big->data, small->len, big->len);
}
}
if (!mpd_qresize(result, rsize, status)) {
return;
}
for(i = 0; i < rsize; i++) {
result->data[i] = rbuf[i];
}
goto finish;
}
if (small->len <= 256) {
rdata = mpd_calloc(rsize, sizeof *rdata);
if (rdata != NULL) {
if (small->len == 1) {
_mpd_shortmul(rdata, big->data, big->len, small->data[0]);
}
else {
_mpd_basemul(rdata, small->data, big->data, small->len, big->len);
}
}
}
else if (rsize <= 1024) {
rdata = _mpd_kmul(big->data, small->data, big->len, small->len, &rsize);
}
else if (rsize <= 3*MPD_MAXTRANSFORM_2N) {
rdata = _mpd_fntmul(big->data, small->data, big->len, small->len, &rsize);
}
else {
rdata = _mpd_kmul_fnt(big->data, small->data, big->len, small->len, &rsize);
}
if (rdata == NULL) {
mpd_seterror(result, MPD_Malloc_error, status);
return;
}
if (mpd_isdynamic_data(result)) {
mpd_free(result->data);
}
result->data = rdata;
result->alloc = rsize;
mpd_set_dynamic_data(result);
finish:
mpd_set_flags(result, mpd_sign(a)^mpd_sign(b));
result->exp = big->exp + small->exp;
result->len = _mpd_real_size(result->data, rsize);
/* resize to smaller cannot fail */
mpd_qresize(result, result->len, status);
mpd_setdigits(result);
}
/* Multiply a and b. */
void
mpd_qmul(mpd_t *result, const mpd_t *a, const mpd_t *b,
const mpd_context_t *ctx, uint32_t *status)
{
_mpd_qmul(result, a, b, ctx, status);
mpd_qfinalize(result, ctx, status);
}
/* Multiply a and b. Set NaN/Invalid_operation if the result is inexact. */
static void
_mpd_qmul_exact(mpd_t *result, const mpd_t *a, const mpd_t *b,
const mpd_context_t *ctx, uint32_t *status)
{
uint32_t workstatus = 0;
mpd_qmul(result, a, b, ctx, &workstatus);
*status |= workstatus;
if (workstatus & (MPD_Inexact|MPD_Rounded|MPD_Clamped)) {
mpd_seterror(result, MPD_Invalid_operation, status);
}
}
/* Multiply decimal and mpd_ssize_t. */
void
mpd_qmul_ssize(mpd_t *result, const mpd_t *a, mpd_ssize_t b,
const mpd_context_t *ctx, uint32_t *status)
{
mpd_context_t maxcontext;
MPD_NEW_STATIC(bb,0,0,0,0);
mpd_maxcontext(&maxcontext);
mpd_qsset_ssize(&bb, b, &maxcontext, status);
mpd_qmul(result, a, &bb, ctx, status);
mpd_del(&bb);
}
/* Multiply decimal and mpd_uint_t. */
void
mpd_qmul_uint(mpd_t *result, const mpd_t *a, mpd_uint_t b,
const mpd_context_t *ctx, uint32_t *status)
{
mpd_context_t maxcontext;
MPD_NEW_STATIC(bb,0,0,0,0);
mpd_maxcontext(&maxcontext);
mpd_qsset_uint(&bb, b, &maxcontext, status);
mpd_qmul(result, a, &bb, ctx, status);
mpd_del(&bb);
}
void
mpd_qmul_i32(mpd_t *result, const mpd_t *a, int32_t b,
const mpd_context_t *ctx, uint32_t *status)
{
mpd_qmul_ssize(result, a, b, ctx, status);
}
void
mpd_qmul_u32(mpd_t *result, const mpd_t *a, uint32_t b,
const mpd_context_t *ctx, uint32_t *status)
{
mpd_qmul_uint(result, a, b, ctx, status);
}
void
mpd_qmul_i64(mpd_t *result, const mpd_t *a, int64_t b,
const mpd_context_t *ctx, uint32_t *status)
{
mpd_qmul_ssize(result, a, b, ctx, status);
}
void
mpd_qmul_u64(mpd_t *result, const mpd_t *a, uint64_t b,
const mpd_context_t *ctx, uint32_t *status)
{
mpd_qmul_uint(result, a, b, ctx, status);
}
/* Like the minus operator. */
void
mpd_qminus(mpd_t *result, const mpd_t *a, const mpd_context_t *ctx,
uint32_t *status)
{
if (mpd_isspecial(a)) {
if (mpd_qcheck_nan(result, a, ctx, status)) {
return;
}
}
if (mpd_iszero(a) && ctx->round != MPD_ROUND_FLOOR) {
mpd_qcopy_abs(result, a, status);
}
else {
mpd_qcopy_negate(result, a, status);
}
mpd_qfinalize(result, ctx, status);
}
/* Like the plus operator. */
void
mpd_qplus(mpd_t *result, const mpd_t *a, const mpd_context_t *ctx,
uint32_t *status)
{
if (mpd_isspecial(a)) {
if (mpd_qcheck_nan(result, a, ctx, status)) {
return;
}
}
if (mpd_iszero(a) && ctx->round != MPD_ROUND_FLOOR) {
mpd_qcopy_abs(result, a, status);
}
else {
mpd_qcopy(result, a, status);
}
mpd_qfinalize(result, ctx, status);
}
/* The largest representable number that is smaller than the operand. */
void
mpd_qnext_minus(mpd_t *result, const mpd_t *a, const mpd_context_t *ctx,
uint32_t *status)
{
mpd_context_t workctx;
MPD_NEW_CONST(tiny,MPD_POS,mpd_etiny(ctx)-1,1,1,1,1);
if (mpd_isspecial(a)) {
if (mpd_qcheck_nan(result, a, ctx, status)) {
return;
}
assert(mpd_isinfinite(a));
if (mpd_isnegative(a)) {
mpd_qcopy(result, a, status);
return;
}
else {
mpd_clear_flags(result);
mpd_qmaxcoeff(result, ctx, status);
if (mpd_isnan(result)) {
return;
}
result->exp = mpd_etop(ctx);
return;
}
}
mpd_workcontext(&workctx, ctx);
workctx.round = MPD_ROUND_FLOOR;
if (!mpd_qcopy(result, a, status)) {
return;
}
mpd_qfinalize(result, &workctx, &workctx.status);
if (workctx.status&(MPD_Inexact|MPD_Errors)) {
*status |= (workctx.status&MPD_Errors);
return;
}
workctx.status = 0;
mpd_qsub(result, a, &tiny, &workctx, &workctx.status);
*status |= (workctx.status&MPD_Errors);
}
/* The smallest representable number that is larger than the operand. */
void
mpd_qnext_plus(mpd_t *result, const mpd_t *a, const mpd_context_t *ctx,
uint32_t *status)
{
mpd_context_t workctx;
MPD_NEW_CONST(tiny,MPD_POS,mpd_etiny(ctx)-1,1,1,1,1);
if (mpd_isspecial(a)) {
if (mpd_qcheck_nan(result, a, ctx, status)) {
return;
}
assert(mpd_isinfinite(a));
if (mpd_ispositive(a)) {
mpd_qcopy(result, a, status);
}
else {
mpd_clear_flags(result);
mpd_qmaxcoeff(result, ctx, status);
if (mpd_isnan(result)) {
return;
}
mpd_set_flags(result, MPD_NEG);
result->exp = mpd_etop(ctx);
}
return;
}
mpd_workcontext(&workctx, ctx);
workctx.round = MPD_ROUND_CEILING;
if (!mpd_qcopy(result, a, status)) {
return;
}
mpd_qfinalize(result, &workctx, &workctx.status);
if (workctx.status & (MPD_Inexact|MPD_Errors)) {
*status |= (workctx.status&MPD_Errors);
return;
}
workctx.status = 0;
mpd_qadd(result, a, &tiny, &workctx, &workctx.status);
*status |= (workctx.status&MPD_Errors);
}
/*
* The number closest to the first operand that is in the direction towards
* the second operand.
*/
void
mpd_qnext_toward(mpd_t *result, const mpd_t *a, const mpd_t *b,
const mpd_context_t *ctx, uint32_t *status)
{
int c;
if (mpd_qcheck_nans(result, a, b, ctx, status)) {
return;
}
c = _mpd_cmp(a, b);
if (c == 0) {
mpd_qcopy_sign(result, a, b, status);
return;
}
if (c < 0) {
mpd_qnext_plus(result, a, ctx, status);
}
else {
mpd_qnext_minus(result, a, ctx, status);
}
if (mpd_isinfinite(result)) {
*status |= (MPD_Overflow|MPD_Rounded|MPD_Inexact);
}
else if (mpd_adjexp(result) < ctx->emin) {
*status |= (MPD_Underflow|MPD_Subnormal|MPD_Rounded|MPD_Inexact);
if (mpd_iszero(result)) {
*status |= MPD_Clamped;
}
}
}
/*
* Internal function: Integer power with mpd_uint_t exponent. The function
* can fail with MPD_Malloc_error.
*
* The error is equal to the error incurred in k-1 multiplications. Assuming
* the upper bound for the relative error in each operation:
*
* abs(err) = 5 * 10**-prec
* result = x**k * (1 + err)**(k-1)
*/
static inline void
_mpd_qpow_uint(mpd_t *result, const mpd_t *base, mpd_uint_t exp,
uint8_t resultsign, const mpd_context_t *ctx, uint32_t *status)
{
uint32_t workstatus = 0;
mpd_uint_t n;
if (exp == 0) {
_settriple(result, resultsign, 1, 0); /* GCOV_NOT_REACHED */
return; /* GCOV_NOT_REACHED */
}
if (!mpd_qcopy(result, base, status)) {
return;
}
n = mpd_bits[mpd_bsr(exp)];
while (n >>= 1) {
mpd_qmul(result, result, result, ctx, &workstatus);
if (exp & n) {
mpd_qmul(result, result, base, ctx, &workstatus);
}
if (mpd_isspecial(result) ||
(mpd_iszerocoeff(result) && (workstatus & MPD_Clamped))) {
break;
}
}
*status |= workstatus;
mpd_set_sign(result, resultsign);
}
/*
* Internal function: Integer power with mpd_t exponent, tbase and texp
* are modified!! Function can fail with MPD_Malloc_error.
*
* The error is equal to the error incurred in k multiplications. Assuming
* the upper bound for the relative error in each operation:
*
* abs(err) = 5 * 10**-prec
* result = x**k * (1 + err)**k
*/
static inline void
_mpd_qpow_mpd(mpd_t *result, mpd_t *tbase, mpd_t *texp, uint8_t resultsign,
const mpd_context_t *ctx, uint32_t *status)
{
uint32_t workstatus = 0;
mpd_context_t maxctx;
MPD_NEW_CONST(two,0,0,1,1,1,2);
mpd_maxcontext(&maxctx);
/* resize to smaller cannot fail */
mpd_qcopy(result, &one, status);
while (!mpd_iszero(texp)) {
if (mpd_isodd(texp)) {
mpd_qmul(result, result, tbase, ctx, &workstatus);
*status |= workstatus;
if (mpd_isspecial(result) ||
(mpd_iszerocoeff(result) && (workstatus & MPD_Clamped))) {
break;
}
}
mpd_qmul(tbase, tbase, tbase, ctx, &workstatus);
mpd_qdivint(texp, texp, &two, &maxctx, &workstatus);
if (mpd_isnan(tbase) || mpd_isnan(texp)) {
mpd_seterror(result, workstatus&MPD_Errors, status);
return;
}
}
mpd_set_sign(result, resultsign);
}
/*
* The power function for integer exponents. Relative error _before_ the
* final rounding to prec:
* abs(result - base**exp) < 0.1 * 10**-prec * abs(base**exp)
*/
static void
_mpd_qpow_int(mpd_t *result, const mpd_t *base, const mpd_t *exp,
uint8_t resultsign,
const mpd_context_t *ctx, uint32_t *status)
{
mpd_context_t workctx;
MPD_NEW_STATIC(tbase,0,0,0,0);
MPD_NEW_STATIC(texp,0,0,0,0);
mpd_ssize_t n;
mpd_workcontext(&workctx, ctx);
workctx.prec += (exp->digits + exp->exp + 2);
workctx.round = MPD_ROUND_HALF_EVEN;
workctx.clamp = 0;
if (mpd_isnegative(exp)) {
workctx.prec += 1;
mpd_qdiv(&tbase, &one, base, &workctx, status);
if (*status&MPD_Errors) {
mpd_setspecial(result, MPD_POS, MPD_NAN);
goto finish;
}
}
else {
if (!mpd_qcopy(&tbase, base, status)) {
mpd_setspecial(result, MPD_POS, MPD_NAN);
goto finish;
}
}
n = mpd_qabs_uint(exp, &workctx.status);
if (workctx.status&MPD_Invalid_operation) {
if (!mpd_qcopy(&texp, exp, status)) {
mpd_setspecial(result, MPD_POS, MPD_NAN); /* GCOV_UNLIKELY */
goto finish; /* GCOV_UNLIKELY */
}
_mpd_qpow_mpd(result, &tbase, &texp, resultsign, &workctx, status);
}
else {
_mpd_qpow_uint(result, &tbase, n, resultsign, &workctx, status);
}
if (mpd_isinfinite(result)) {
/* for ROUND_DOWN, ROUND_FLOOR, etc. */
_settriple(result, resultsign, 1, MPD_EXP_INF);
}
finish:
mpd_del(&tbase);
mpd_del(&texp);
mpd_qfinalize(result, ctx, status);
}
/*
* If the exponent is infinite and base equals one, the result is one
* with a coefficient of length prec. Otherwise, result is undefined.
* Return the value of the comparison against one.
*/
static int
_qcheck_pow_one_inf(mpd_t *result, const mpd_t *base, uint8_t resultsign,
const mpd_context_t *ctx, uint32_t *status)
{
mpd_ssize_t shift;
int cmp;
if ((cmp = _mpd_cmp(base, &one)) == 0) {
shift = ctx->prec-1;
mpd_qshiftl(result, &one, shift, status);
result->exp = -shift;
mpd_set_flags(result, resultsign);
*status |= (MPD_Inexact|MPD_Rounded);
}
return cmp;
}
/*
* If abs(base) equals one, calculate the correct power of one result.
* Otherwise, result is undefined. Return the value of the comparison
* against 1.
*
* This is an internal function that does not check for specials.
*/
static int
_qcheck_pow_one(mpd_t *result, const mpd_t *base, const mpd_t *exp,
uint8_t resultsign,
const mpd_context_t *ctx, uint32_t *status)
{
uint32_t workstatus = 0;
mpd_ssize_t shift;
int cmp;
if ((cmp = _mpd_cmp_abs(base, &one)) == 0) {
if (_mpd_isint(exp)) {
if (mpd_isnegative(exp)) {
_settriple(result, resultsign, 1, 0);
return 0;
}
/* 1.000**3 = 1.000000000 */
mpd_qmul_ssize(result, exp, -base->exp, ctx, &workstatus);
if (workstatus&MPD_Errors) {
*status |= (workstatus&MPD_Errors);
return 0;
}
/* digits-1 after exponentiation */
shift = mpd_qget_ssize(result, &workstatus);
/* shift is MPD_SSIZE_MAX if result is too large */
if (shift > ctx->prec-1) {
shift = ctx->prec-1;
*status |= MPD_Rounded;
}
}
else if (mpd_ispositive(base)) {
shift = ctx->prec-1;
*status |= (MPD_Inexact|MPD_Rounded);
}
else {
return -2; /* GCOV_NOT_REACHED */
}
if (!mpd_qshiftl(result, &one, shift, status)) {
return 0;
}
result->exp = -shift;
mpd_set_flags(result, resultsign);
}
return cmp;
}
/*
* Detect certain over/underflow of x**y.
* ACL2 proof: pow-bounds.lisp.
*
* Symbols:
*
* e: EXP_INF or EXP_CLAMP
* x: base
* y: exponent
*
* omega(e) = log10(abs(e))
* zeta(x) = log10(abs(log10(x)))
* theta(y) = log10(abs(y))
*
* Upper and lower bounds:
*
* ub_omega(e) = ceil(log10(abs(e)))
* lb_theta(y) = floor(log10(abs(y)))
*
* | floor(log10(floor(abs(log10(x))))) if x < 1/10 or x >= 10
* lb_zeta(x) = | floor(log10(abs(x-1)/10)) if 1/10 <= x < 1
* | floor(log10(abs((x-1)/100))) if 1 < x < 10
*
* ub_omega(e) and lb_theta(y) are obviously upper and lower bounds
* for omega(e) and theta(y).
*
* lb_zeta is a lower bound for zeta(x):
*
* x < 1/10 or x >= 10:
*
* abs(log10(x)) >= 1, so the outer log10 is well defined. Since log10
* is strictly increasing, the end result is a lower bound.
*
* 1/10 <= x < 1:
*
* We use: log10(x) <= (x-1)/log(10)
* abs(log10(x)) >= abs(x-1)/log(10)
* abs(log10(x)) >= abs(x-1)/10
*
* 1 < x < 10:
*
* We use: (x-1)/(x*log(10)) < log10(x)
* abs((x-1)/100) < abs(log10(x))
*
* XXX: abs((x-1)/10) would work, need ACL2 proof.
*
*
* Let (0 < x < 1 and y < 0) or (x > 1 and y > 0). (H1)
* Let ub_omega(exp_inf) < lb_zeta(x) + lb_theta(y) (H2)
*
* Then:
* log10(abs(exp_inf)) < log10(abs(log10(x))) + log10(abs(y)). (1)
* exp_inf < log10(x) * y (2)
* 10**exp_inf < x**y (3)
*
* Let (0 < x < 1 and y > 0) or (x > 1 and y < 0). (H3)
* Let ub_omega(exp_clamp) < lb_zeta(x) + lb_theta(y) (H4)
*
* Then:
* log10(abs(exp_clamp)) < log10(abs(log10(x))) + log10(abs(y)). (4)
* log10(x) * y < exp_clamp (5)
* x**y < 10**exp_clamp (6)
*
*/
static mpd_ssize_t
_lower_bound_zeta(const mpd_t *x, uint32_t *status)
{
mpd_context_t maxctx;
MPD_NEW_STATIC(scratch,0,0,0,0);
mpd_ssize_t t, u;
t = mpd_adjexp(x);
if (t > 0) {
/* x >= 10 -> floor(log10(floor(abs(log10(x))))) */
return mpd_exp_digits(t) - 1;
}
else if (t < -1) {
/* x < 1/10 -> floor(log10(floor(abs(log10(x))))) */
return mpd_exp_digits(t+1) - 1;
}
else {
mpd_maxcontext(&maxctx);
mpd_qsub(&scratch, x, &one, &maxctx, status);
if (mpd_isspecial(&scratch)) {
mpd_del(&scratch);
return MPD_SSIZE_MAX;
}
u = mpd_adjexp(&scratch);
mpd_del(&scratch);
/* t == -1, 1/10 <= x < 1 -> floor(log10(abs(x-1)/10))
* t == 0, 1 < x < 10 -> floor(log10(abs(x-1)/100)) */
return (t == 0) ? u-2 : u-1;
}
}
/*
* Detect cases of certain overflow/underflow in the power function.
* Assumptions: x != 1, y != 0. The proof above is for positive x.
* If x is negative and y is an odd integer, x**y == -(abs(x)**y),
* so the analysis does not change.
*/
static int
_qcheck_pow_bounds(mpd_t *result, const mpd_t *x, const mpd_t *y,
uint8_t resultsign,
const mpd_context_t *ctx, uint32_t *status)
{
MPD_NEW_SHARED(abs_x, x);
mpd_ssize_t ub_omega, lb_zeta, lb_theta;
uint8_t sign;
mpd_set_positive(&abs_x);
lb_theta = mpd_adjexp(y);
lb_zeta = _lower_bound_zeta(&abs_x, status);
if (lb_zeta == MPD_SSIZE_MAX) {
mpd_seterror(result, MPD_Malloc_error, status);
return 1;
}
sign = (mpd_adjexp(&abs_x) < 0) ^ mpd_sign(y);
if (sign == 0) {
/* (0 < |x| < 1 and y < 0) or (|x| > 1 and y > 0) */
ub_omega = mpd_exp_digits(ctx->emax);
if (ub_omega < lb_zeta + lb_theta) {
_settriple(result, resultsign, 1, MPD_EXP_INF);
mpd_qfinalize(result, ctx, status);
return 1;
}
}
else {
/* (0 < |x| < 1 and y > 0) or (|x| > 1 and y < 0). */
ub_omega = mpd_exp_digits(mpd_etiny(ctx));
if (ub_omega < lb_zeta + lb_theta) {
_settriple(result, resultsign, 1, mpd_etiny(ctx)-1);
mpd_qfinalize(result, ctx, status);
return 1;
}
}
return 0;
}
/*
* TODO: Implement algorithm for computing exact powers from decimal.py.
* In order to prevent infinite loops, this has to be called before
* using Ziv's strategy for correct rounding.
*/
/*
static int
_mpd_qpow_exact(mpd_t *result, const mpd_t *base, const mpd_t *exp,
const mpd_context_t *ctx, uint32_t *status)
{
return 0;
}
*/
/*
* The power function for real exponents.
* Relative error: abs(result - e**y) < e**y * 1/5 * 10**(-prec - 1)
*/
static void
_mpd_qpow_real(mpd_t *result, const mpd_t *base, const mpd_t *exp,
const mpd_context_t *ctx, uint32_t *status)
{
mpd_context_t workctx;
MPD_NEW_STATIC(texp,0,0,0,0);
if (!mpd_qcopy(&texp, exp, status)) {
mpd_seterror(result, MPD_Malloc_error, status);
return;
}
mpd_maxcontext(&workctx);
workctx.prec = (base->digits > ctx->prec) ? base->digits : ctx->prec;
workctx.prec += (4 + MPD_EXPDIGITS);
workctx.round = MPD_ROUND_HALF_EVEN;
workctx.allcr = ctx->allcr;
/*
* extra := MPD_EXPDIGITS = MPD_EXP_MAX_T
* wp := prec + 4 + extra
* abs(err) < 5 * 10**-wp
* y := log(base) * exp
* Calculate:
* 1) e**(y * (1 + err)**2) * (1 + err)
* = e**y * e**(y * (2*err + err**2)) * (1 + err)
* ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
* Relative error of the underlined term:
* 2) abs(e**(y * (2*err + err**2)) - 1)
* Case abs(y) >= 10**extra:
* 3) adjexp(y)+1 > log10(abs(y)) >= extra
* This triggers the Overflow/Underflow shortcut in _mpd_qexp(),
* so no further analysis is necessary.
* Case abs(y) < 10**extra:
* 4) abs(y * (2*err + err**2)) < 1/5 * 10**(-prec - 2)
* Use (see _mpd_qexp):
* 5) abs(x) <= 9/10 * 10**-p ==> abs(e**x - 1) < 10**-p
* With 2), 4) and 5):
* 6) abs(e**(y * (2*err + err**2)) - 1) < 10**(-prec - 2)
* The complete relative error of 1) is:
* 7) abs(result - e**y) < e**y * 1/5 * 10**(-prec - 1)
*/
mpd_qln(result, base, &workctx, &workctx.status);
mpd_qmul(result, result, &texp, &workctx, &workctx.status);
mpd_qexp(result, result, &workctx, status);
mpd_del(&texp);
*status |= (workctx.status&MPD_Errors);
*status |= (MPD_Inexact|MPD_Rounded);
}
/* The power function: base**exp */
void
mpd_qpow(mpd_t *result, const mpd_t *base, const mpd_t *exp,
const mpd_context_t *ctx, uint32_t *status)
{
uint8_t resultsign = 0;
int intexp = 0;
int cmp;
if (mpd_isspecial(base) || mpd_isspecial(exp)) {
if (mpd_qcheck_nans(result, base, exp, ctx, status)) {
return;
}
}
if (mpd_isinteger(exp)) {
intexp = 1;
resultsign = mpd_isnegative(base) && mpd_isodd(exp);
}
if (mpd_iszero(base)) {
if (mpd_iszero(exp)) {
mpd_seterror(result, MPD_Invalid_operation, status);
}
else if (mpd_isnegative(exp)) {
mpd_setspecial(result, resultsign, MPD_INF);
}
else {
_settriple(result, resultsign, 0, 0);
}
return;
}
if (mpd_isnegative(base)) {
if (!intexp || mpd_isinfinite(exp)) {
mpd_seterror(result, MPD_Invalid_operation, status);
return;
}
}
if (mpd_isinfinite(exp)) {
/* power of one */
cmp = _qcheck_pow_one_inf(result, base, resultsign, ctx, status);
if (cmp == 0) {
return;
}
else {
cmp *= mpd_arith_sign(exp);
if (cmp < 0) {
_settriple(result, resultsign, 0, 0);
}
else {
mpd_setspecial(result, resultsign, MPD_INF);
}
}
return;
}
if (mpd_isinfinite(base)) {
if (mpd_iszero(exp)) {
_settriple(result, resultsign, 1, 0);
}
else if (mpd_isnegative(exp)) {
_settriple(result, resultsign, 0, 0);
}
else {
mpd_setspecial(result, resultsign, MPD_INF);
}
return;
}
if (mpd_iszero(exp)) {
_settriple(result, resultsign, 1, 0);
return;
}
if (_qcheck_pow_one(result, base, exp, resultsign, ctx, status) == 0) {
return;
}
if (_qcheck_pow_bounds(result, base, exp, resultsign, ctx, status)) {
return;
}
if (intexp) {
_mpd_qpow_int(result, base, exp, resultsign, ctx, status);
}
else {
_mpd_qpow_real(result, base, exp, ctx, status);
if (!mpd_isspecial(result) && _mpd_cmp(result, &one) == 0) {
mpd_ssize_t shift = ctx->prec-1;
mpd_qshiftl(result, &one, shift, status);
result->exp = -shift;
}
if (mpd_isinfinite(result)) {
/* for ROUND_DOWN, ROUND_FLOOR, etc. */
_settriple(result, MPD_POS, 1, MPD_EXP_INF);
}
mpd_qfinalize(result, ctx, status);
}
}
/*
* Internal function: Integer powmod with mpd_uint_t exponent, base is modified!
* Function can fail with MPD_Malloc_error.
*/
static inline void
_mpd_qpowmod_uint(mpd_t *result, mpd_t *base, mpd_uint_t exp,
const mpd_t *mod, uint32_t *status)
{
mpd_context_t maxcontext;
mpd_maxcontext(&maxcontext);
/* resize to smaller cannot fail */
mpd_qcopy(result, &one, status);
while (exp > 0) {
if (exp & 1) {
_mpd_qmul_exact(result, result, base, &maxcontext, status);
mpd_qrem(result, result, mod, &maxcontext, status);
}
_mpd_qmul_exact(base, base, base, &maxcontext, status);
mpd_qrem(base, base, mod, &maxcontext, status);
exp >>= 1;
}
}
/* The powmod function: (base**exp) % mod */
void
mpd_qpowmod(mpd_t *result, const mpd_t *base, const mpd_t *exp,
const mpd_t *mod,
const mpd_context_t *ctx, uint32_t *status)
{
mpd_context_t maxcontext;
MPD_NEW_STATIC(tbase,0,0,0,0);
MPD_NEW_STATIC(texp,0,0,0,0);
MPD_NEW_STATIC(tmod,0,0,0,0);
MPD_NEW_STATIC(tmp,0,0,0,0);
MPD_NEW_CONST(two,0,0,1,1,1,2);
mpd_ssize_t tbase_exp, texp_exp;
mpd_ssize_t i;
mpd_t t;
mpd_uint_t r;
uint8_t sign;
if (mpd_isspecial(base) || mpd_isspecial(exp) || mpd_isspecial(mod)) {
if (mpd_qcheck_3nans(result, base, exp, mod, ctx, status)) {
return;
}
mpd_seterror(result, MPD_Invalid_operation, status);
return;
}
if (!_mpd_isint(base) || !_mpd_isint(exp) || !_mpd_isint(mod)) {
mpd_seterror(result, MPD_Invalid_operation, status);
return;
}
if (mpd_iszerocoeff(mod)) {
mpd_seterror(result, MPD_Invalid_operation, status);
return;
}
if (mod->digits+mod->exp > ctx->prec) {
mpd_seterror(result, MPD_Invalid_operation, status);
return;
}
sign = (mpd_isnegative(base)) && (mpd_isodd(exp));
if (mpd_iszerocoeff(exp)) {
if (mpd_iszerocoeff(base)) {
mpd_seterror(result, MPD_Invalid_operation, status);
return;
}
r = (_mpd_cmp_abs(mod, &one)==0) ? 0 : 1;
_settriple(result, sign, r, 0);
return;
}
if (mpd_isnegative(exp)) {
mpd_seterror(result, MPD_Invalid_operation, status);
return;
}
if (mpd_iszerocoeff(base)) {
_settriple(result, sign, 0, 0);
return;
}
mpd_maxcontext(&maxcontext);
mpd_qrescale(&tmod, mod, 0, &maxcontext, &maxcontext.status);
if (maxcontext.status&MPD_Errors) {
mpd_seterror(result, maxcontext.status&MPD_Errors, status);
goto out;
}
maxcontext.status = 0;
mpd_set_positive(&tmod);
mpd_qround_to_int(&tbase, base, &maxcontext, status);
mpd_set_positive(&tbase);
tbase_exp = tbase.exp;
tbase.exp = 0;
mpd_qround_to_int(&texp, exp, &maxcontext, status);
texp_exp = texp.exp;
texp.exp = 0;
/* base = (base.int % modulo * pow(10, base.exp, modulo)) % modulo */
mpd_qrem(&tbase, &tbase, &tmod, &maxcontext, status);
mpd_qshiftl(result, &one, tbase_exp, status);
mpd_qrem(result, result, &tmod, &maxcontext, status);
_mpd_qmul_exact(&tbase, &tbase, result, &maxcontext, status);
mpd_qrem(&tbase, &tbase, &tmod, &maxcontext, status);
if (mpd_isspecial(&tbase) ||
mpd_isspecial(&texp) ||
mpd_isspecial(&tmod)) {
goto mpd_errors;
}
for (i = 0; i < texp_exp; i++) {
_mpd_qpowmod_uint(&tmp, &tbase, 10, &tmod, status);
t = tmp;
tmp = tbase;
tbase = t;
}
if (mpd_isspecial(&tbase)) {
goto mpd_errors; /* GCOV_UNLIKELY */
}
/* resize to smaller cannot fail */
mpd_qcopy(result, &one, status);
while (mpd_isfinite(&texp) && !mpd_iszero(&texp)) {
if (mpd_isodd(&texp)) {
_mpd_qmul_exact(result, result, &tbase, &maxcontext, status);
mpd_qrem(result, result, &tmod, &maxcontext, status);
}
_mpd_qmul_exact(&tbase, &tbase, &tbase, &maxcontext, status);
mpd_qrem(&tbase, &tbase, &tmod, &maxcontext, status);
mpd_qdivint(&texp, &texp, &two, &maxcontext, status);
}
if (mpd_isspecial(&texp) || mpd_isspecial(&tbase) ||
mpd_isspecial(&tmod) || mpd_isspecial(result)) {
/* MPD_Malloc_error */
goto mpd_errors;
}
else {
mpd_set_sign(result, sign);
}
out:
mpd_del(&tbase);
mpd_del(&texp);
mpd_del(&tmod);
mpd_del(&tmp);
return;
mpd_errors:
mpd_setspecial(result, MPD_POS, MPD_NAN);
goto out;
}
void
mpd_qquantize(mpd_t *result, const mpd_t *a, const mpd_t *b,
const mpd_context_t *ctx, uint32_t *status)
{
uint32_t workstatus = 0;
mpd_ssize_t b_exp = b->exp;
mpd_ssize_t expdiff, shift;
mpd_uint_t rnd;
if (mpd_isspecial(a) || mpd_isspecial(b)) {
if (mpd_qcheck_nans(result, a, b, ctx, status)) {
return;
}
if (mpd_isinfinite(a) && mpd_isinfinite(b)) {
mpd_qcopy(result, a, status);
return;
}
mpd_seterror(result, MPD_Invalid_operation, status);
return;
}
if (b->exp > ctx->emax || b->exp < mpd_etiny(ctx)) {
mpd_seterror(result, MPD_Invalid_operation, status);
return;
}
if (mpd_iszero(a)) {
_settriple(result, mpd_sign(a), 0, b->exp);
mpd_qfinalize(result, ctx, status);
return;
}
expdiff = a->exp - b->exp;
if (a->digits + expdiff > ctx->prec) {
mpd_seterror(result, MPD_Invalid_operation, status);
return;
}
if (expdiff >= 0) {
shift = expdiff;
if (!mpd_qshiftl(result, a, shift, status)) {
return;
}
result->exp = b_exp;
}
else {
/* At this point expdiff < 0 and a->digits+expdiff <= prec,
* so the shift before an increment will fit in prec. */
shift = -expdiff;
rnd = mpd_qshiftr(result, a, shift, status);
if (rnd == MPD_UINT_MAX) {
return;
}
result->exp = b_exp;
if (!_mpd_apply_round_fit(result, rnd, ctx, status)) {
return;
}
workstatus |= MPD_Rounded;
if (rnd) {
workstatus |= MPD_Inexact;
}
}
if (mpd_adjexp(result) > ctx->emax ||
mpd_adjexp(result) < mpd_etiny(ctx)) {
mpd_seterror(result, MPD_Invalid_operation, status);
return;
}
*status |= workstatus;
mpd_qfinalize(result, ctx, status);
}
void
mpd_qreduce(mpd_t *result, const mpd_t *a, const mpd_context_t *ctx,
uint32_t *status)
{
mpd_ssize_t shift, maxexp, maxshift;
uint8_t sign_a = mpd_sign(a);
if (mpd_isspecial(a)) {
if (mpd_qcheck_nan(result, a, ctx, status)) {
return;
}
mpd_qcopy(result, a, status);
return;
}
if (!mpd_qcopy(result, a, status)) {
return;
}
mpd_qfinalize(result, ctx, status);
if (mpd_isspecial(result)) {
return;
}
if (mpd_iszero(result)) {
_settriple(result, sign_a, 0, 0);
return;
}
shift = mpd_trail_zeros(result);
maxexp = (ctx->clamp) ? mpd_etop(ctx) : ctx->emax;
/* After the finalizing above result->exp <= maxexp. */
maxshift = maxexp - result->exp;
shift = (shift > maxshift) ? maxshift : shift;
mpd_qshiftr_inplace(result, shift);
result->exp += shift;
}
void
mpd_qrem(mpd_t *r, const mpd_t *a, const mpd_t *b, const mpd_context_t *ctx,
uint32_t *status)
{
MPD_NEW_STATIC(q,0,0,0,0);
if (mpd_isspecial(a) || mpd_isspecial(b)) {
if (mpd_qcheck_nans(r, a, b, ctx, status)) {
return;
}
if (mpd_isinfinite(a)) {
mpd_seterror(r, MPD_Invalid_operation, status);
return;
}
if (mpd_isinfinite(b)) {
mpd_qcopy(r, a, status);
mpd_qfinalize(r, ctx, status);
return;
}
/* debug */
abort(); /* GCOV_NOT_REACHED */
}
if (mpd_iszerocoeff(b)) {
if (mpd_iszerocoeff(a)) {
mpd_seterror(r, MPD_Division_undefined, status);
}
else {
mpd_seterror(r, MPD_Invalid_operation, status);
}
return;
}
_mpd_qdivmod(&q, r, a, b, ctx, status);
mpd_del(&q);
mpd_qfinalize(r, ctx, status);
}
void
mpd_qrem_near(mpd_t *r, const mpd_t *a, const mpd_t *b,
const mpd_context_t *ctx, uint32_t *status)
{
mpd_context_t workctx;
MPD_NEW_STATIC(btmp,0,0,0,0);
MPD_NEW_STATIC(q,0,0,0,0);
mpd_ssize_t expdiff, qdigits;
int cmp, isodd, allnine;
if (mpd_isspecial(a) || mpd_isspecial(b)) {
if (mpd_qcheck_nans(r, a, b, ctx, status)) {
return;
}
if (mpd_isinfinite(a)) {
mpd_seterror(r, MPD_Invalid_operation, status);
return;
}
if (mpd_isinfinite(b)) {
mpd_qcopy(r, a, status);
mpd_qfinalize(r, ctx, status);
return;
}
/* debug */
abort(); /* GCOV_NOT_REACHED */
}
if (mpd_iszerocoeff(b)) {
if (mpd_iszerocoeff(a)) {
mpd_seterror(r, MPD_Division_undefined, status);
}
else {
mpd_seterror(r, MPD_Invalid_operation, status);
}
return;
}
if (r == b) {
if (!mpd_qcopy(&btmp, b, status)) {
mpd_seterror(r, MPD_Malloc_error, status);
return;
}
b = &btmp;
}
_mpd_qdivmod(&q, r, a, b, ctx, status);
if (mpd_isnan(&q) || mpd_isnan(r)) {
goto finish;
}
if (mpd_iszerocoeff(r)) {
goto finish;
}
expdiff = mpd_adjexp(b) - mpd_adjexp(r);
if (-1 <= expdiff && expdiff <= 1) {
allnine = mpd_coeff_isallnine(&q);
qdigits = q.digits;
isodd = mpd_isodd(&q);
mpd_maxcontext(&workctx);
if (mpd_sign(a) == mpd_sign(b)) {
/* sign(r) == sign(b) */
_mpd_qsub(&q, r, b, &workctx, &workctx.status);
}
else {
/* sign(r) != sign(b) */
_mpd_qadd(&q, r, b, &workctx, &workctx.status);
}
if (workctx.status&MPD_Errors) {
mpd_seterror(r, workctx.status&MPD_Errors, status);
goto finish;
}
cmp = _mpd_cmp_abs(&q, r);
if (cmp < 0 || (cmp == 0 && isodd)) {
/* abs(r) > abs(b)/2 or abs(r) == abs(b)/2 and isodd(quotient) */
if (allnine && qdigits == ctx->prec) {
/* abs(quotient) + 1 == 10**prec */
mpd_seterror(r, MPD_Division_impossible, status);
goto finish;
}
mpd_qcopy(r, &q, status);
}
}
finish:
mpd_del(&btmp);
mpd_del(&q);
mpd_qfinalize(r, ctx, status);
}
static void
_mpd_qrescale(mpd_t *result, const mpd_t *a, mpd_ssize_t exp,
const mpd_context_t *ctx, uint32_t *status)
{
mpd_ssize_t expdiff, shift;
mpd_uint_t rnd;
if (mpd_isspecial(a)) {
mpd_qcopy(result, a, status);
return;
}
if (mpd_iszero(a)) {
_settriple(result, mpd_sign(a), 0, exp);
return;
}
expdiff = a->exp - exp;
if (expdiff >= 0) {
shift = expdiff;
if (a->digits + shift > MPD_MAX_PREC+1) {
mpd_seterror(result, MPD_Invalid_operation, status);
return;
}
if (!mpd_qshiftl(result, a, shift, status)) {
return;
}
result->exp = exp;
}
else {
shift = -expdiff;
rnd = mpd_qshiftr(result, a, shift, status);
if (rnd == MPD_UINT_MAX) {
return;
}
result->exp = exp;
_mpd_apply_round_excess(result, rnd, ctx, status);
*status |= MPD_Rounded;
if (rnd) {
*status |= MPD_Inexact;
}
}
if (mpd_issubnormal(result, ctx)) {
*status |= MPD_Subnormal;
}
}
/*
* Rescale a number so that it has exponent 'exp'. Does not regard context
* precision, emax, emin, but uses the rounding mode. Special numbers are
* quietly copied. Restrictions:
*
* MPD_MIN_ETINY <= exp <= MPD_MAX_EMAX+1
* result->digits <= MPD_MAX_PREC+1
*/
void
mpd_qrescale(mpd_t *result, const mpd_t *a, mpd_ssize_t exp,
const mpd_context_t *ctx, uint32_t *status)
{
if (exp > MPD_MAX_EMAX+1 || exp < MPD_MIN_ETINY) {
mpd_seterror(result, MPD_Invalid_operation, status);
return;
}
_mpd_qrescale(result, a, exp, ctx, status);
}
/*
* Same as mpd_qrescale, but with relaxed restrictions. The result of this
* function should only be used for formatting a number and never as input
* for other operations.
*
* MPD_MIN_ETINY-MPD_MAX_PREC <= exp <= MPD_MAX_EMAX+1
* result->digits <= MPD_MAX_PREC+1
*/
void
mpd_qrescale_fmt(mpd_t *result, const mpd_t *a, mpd_ssize_t exp,
const mpd_context_t *ctx, uint32_t *status)
{
if (exp > MPD_MAX_EMAX+1 || exp < MPD_MIN_ETINY-MPD_MAX_PREC) {
mpd_seterror(result, MPD_Invalid_operation, status);
return;
}
_mpd_qrescale(result, a, exp, ctx, status);
}
/* Round to an integer according to 'action' and ctx->round. */
enum {TO_INT_EXACT, TO_INT_SILENT, TO_INT_TRUNC};
static void
_mpd_qround_to_integral(int action, mpd_t *result, const mpd_t *a,
const mpd_context_t *ctx, uint32_t *status)
{
mpd_uint_t rnd;
if (mpd_isspecial(a)) {
if (mpd_qcheck_nan(result, a, ctx, status)) {
return;
}
mpd_qcopy(result, a, status);
return;
}
if (a->exp >= 0) {
mpd_qcopy(result, a, status);
return;
}
if (mpd_iszerocoeff(a)) {
_settriple(result, mpd_sign(a), 0, 0);
return;
}
rnd = mpd_qshiftr(result, a, -a->exp, status);
if (rnd == MPD_UINT_MAX) {
return;
}
result->exp = 0;
if (action == TO_INT_EXACT || action == TO_INT_SILENT) {
_mpd_apply_round_excess(result, rnd, ctx, status);
if (action == TO_INT_EXACT) {
*status |= MPD_Rounded;
if (rnd) {
*status |= MPD_Inexact;
}
}
}
}
void
mpd_qround_to_intx(mpd_t *result, const mpd_t *a, const mpd_context_t *ctx,
uint32_t *status)
{
(void)_mpd_qround_to_integral(TO_INT_EXACT, result, a, ctx, status);
}
void
mpd_qround_to_int(mpd_t *result, const mpd_t *a, const mpd_context_t *ctx,
uint32_t *status)
{
(void)_mpd_qround_to_integral(TO_INT_SILENT, result, a, ctx, status);
}
void
mpd_qtrunc(mpd_t *result, const mpd_t *a, const mpd_context_t *ctx,
uint32_t *status)
{
(void)_mpd_qround_to_integral(TO_INT_TRUNC, result, a, ctx, status);
}
void
mpd_qfloor(mpd_t *result, const mpd_t *a, const mpd_context_t *ctx,
uint32_t *status)
{
mpd_context_t workctx = *ctx;
workctx.round = MPD_ROUND_FLOOR;
(void)_mpd_qround_to_integral(TO_INT_SILENT, result, a,
&workctx, status);
}
void
mpd_qceil(mpd_t *result, const mpd_t *a, const mpd_context_t *ctx,
uint32_t *status)
{
mpd_context_t workctx = *ctx;
workctx.round = MPD_ROUND_CEILING;
(void)_mpd_qround_to_integral(TO_INT_SILENT, result, a,
&workctx, status);
}
int
mpd_same_quantum(const mpd_t *a, const mpd_t *b)
{
if (mpd_isspecial(a) || mpd_isspecial(b)) {
return ((mpd_isnan(a) && mpd_isnan(b)) ||
(mpd_isinfinite(a) && mpd_isinfinite(b)));
}
return a->exp == b->exp;
}
/* Schedule the increase in precision for the Newton iteration. */
static inline int
recpr_schedule_prec(mpd_ssize_t klist[MPD_MAX_PREC_LOG2],
mpd_ssize_t maxprec, mpd_ssize_t initprec)
{
mpd_ssize_t k;
int i;
assert(maxprec > 0 && initprec > 0);
if (maxprec <= initprec) return -1;
i = 0; k = maxprec;
do {
k = (k+1) / 2;
klist[i++] = k;
} while (k > initprec);
return i-1;
}
/*
* Initial approximation for the reciprocal:
* k_0 := MPD_RDIGITS-2
* z_0 := 10**(-k_0) * floor(10**(2*k_0 + 2) / floor(v * 10**(k_0 + 2)))
* Absolute error:
* |1/v - z_0| < 10**(-k_0)
* ACL2 proof: maxerror-inverse-approx
*/
static void
_mpd_qreciprocal_approx(mpd_t *z, const mpd_t *v, uint32_t *status)
{
mpd_uint_t p10data[2] = {0, mpd_pow10[MPD_RDIGITS-2]};
mpd_uint_t dummy, word;
int n;
assert(v->exp == -v->digits);
_mpd_get_msdigits(&dummy, &word, v, MPD_RDIGITS);
n = mpd_word_digits(word);
word *= mpd_pow10[MPD_RDIGITS-n];
mpd_qresize(z, 2, status);
(void)_mpd_shortdiv(z->data, p10data, 2, word);
mpd_clear_flags(z);
z->exp = -(MPD_RDIGITS-2);
z->len = (z->data[1] == 0) ? 1 : 2;
mpd_setdigits(z);
}
/*
* Reciprocal, calculated with Newton's Method. Assumption: result != a.
* NOTE: The comments in the function show that certain operations are
* exact. The proof for the maximum error is too long to fit in here.
* ACL2 proof: maxerror-inverse-complete
*/
static void
_mpd_qreciprocal(mpd_t *result, const mpd_t *a, const mpd_context_t *ctx,
uint32_t *status)
{
mpd_context_t varcontext, maxcontext;
mpd_t *z = result; /* current approximation */
mpd_t *v; /* a, normalized to a number between 0.1 and 1 */
MPD_NEW_SHARED(vtmp, a); /* v shares data with a */
MPD_NEW_STATIC(s,0,0,0,0); /* temporary variable */
MPD_NEW_STATIC(t,0,0,0,0); /* temporary variable */
MPD_NEW_CONST(two,0,0,1,1,1,2); /* const 2 */
mpd_ssize_t klist[MPD_MAX_PREC_LOG2];
mpd_ssize_t adj, maxprec, initprec;
uint8_t sign = mpd_sign(a);
int i;
assert(result != a);
v = &vtmp;
mpd_clear_flags(v);
adj = v->digits + v->exp;
v->exp = -v->digits;
/* Initial approximation */
_mpd_qreciprocal_approx(z, v, status);
mpd_maxcontext(&varcontext);
mpd_maxcontext(&maxcontext);
varcontext.round = maxcontext.round = MPD_ROUND_TRUNC;
varcontext.emax = maxcontext.emax = MPD_MAX_EMAX + 100;
varcontext.emin = maxcontext.emin = MPD_MIN_EMIN - 100;
maxcontext.prec = MPD_MAX_PREC + 100;
maxprec = ctx->prec;
maxprec += 2;
initprec = MPD_RDIGITS-3;
i = recpr_schedule_prec(klist, maxprec, initprec);
for (; i >= 0; i--) {
/* Loop invariant: z->digits <= klist[i]+7 */
/* Let s := z**2, exact result */
_mpd_qmul_exact(&s, z, z, &maxcontext, status);
varcontext.prec = 2*klist[i] + 5;
if (v->digits > varcontext.prec) {
/* Let t := v, truncated to n >= 2*k+5 fraction digits */
mpd_qshiftr(&t, v, v->digits-varcontext.prec, status);
t.exp = -varcontext.prec;
/* Let t := trunc(v)*s, truncated to n >= 2*k+1 fraction digits */
mpd_qmul(&t, &t, &s, &varcontext, status);
}
else { /* v->digits <= 2*k+5 */
/* Let t := v*s, truncated to n >= 2*k+1 fraction digits */
mpd_qmul(&t, v, &s, &varcontext, status);
}
/* Let s := 2*z, exact result */
_mpd_qmul_exact(&s, z, &two, &maxcontext, status);
/* s.digits < t.digits <= 2*k+5, |adjexp(s)-adjexp(t)| <= 1,
* so the subtraction generates at most 2*k+6 <= klist[i+1]+7
* digits. The loop invariant is preserved. */
_mpd_qsub_exact(z, &s, &t, &maxcontext, status);
}
if (!mpd_isspecial(z)) {
z->exp -= adj;
mpd_set_flags(z, sign);
}
mpd_del(&s);
mpd_del(&t);
mpd_qfinalize(z, ctx, status);
}
/*
* Internal function for large numbers:
*
* q, r = divmod(coeff(a), coeff(b))
*
* Strategy: Multiply the dividend by the reciprocal of the divisor. The
* inexact result is fixed by a small loop, using at most one iteration.
*
* ACL2 proofs:
* ------------
* 1) q is a natural number. (ndivmod-quotient-natp)
* 2) r is a natural number. (ndivmod-remainder-natp)
* 3) a = q * b + r (ndivmod-q*b+r==a)
* 4) r < b (ndivmod-remainder-<-b)
*/
static void
_mpd_base_ndivmod(mpd_t *q, mpd_t *r, const mpd_t *a, const mpd_t *b,
uint32_t *status)
{
mpd_context_t workctx;
mpd_t *qq = q, *rr = r;
mpd_t aa, bb;
int k;
_mpd_copy_shared(&aa, a);
_mpd_copy_shared(&bb, b);
mpd_set_positive(&aa);
mpd_set_positive(&bb);
aa.exp = 0;
bb.exp = 0;
if (q == a || q == b) {
if ((qq = mpd_qnew()) == NULL) {
*status |= MPD_Malloc_error;
goto nanresult;
}
}
if (r == a || r == b) {
if ((rr = mpd_qnew()) == NULL) {
*status |= MPD_Malloc_error;
goto nanresult;
}
}
mpd_maxcontext(&workctx);
/* Let prec := adigits - bdigits + 4 */
workctx.prec = a->digits - b->digits + 1 + 3;
if (a->digits > MPD_MAX_PREC || workctx.prec > MPD_MAX_PREC) {
*status |= MPD_Division_impossible;
goto nanresult;
}
/* Let x := _mpd_qreciprocal(b, prec)
* Then x is bounded by:
* 1) 1/b - 10**(-prec - bdigits) < x < 1/b + 10**(-prec - bdigits)
* 2) 1/b - 10**(-adigits - 4) < x < 1/b + 10**(-adigits - 4)
*/
_mpd_qreciprocal(rr, &bb, &workctx, &workctx.status);
/* Get an estimate for the quotient. Let q := a * x
* Then q is bounded by:
* 3) a/b - 10**-4 < q < a/b + 10**-4
*/
_mpd_qmul(qq, &aa, rr, &workctx, &workctx.status);
/* Truncate q to an integer:
* 4) a/b - 2 < trunc(q) < a/b + 1
*/
mpd_qtrunc(qq, qq, &workctx, &workctx.status);
workctx.prec = aa.digits + 3;
workctx.emax = MPD_MAX_EMAX + 3;
workctx.emin = MPD_MIN_EMIN - 3;
/* Multiply the estimate for q by b:
* 5) a - 2 * b < trunc(q) * b < a + b
*/
_mpd_qmul(rr, &bb, qq, &workctx, &workctx.status);
/* Get the estimate for r such that a = q * b + r. */
_mpd_qsub_exact(rr, &aa, rr, &workctx, &workctx.status);
/* Fix the result. At this point -b < r < 2*b, so the correction loop
takes at most one iteration. */
for (k = 0;; k++) {
if (mpd_isspecial(qq) || mpd_isspecial(rr)) {
*status |= (workctx.status&MPD_Errors);
goto nanresult;
}
if (k > 2) { /* Allow two iterations despite the proof. */
mpd_err_warn("libmpdec: internal error in " /* GCOV_NOT_REACHED */
"_mpd_base_ndivmod: please report"); /* GCOV_NOT_REACHED */
*status |= MPD_Invalid_operation; /* GCOV_NOT_REACHED */
goto nanresult; /* GCOV_NOT_REACHED */
}
/* r < 0 */
else if (_mpd_cmp(&zero, rr) == 1) {
_mpd_qadd_exact(rr, rr, &bb, &workctx, &workctx.status);
_mpd_qadd_exact(qq, qq, &minus_one, &workctx, &workctx.status);
}
/* 0 <= r < b */
else if (_mpd_cmp(rr, &bb) == -1) {
break;
}
/* r >= b */
else {
_mpd_qsub_exact(rr, rr, &bb, &workctx, &workctx.status);
_mpd_qadd_exact(qq, qq, &one, &workctx, &workctx.status);
}
}
if (qq != q) {
if (!mpd_qcopy(q, qq, status)) {
goto nanresult; /* GCOV_UNLIKELY */
}
mpd_del(qq);
}
if (rr != r) {
if (!mpd_qcopy(r, rr, status)) {
goto nanresult; /* GCOV_UNLIKELY */
}
mpd_del(rr);
}
*status |= (workctx.status&MPD_Errors);
return;
nanresult:
if (qq && qq != q) mpd_del(qq);
if (rr && rr != r) mpd_del(rr);
mpd_setspecial(q, MPD_POS, MPD_NAN);
mpd_setspecial(r, MPD_POS, MPD_NAN);
}
/* LIBMPDEC_ONLY */
/*
* Schedule the optimal precision increase for the Newton iteration.
* v := input operand
* z_0 := initial approximation
* initprec := natural number such that abs(sqrt(v) - z_0) < 10**-initprec
* maxprec := target precision
*
* For convenience the output klist contains the elements in reverse order:
* klist := [k_n-1, ..., k_0], where
* 1) k_0 <= initprec and
* 2) abs(sqrt(v) - result) < 10**(-2*k_n-1 + 2) <= 10**-maxprec.
*/
static inline int
invroot_schedule_prec(mpd_ssize_t klist[MPD_MAX_PREC_LOG2],
mpd_ssize_t maxprec, mpd_ssize_t initprec)
{
mpd_ssize_t k;
int i;
assert(maxprec >= 3 && initprec >= 3);
if (maxprec <= initprec) return -1;
i = 0; k = maxprec;
do {
k = (k+3) / 2;
klist[i++] = k;
} while (k > initprec);
return i-1;
}
/*
* Initial approximation for the inverse square root function.
* Input:
* v := rational number, with 1 <= v < 100
* vhat := floor(v * 10**6)
* Output:
* z := approximation to 1/sqrt(v), such that abs(z - 1/sqrt(v)) < 10**-3.
*/
static inline void
_invroot_init_approx(mpd_t *z, mpd_uint_t vhat)
{
mpd_uint_t lo = 1000;
mpd_uint_t hi = 10000;
mpd_uint_t a, sq;
assert(lo*lo <= vhat && vhat < (hi+1)*(hi+1));
for(;;) {
a = (lo + hi) / 2;
sq = a * a;
if (vhat >= sq) {
if (vhat < sq + 2*a + 1) {
break;
}
lo = a + 1;
}
else {
hi = a - 1;
}
}
/*
* After the binary search we have:
* 1) a**2 <= floor(v * 10**6) < (a + 1)**2
* This implies:
* 2) a**2 <= v * 10**6 < (a + 1)**2
* 3) a <= sqrt(v) * 10**3 < a + 1
* Since 10**3 <= a:
* 4) 0 <= 10**prec/a - 1/sqrt(v) < 10**-prec
* We have:
* 5) 10**3/a - 10**-3 < floor(10**9/a) * 10**-6 <= 10**3/a
* Merging 4) and 5):
* 6) abs(floor(10**9/a) * 10**-6 - 1/sqrt(v)) < 10**-3
*/
mpd_minalloc(z);
mpd_clear_flags(z);
z->data[0] = 1000000000UL / a;
z->len = 1;
z->exp = -6;
mpd_setdigits(z);
}
/*
* Set 'result' to 1/sqrt(a).
* Relative error: abs(result - 1/sqrt(a)) < 10**-prec * 1/sqrt(a)
*/
static void
_mpd_qinvroot(mpd_t *result, const mpd_t *a, const mpd_context_t *ctx,
uint32_t *status)
{
uint32_t workstatus = 0;
mpd_context_t varcontext, maxcontext;
mpd_t *z = result; /* current approximation */
mpd_t *v; /* a, normalized to a number between 1 and 100 */
MPD_NEW_SHARED(vtmp, a); /* by default v will share data with a */
MPD_NEW_STATIC(s,0,0,0,0); /* temporary variable */
MPD_NEW_STATIC(t,0,0,0,0); /* temporary variable */
MPD_NEW_CONST(one_half,0,-1,1,1,1,5);
MPD_NEW_CONST(three,0,0,1,1,1,3);
mpd_ssize_t klist[MPD_MAX_PREC_LOG2];
mpd_ssize_t ideal_exp, shift;
mpd_ssize_t adj, tz;
mpd_ssize_t maxprec, fracdigits;
mpd_uint_t vhat, dummy;
int i, n;
ideal_exp = -(a->exp - (a->exp & 1)) / 2;
v = &vtmp;
if (result == a) {
if ((v = mpd_qncopy(a)) == NULL) {
mpd_seterror(result, MPD_Malloc_error, status);
return;
}
}
/* normalize a to 1 <= v < 100 */
if ((v->digits+v->exp) & 1) {
fracdigits = v->digits - 1;
v->exp = -fracdigits;
n = (v->digits > 7) ? 7 : (int)v->digits;
/* Let vhat := floor(v * 10**(2*initprec)) */
_mpd_get_msdigits(&dummy, &vhat, v, n);
if (n < 7) {
vhat *= mpd_pow10[7-n];
}
}
else {
fracdigits = v->digits - 2;
v->exp = -fracdigits;
n = (v->digits > 8) ? 8 : (int)v->digits;
/* Let vhat := floor(v * 10**(2*initprec)) */
_mpd_get_msdigits(&dummy, &vhat, v, n);
if (n < 8) {
vhat *= mpd_pow10[8-n];
}
}
adj = (a->exp-v->exp) / 2;
/* initial approximation */
_invroot_init_approx(z, vhat);
mpd_maxcontext(&maxcontext);
mpd_maxcontext(&varcontext);
varcontext.round = MPD_ROUND_TRUNC;
maxprec = ctx->prec + 1;
/* initprec == 3 */
i = invroot_schedule_prec(klist, maxprec, 3);
for (; i >= 0; i--) {
varcontext.prec = 2*klist[i]+2;
mpd_qmul(&s, z, z, &maxcontext, &workstatus);
if (v->digits > varcontext.prec) {
shift = v->digits - varcontext.prec;
mpd_qshiftr(&t, v, shift, &workstatus);
t.exp += shift;
mpd_qmul(&t, &t, &s, &varcontext, &workstatus);
}
else {
mpd_qmul(&t, v, &s, &varcontext, &workstatus);
}
mpd_qsub(&t, &three, &t, &maxcontext, &workstatus);
mpd_qmul(z, z, &t, &varcontext, &workstatus);
mpd_qmul(z, z, &one_half, &maxcontext, &workstatus);
}
z->exp -= adj;
tz = mpd_trail_zeros(result);
shift = ideal_exp - result->exp;
shift = (tz > shift) ? shift : tz;
if (shift > 0) {
mpd_qshiftr_inplace(result, shift);
result->exp += shift;
}
mpd_del(&s);
mpd_del(&t);
if (v != &vtmp) mpd_del(v);
*status |= (workstatus&MPD_Errors);
*status |= (MPD_Rounded|MPD_Inexact);
}
void
mpd_qinvroot(mpd_t *result, const mpd_t *a, const mpd_context_t *ctx,
uint32_t *status)
{
mpd_context_t workctx;
if (mpd_isspecial(a)) {
if (mpd_qcheck_nan(result, a, ctx, status)) {
return;
}
if (mpd_isnegative(a)) {
mpd_seterror(result, MPD_Invalid_operation, status);
return;
}
/* positive infinity */
_settriple(result, MPD_POS, 0, mpd_etiny(ctx));
*status |= MPD_Clamped;
return;
}
if (mpd_iszero(a)) {
mpd_setspecial(result, mpd_sign(a), MPD_INF);
*status |= MPD_Division_by_zero;
return;
}
if (mpd_isnegative(a)) {
mpd_seterror(result, MPD_Invalid_operation, status);
return;
}
workctx = *ctx;
workctx.prec += 2;
workctx.round = MPD_ROUND_HALF_EVEN;
_mpd_qinvroot(result, a, &workctx, status);
mpd_qfinalize(result, ctx, status);
}
/* END LIBMPDEC_ONLY */
/* Algorithm from decimal.py */
void
mpd_qsqrt(mpd_t *result, const mpd_t *a, const mpd_context_t *ctx,
uint32_t *status)
{
mpd_context_t maxcontext;
MPD_NEW_STATIC(c,0,0,0,0);
MPD_NEW_STATIC(q,0,0,0,0);
MPD_NEW_STATIC(r,0,0,0,0);
MPD_NEW_CONST(two,0,0,1,1,1,2);
mpd_ssize_t prec, ideal_exp;
mpd_ssize_t l, shift;
int exact = 0;
ideal_exp = (a->exp - (a->exp & 1)) / 2;
if (mpd_isspecial(a)) {
if (mpd_qcheck_nan(result, a, ctx, status)) {
return;
}
if (mpd_isnegative(a)) {
mpd_seterror(result, MPD_Invalid_operation, status);
return;
}
mpd_setspecial(result, MPD_POS, MPD_INF);
return;
}
if (mpd_iszero(a)) {
_settriple(result, mpd_sign(a), 0, ideal_exp);
mpd_qfinalize(result, ctx, status);
return;
}
if (mpd_isnegative(a)) {
mpd_seterror(result, MPD_Invalid_operation, status);
return;
}
mpd_maxcontext(&maxcontext);
prec = ctx->prec + 1;
if (!mpd_qcopy(&c, a, status)) {
goto malloc_error;
}
c.exp = 0;
if (a->exp & 1) {
if (!mpd_qshiftl(&c, &c, 1, status)) {
goto malloc_error;
}
l = (a->digits >> 1) + 1;
}
else {
l = (a->digits + 1) >> 1;
}
shift = prec - l;
if (shift >= 0) {
if (!mpd_qshiftl(&c, &c, 2*shift, status)) {
goto malloc_error;
}
exact = 1;
}
else {
exact = !mpd_qshiftr_inplace(&c, -2*shift);
}
ideal_exp -= shift;
/* find result = floor(sqrt(c)) using Newton's method */
if (!mpd_qshiftl(result, &one, prec, status)) {
goto malloc_error;
}
while (1) {
_mpd_qdivmod(&q, &r, &c, result, &maxcontext, &maxcontext.status);
if (mpd_isspecial(result) || mpd_isspecial(&q)) {
mpd_seterror(result, maxcontext.status&MPD_Errors, status);
goto out;
}
if (_mpd_cmp(result, &q) <= 0) {
break;
}
_mpd_qadd_exact(result, result, &q, &maxcontext, &maxcontext.status);
if (mpd_isspecial(result)) {
mpd_seterror(result, maxcontext.status&MPD_Errors, status);
goto out;
}
_mpd_qdivmod(result, &r, result, &two, &maxcontext, &maxcontext.status);
}
if (exact) {
_mpd_qmul_exact(&r, result, result, &maxcontext, &maxcontext.status);
if (mpd_isspecial(&r)) {
mpd_seterror(result, maxcontext.status&MPD_Errors, status);
goto out;
}
exact = (_mpd_cmp(&r, &c) == 0);
}
if (exact) {
if (shift >= 0) {
mpd_qshiftr_inplace(result, shift);
}
else {
if (!mpd_qshiftl(result, result, -shift, status)) {
goto malloc_error;
}
}
ideal_exp += shift;
}
else {
int lsd = (int)mpd_lsd(result->data[0]);
if (lsd == 0 || lsd == 5) {
result->data[0] += 1;
}
}
result->exp = ideal_exp;
out:
mpd_del(&c);
mpd_del(&q);
mpd_del(&r);
maxcontext = *ctx;
maxcontext.round = MPD_ROUND_HALF_EVEN;
mpd_qfinalize(result, &maxcontext, status);
return;
malloc_error:
mpd_seterror(result, MPD_Malloc_error, status);
goto out;
}
/******************************************************************************/
/* Base conversions */
/******************************************************************************/
/* Space needed to represent an integer mpd_t in base 'base'. */
size_t
mpd_sizeinbase(const mpd_t *a, uint32_t base)
{
double x;
size_t digits;
assert(mpd_isinteger(a));
assert(base >= 2);
if (mpd_iszero(a)) {
return 1;
}
digits = a->digits+a->exp;
assert(digits > 0);
/* ceil(2711437152599294 / log10(2)) + 4 == 2**53 */
if (digits > 2711437152599294ULL) {
return SIZE_MAX;
}
x = (double)digits / log10(base);
return (x > (SIZE_MAX>>1)+1) ? SIZE_MAX : (size_t)x + 1;
}
/* Space needed to import a base 'base' integer of length 'srclen'. */
static mpd_ssize_t
_mpd_importsize(size_t srclen, uint32_t base)
{
double x;
assert(srclen > 0);
assert(base >= 2);
#if SIZE_MAX == UINT64_MAX
if (srclen > (1ULL<<53)) {
return MPD_SSIZE_MAX;
}
#endif
x = (double)srclen * (log10(base)/MPD_RDIGITS);
return (x >= (double)(MPD_MAXIMPORT/2)) ? MPD_SSIZE_MAX : (mpd_ssize_t)x + 1;
}
static uint8_t
mpd_resize_u16(uint16_t **w, size_t nmemb)
{
uint8_t err = 0;
*w = mpd_realloc(*w, nmemb, sizeof **w, &err);
return !err;
}
static uint8_t
mpd_resize_u32(uint32_t **w, size_t nmemb)
{
uint8_t err = 0;
*w = mpd_realloc(*w, nmemb, sizeof **w, &err);
return !err;
}
static size_t
_baseconv_to_u16(uint16_t **w, size_t wlen, mpd_uint_t wbase,
mpd_uint_t *u, mpd_ssize_t ulen)
{
size_t n = 0;
assert(wlen > 0 && ulen > 0);
assert(wbase <= (1U<<16));
do {
if (n >= wlen) {
if (!mpd_resize_u16(w, n+1)) {
return SIZE_MAX;
}
wlen = n+1;
}
(*w)[n++] = (uint16_t)_mpd_shortdiv(u, u, ulen, wbase);
/* ulen is at least 1. u[ulen-1] can only be zero if ulen == 1. */
ulen = _mpd_real_size(u, ulen);
} while (u[ulen-1] != 0);
return n;
}
static size_t
_coeff_from_u16(mpd_t *w, mpd_ssize_t wlen,
const mpd_uint_t *u, size_t ulen, uint32_t ubase,
uint32_t *status)
{
mpd_ssize_t n = 0;
mpd_uint_t carry;
assert(wlen > 0 && ulen > 0);
assert(ubase <= (1U<<16));
w->data[n++] = u[--ulen];
while (--ulen != SIZE_MAX) {
carry = _mpd_shortmul_c(w->data, w->data, n, ubase);
if (carry) {
if (n >= wlen) {
if (!mpd_qresize(w, n+1, status)) {
return SIZE_MAX;
}
wlen = n+1;
}
w->data[n++] = carry;
}
carry = _mpd_shortadd(w->data, n, u[ulen]);
if (carry) {
if (n >= wlen) {
if (!mpd_qresize(w, n+1, status)) {
return SIZE_MAX;
}
wlen = n+1;
}
w->data[n++] = carry;
}
}
return n;
}
/* target base wbase < source base ubase */
static size_t
_baseconv_to_smaller(uint32_t **w, size_t wlen, uint32_t wbase,
mpd_uint_t *u, mpd_ssize_t ulen, mpd_uint_t ubase)
{
size_t n = 0;
assert(wlen > 0 && ulen > 0);
assert(wbase < ubase);
do {
if (n >= wlen) {
if (!mpd_resize_u32(w, n+1)) {
return SIZE_MAX;
}
wlen = n+1;
}
(*w)[n++] = (uint32_t)_mpd_shortdiv_b(u, u, ulen, wbase, ubase);
/* ulen is at least 1. u[ulen-1] can only be zero if ulen == 1. */
ulen = _mpd_real_size(u, ulen);
} while (u[ulen-1] != 0);
return n;
}
/* target base 'wbase' > source base 'ubase' */
static size_t
_coeff_from_smaller_base(mpd_t *w, mpd_ssize_t wlen, mpd_uint_t wbase,
const uint32_t *u, size_t ulen, mpd_uint_t ubase,
uint32_t *status)
{
mpd_ssize_t n = 0;
mpd_uint_t carry;
assert(wlen > 0 && ulen > 0);
assert(wbase > ubase);
w->data[n++] = u[--ulen];
while (--ulen != SIZE_MAX) {
carry = _mpd_shortmul_b(w->data, w->data, n, ubase, wbase);
if (carry) {
if (n >= wlen) {
if (!mpd_qresize(w, n+1, status)) {
return SIZE_MAX;
}
wlen = n+1;
}
w->data[n++] = carry;
}
carry = _mpd_shortadd_b(w->data, n, u[ulen], wbase);
if (carry) {
if (n >= wlen) {
if (!mpd_qresize(w, n+1, status)) {
return SIZE_MAX;
}
wlen = n+1;
}
w->data[n++] = carry;
}
}
return n;
}
/*
* Convert an integer mpd_t to a multiprecision integer with base <= 2**16.
* The least significant word of the result is (*rdata)[0].
*
* If rdata is NULL, space is allocated by the function and rlen is irrelevant.
* In case of an error any allocated storage is freed and rdata is set back to
* NULL.
*
* If rdata is non-NULL, it MUST be allocated by one of libmpdec's allocation
* functions and rlen MUST be correct. If necessary, the function will resize
* rdata. In case of an error the caller must free rdata.
*
* Return value: In case of success, the exact length of rdata, SIZE_MAX
* otherwise.
*/
size_t
mpd_qexport_u16(uint16_t **rdata, size_t rlen, uint32_t rbase,
const mpd_t *src, uint32_t *status)
{
MPD_NEW_STATIC(tsrc,0,0,0,0);
int alloc = 0; /* rdata == NULL */
size_t n;
assert(rbase <= (1U<<16));
if (mpd_isspecial(src) || !_mpd_isint(src)) {
*status |= MPD_Invalid_operation;
return SIZE_MAX;
}
if (*rdata == NULL) {
rlen = mpd_sizeinbase(src, rbase);
if (rlen == SIZE_MAX) {
*status |= MPD_Invalid_operation;
return SIZE_MAX;
}
*rdata = mpd_alloc(rlen, sizeof **rdata);
if (*rdata == NULL) {
goto malloc_error;
}
alloc = 1;
}
if (mpd_iszero(src)) {
**rdata = 0;
return 1;
}
if (src->exp >= 0) {
if (!mpd_qshiftl(&tsrc, src, src->exp, status)) {
goto malloc_error;
}
}
else {
if (mpd_qshiftr(&tsrc, src, -src->exp, status) == MPD_UINT_MAX) {
goto malloc_error;
}
}
n = _baseconv_to_u16(rdata, rlen, rbase, tsrc.data, tsrc.len);
if (n == SIZE_MAX) {
goto malloc_error;
}
out:
mpd_del(&tsrc);
return n;
malloc_error:
if (alloc) {
mpd_free(*rdata);
*rdata = NULL;
}
n = SIZE_MAX;
*status |= MPD_Malloc_error;
goto out;
}
/*
* Convert an integer mpd_t to a multiprecision integer with base<=UINT32_MAX.
* The least significant word of the result is (*rdata)[0].
*
* If rdata is NULL, space is allocated by the function and rlen is irrelevant.
* In case of an error any allocated storage is freed and rdata is set back to
* NULL.
*
* If rdata is non-NULL, it MUST be allocated by one of libmpdec's allocation
* functions and rlen MUST be correct. If necessary, the function will resize
* rdata. In case of an error the caller must free rdata.
*
* Return value: In case of success, the exact length of rdata, SIZE_MAX
* otherwise.
*/
size_t
mpd_qexport_u32(uint32_t **rdata, size_t rlen, uint32_t rbase,
const mpd_t *src, uint32_t *status)
{
MPD_NEW_STATIC(tsrc,0,0,0,0);
int alloc = 0; /* rdata == NULL */
size_t n;
if (mpd_isspecial(src) || !_mpd_isint(src)) {
*status |= MPD_Invalid_operation;
return SIZE_MAX;
}
if (*rdata == NULL) {
rlen = mpd_sizeinbase(src, rbase);
if (rlen == SIZE_MAX) {
*status |= MPD_Invalid_operation;
return SIZE_MAX;
}
*rdata = mpd_alloc(rlen, sizeof **rdata);
if (*rdata == NULL) {
goto malloc_error;
}
alloc = 1;
}
if (mpd_iszero(src)) {
**rdata = 0;
return 1;
}
if (src->exp >= 0) {
if (!mpd_qshiftl(&tsrc, src, src->exp, status)) {
goto malloc_error;
}
}
else {
if (mpd_qshiftr(&tsrc, src, -src->exp, status) == MPD_UINT_MAX) {
goto malloc_error;
}
}
n = _baseconv_to_smaller(rdata, rlen, rbase,
tsrc.data, tsrc.len, MPD_RADIX);
if (n == SIZE_MAX) {
goto malloc_error;
}
out:
mpd_del(&tsrc);
return n;
malloc_error:
if (alloc) {
mpd_free(*rdata);
*rdata = NULL;
}
n = SIZE_MAX;
*status |= MPD_Malloc_error;
goto out;
}
/*
* Converts a multiprecision integer with base <= UINT16_MAX+1 to an mpd_t.
* The least significant word of the source is srcdata[0].
*/
void
mpd_qimport_u16(mpd_t *result,
const uint16_t *srcdata, size_t srclen,
uint8_t srcsign, uint32_t srcbase,
const mpd_context_t *ctx, uint32_t *status)
{
mpd_uint_t *usrc; /* uint16_t src copied to an mpd_uint_t array */
mpd_ssize_t rlen; /* length of the result */
size_t n;
assert(srclen > 0);
assert(srcbase <= (1U<<16));
rlen = _mpd_importsize(srclen, srcbase);
if (rlen == MPD_SSIZE_MAX) {
mpd_seterror(result, MPD_Invalid_operation, status);
return;
}
usrc = mpd_alloc((mpd_size_t)srclen, sizeof *usrc);
if (usrc == NULL) {
mpd_seterror(result, MPD_Malloc_error, status);
return;
}
for (n = 0; n < srclen; n++) {
usrc[n] = srcdata[n];
}
if (!mpd_qresize(result, rlen, status)) {
goto finish;
}
n = _coeff_from_u16(result, rlen, usrc, srclen, srcbase, status);
if (n == SIZE_MAX) {
goto finish;
}
mpd_set_flags(result, srcsign);
result->exp = 0;
result->len = n;
mpd_setdigits(result);
mpd_qresize(result, result->len, status);
mpd_qfinalize(result, ctx, status);
finish:
mpd_free(usrc);
}
/*
* Converts a multiprecision integer with base <= UINT32_MAX to an mpd_t.
* The least significant word of the source is srcdata[0].
*/
void
mpd_qimport_u32(mpd_t *result,
const uint32_t *srcdata, size_t srclen,
uint8_t srcsign, uint32_t srcbase,
const mpd_context_t *ctx, uint32_t *status)
{
mpd_ssize_t rlen; /* length of the result */
size_t n;
assert(srclen > 0);
rlen = _mpd_importsize(srclen, srcbase);
if (rlen == MPD_SSIZE_MAX) {
mpd_seterror(result, MPD_Invalid_operation, status);
return;
}
if (!mpd_qresize(result, rlen, status)) {
return;
}
n = _coeff_from_smaller_base(result, rlen, MPD_RADIX,
srcdata, srclen, srcbase,
status);
if (n == SIZE_MAX) {
return;
}
mpd_set_flags(result, srcsign);
result->exp = 0;
result->len = n;
mpd_setdigits(result);
mpd_qresize(result, result->len, status);
mpd_qfinalize(result, ctx, status);
}
| 219,025 | 7,364 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Modules/_decimal/libmpdec/typearith.h | #ifndef TYPEARITH_H
#define TYPEARITH_H
#include "libc/assert.h"
#include "third_party/python/Modules/_decimal/libmpdec/mpdecimal.h"
/* clang-format off */
#if defined(__GNUC__) && defined(__x86_64__) && !defined(__STRICT_ANSI__)
static inline void
_mpd_mul_words(mpd_uint_t *hi, mpd_uint_t *lo, mpd_uint_t a, mpd_uint_t b)
{
mpd_uint_t h, l;
asm ( "mulq %3\n\t"
: "=d" (h), "=a" (l)
: "%a" (a), "rm" (b)
: "cc"
);
*hi = h;
*lo = l;
}
static inline void
_mpd_div_words(mpd_uint_t *q, mpd_uint_t *r, mpd_uint_t hi, mpd_uint_t lo,
mpd_uint_t d)
{
mpd_uint_t qq, rr;
asm ( "divq %4\n\t"
: "=a" (qq), "=d" (rr)
: "a" (lo), "d" (hi), "rm" (d)
: "cc"
);
*q = qq;
*r = rr;
}
#else
static inline void
_mpd_mul_words(mpd_uint_t *hi, mpd_uint_t *lo, mpd_uint_t a, mpd_uint_t b)
{
uint32_t w[4], carry;
uint32_t ah, al, bh, bl;
uint64_t hl;
ah = (uint32_t)(a>>32); al = (uint32_t)a;
bh = (uint32_t)(b>>32); bl = (uint32_t)b;
hl = (uint64_t)al * bl;
w[0] = (uint32_t)hl;
carry = (uint32_t)(hl>>32);
hl = (uint64_t)ah * bl + carry;
w[1] = (uint32_t)hl;
w[2] = (uint32_t)(hl>>32);
hl = (uint64_t)al * bh + w[1];
w[1] = (uint32_t)hl;
carry = (uint32_t)(hl>>32);
hl = ((uint64_t)ah * bh + w[2]) + carry;
w[2] = (uint32_t)hl;
w[3] = (uint32_t)(hl>>32);
*hi = ((uint64_t)w[3]<<32) + w[2];
*lo = ((uint64_t)w[1]<<32) + w[0];
}
/*
* By Henry S. Warren: http://www.hackersdelight.org/HDcode/divlu.c.txt
* http://www.hackersdelight.org/permissions.htm:
* "You are free to use, copy, and distribute any of the code on this web
* site, whether modified by you or not. You need not give attribution."
*
* Slightly modified, comments are mine.
*/
static inline int
nlz(uint64_t x)
{
int n;
if (x == 0) return(64);
n = 0;
if (x <= 0x00000000FFFFFFFF) {n = n +32; x = x <<32;}
if (x <= 0x0000FFFFFFFFFFFF) {n = n +16; x = x <<16;}
if (x <= 0x00FFFFFFFFFFFFFF) {n = n + 8; x = x << 8;}
if (x <= 0x0FFFFFFFFFFFFFFF) {n = n + 4; x = x << 4;}
if (x <= 0x3FFFFFFFFFFFFFFF) {n = n + 2; x = x << 2;}
if (x <= 0x7FFFFFFFFFFFFFFF) {n = n + 1;}
return n;
}
static inline void
_mpd_div_words(mpd_uint_t *q, mpd_uint_t *r, mpd_uint_t u1, mpd_uint_t u0,
mpd_uint_t v)
{
const mpd_uint_t b = 4294967296;
mpd_uint_t un1, un0,
vn1, vn0,
q1, q0,
un32, un21, un10,
rhat, t;
int s;
assert(u1 < v);
s = nlz(v);
v = v << s;
vn1 = v >> 32;
vn0 = v & 0xFFFFFFFF;
t = (s == 0) ? 0 : u0 >> (64 - s);
un32 = (u1 << s) | t;
un10 = u0 << s;
un1 = un10 >> 32;
un0 = un10 & 0xFFFFFFFF;
q1 = un32 / vn1;
rhat = un32 - q1*vn1;
again1:
if (q1 >= b || q1*vn0 > b*rhat + un1) {
q1 = q1 - 1;
rhat = rhat + vn1;
if (rhat < b) goto again1;
}
/*
* Before again1 we had:
* (1) q1*vn1 + rhat = un32
* (2) q1*vn1*b + rhat*b + un1 = un32*b + un1
*
* The statements inside the if-clause do not change the value
* of the left-hand side of (2), and the loop is only exited
* if q1*vn0 <= rhat*b + un1, so:
*
* (3) q1*vn1*b + q1*vn0 <= un32*b + un1
* (4) q1*v <= un32*b + un1
* (5) 0 <= un32*b + un1 - q1*v
*
* By (5) we are certain that the possible add-back step from
* Knuth's algorithm D is never required.
*
* Since the final quotient is less than 2**64, the following
* must be true:
*
* (6) un32*b + un1 - q1*v <= UINT64_MAX
*
* This means that in the following line, the high words
* of un32*b and q1*v can be discarded without any effect
* on the result.
*/
un21 = un32*b + un1 - q1*v;
q0 = un21 / vn1;
rhat = un21 - q0*vn1;
again2:
if (q0 >= b || q0*vn0 > b*rhat + un0) {
q0 = q0 - 1;
rhat = rhat + vn1;
if (rhat < b) goto again2;
}
*q = q1*b + q0;
*r = (un21*b + un0 - q0*v) >> s;
}
#endif /* ANSI */
#define DIVMOD(q, r, v, d) *q = v / d; *r = v - *q * d
static inline void
_mpd_divmod_pow10(mpd_uint_t *q, mpd_uint_t *r, mpd_uint_t v, mpd_uint_t exp)
{
assert(exp <= 19);
if (exp <= 9) {
if (exp <= 4) {
switch (exp) {
case 0: *q = v; *r = 0; break;
case 1: DIVMOD(q, r, v, 10UL); break;
case 2: DIVMOD(q, r, v, 100UL); break;
case 3: DIVMOD(q, r, v, 1000UL); break;
case 4: DIVMOD(q, r, v, 10000UL); break;
}
}
else {
switch (exp) {
case 5: DIVMOD(q, r, v, 100000UL); break;
case 6: DIVMOD(q, r, v, 1000000UL); break;
case 7: DIVMOD(q, r, v, 10000000UL); break;
case 8: DIVMOD(q, r, v, 100000000UL); break;
case 9: DIVMOD(q, r, v, 1000000000UL); break;
}
}
}
else {
if (exp <= 14) {
switch (exp) {
case 10: DIVMOD(q, r, v, 10000000000ULL); break;
case 11: DIVMOD(q, r, v, 100000000000ULL); break;
case 12: DIVMOD(q, r, v, 1000000000000ULL); break;
case 13: DIVMOD(q, r, v, 10000000000000ULL); break;
case 14: DIVMOD(q, r, v, 100000000000000ULL); break;
}
}
else {
switch (exp) {
case 15: DIVMOD(q, r, v, 1000000000000000ULL); break;
case 16: DIVMOD(q, r, v, 10000000000000000ULL); break;
case 17: DIVMOD(q, r, v, 100000000000000000ULL); break;
case 18: DIVMOD(q, r, v, 1000000000000000000ULL); break;
case 19: DIVMOD(q, r, v, 10000000000000000000ULL); break;
default: unreachable;
}
}
}
}
static inline void
_mpd_div_word(mpd_uint_t *q, mpd_uint_t *r, mpd_uint_t v, mpd_uint_t d)
{
*q = v / d;
*r = v - *q * d;
}
static inline void
_mpd_idiv_word(mpd_ssize_t *q, mpd_ssize_t *r, mpd_ssize_t v, mpd_ssize_t d)
{
*q = v / d;
*r = v - *q * d;
}
/** ------------------------------------------------------------
** Arithmetic with overflow checking
** ------------------------------------------------------------
*/
/* The following macros do call exit() in case of an overflow.
If the library is used correctly (i.e. with valid context
parameters), such overflows cannot occur. The macros are used
as sanity checks in a couple of strategic places and should
be viewed as a handwritten version of gcc's -ftrapv option. */
static inline mpd_size_t
add_size_t(mpd_size_t a, mpd_size_t b)
{
if (a > MPD_SIZE_MAX - b) {
mpd_err_fatal("add_size_t(): overflow: check the context"); /* GCOV_NOT_REACHED */
}
return a + b;
}
static inline mpd_size_t
sub_size_t(mpd_size_t a, mpd_size_t b)
{
if (b > a) {
mpd_err_fatal("sub_size_t(): overflow: check the context"); /* GCOV_NOT_REACHED */
}
return a - b;
}
#if MPD_SIZE_MAX != MPD_UINT_MAX
#error "adapt mul_size_t() and mulmod_size_t()"
#endif
static inline mpd_size_t
mul_size_t(mpd_size_t a, mpd_size_t b)
{
mpd_uint_t hi, lo;
_mpd_mul_words(&hi, &lo, (mpd_uint_t)a, (mpd_uint_t)b);
if (hi) {
mpd_err_fatal("mul_size_t(): overflow: check the context"); /* GCOV_NOT_REACHED */
}
return lo;
}
static inline mpd_size_t
add_size_t_overflow(mpd_size_t a, mpd_size_t b, mpd_size_t *overflow)
{
mpd_size_t ret;
*overflow = 0;
ret = a + b;
if (ret < a) *overflow = 1;
return ret;
}
static inline mpd_size_t
mul_size_t_overflow(mpd_size_t a, mpd_size_t b, mpd_size_t *overflow)
{
mpd_uint_t lo;
_mpd_mul_words((mpd_uint_t *)overflow, &lo, (mpd_uint_t)a,
(mpd_uint_t)b);
return lo;
}
static inline mpd_ssize_t
mod_mpd_ssize_t(mpd_ssize_t a, mpd_ssize_t m)
{
mpd_ssize_t r = a % m;
return (r < 0) ? r + m : r;
}
static inline mpd_size_t
mulmod_size_t(mpd_size_t a, mpd_size_t b, mpd_size_t m)
{
mpd_uint_t hi, lo;
mpd_uint_t q, r;
_mpd_mul_words(&hi, &lo, (mpd_uint_t)a, (mpd_uint_t)b);
_mpd_div_words(&q, &r, hi, lo, (mpd_uint_t)m);
return r;
}
#endif /* TYPEARITH_H */
| 8,347 | 298 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Modules/_decimal/libmpdec/bits.h | #ifndef BITS_H
#define BITS_H
#include "third_party/python/Modules/_decimal/libmpdec/mpdecimal.h"
/* clang-format off */
/*
* Check if ð is a power of 2.
*/
static inline int
ispower2(mpd_size_t n)
{
return n != 0 && (n & (n-1)) == 0;
}
/*
* Returns most significant bit position of ð.
* Assumptions: ð â 0
*/
static inline int
mpd_bsr(mpd_size_t n)
{
#if defined(__GNUC__) && !defined(__STRICT_ANSI__)
return __builtin_clzll(n) ^ (sizeof(long long) * CHAR_BIT - 1);
#else
int pos = 0;
mpd_size_t tmp;
tmp = n >> 32; if (tmp != 0) { n = tmp; pos += 32; }
tmp = n >> 16; if (tmp != 0) { n = tmp; pos += 16; }
tmp = n >> 8; if (tmp != 0) { n = tmp; pos += 8; }
tmp = n >> 4; if (tmp != 0) { n = tmp; pos += 4; }
tmp = n >> 2; if (tmp != 0) { n = tmp; pos += 2; }
tmp = n >> 1; if (tmp != 0) { n = tmp; pos += 1; }
return pos + (int)n - 1;
#endif
}
/*
* Return the least significant bit position of n from 0 to 31 (63).
* Assumptions: n != 0.
*/
static inline int
mpd_bsf(mpd_size_t n)
{
#if defined(__GNUC__) && !defined(__STRICT_ANSI__)
return __builtin_ctzll(n);
#else
int pos;
pos = 63;
if (n & 0x00000000FFFFFFFFULL) { pos -= 32; } else { n >>= 32; }
if (n & 0x000000000000FFFFULL) { pos -= 16; } else { n >>= 16; }
if (n & 0x00000000000000FFULL) { pos -= 8; } else { n >>= 8; }
if (n & 0x000000000000000FULL) { pos -= 4; } else { n >>= 4; }
if (n & 0x0000000000000003ULL) { pos -= 2; } else { n >>= 2; }
if (n & 0x0000000000000001ULL) { pos -= 1; }
return pos;
#endif
}
#endif /* BITS_H */
| 1,615 | 60 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Modules/_decimal/libmpdec/fnt.h | #ifndef FNT_H
#define FNT_H
#include "third_party/python/Modules/_decimal/libmpdec/mpdecimal.h"
/* Internal header file: all symbols have local scope in the DSO */
int std_fnt(mpd_uint_t[], mpd_size_t, int);
int std_inv_fnt(mpd_uint_t[], mpd_size_t, int);
#endif
| 266 | 11 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Modules/_decimal/libmpdec/umodarith.h | #ifndef UMODARITH_H
#define UMODARITH_H
#include "third_party/python/Modules/_decimal/libmpdec/constants.h"
#include "third_party/python/Modules/_decimal/libmpdec/mpdecimal.h"
#include "third_party/python/Modules/_decimal/libmpdec/typearith.h"
/* clang-format off */
/* Bignum: Low level routines for unsigned modular arithmetic. These are
used in the fast convolution functions for very large coefficients. */
/*
* Restrictions: a < m and b < m
* ACL2 proof: umodarith.lisp: addmod-correct
*/
static inline mpd_uint_t
addmod(mpd_uint_t a, mpd_uint_t b, mpd_uint_t m)
{
mpd_uint_t s;
s = a + b;
s = (s < a) ? s - m : s;
s = (s >= m) ? s - m : s;
return s;
}
/*
* Restrictions: a < m and b < m
* ACL2 proof: umodarith.lisp: submod-2-correct
*/
static inline mpd_uint_t
submod(mpd_uint_t a, mpd_uint_t b, mpd_uint_t m)
{
mpd_uint_t d;
d = a - b;
d = (a < b) ? d + m : d;
return d;
}
/*
* Restrictions: a < 2m and b < 2m
* ACL2 proof: umodarith.lisp: section ext-submod
*/
static inline mpd_uint_t
ext_submod(mpd_uint_t a, mpd_uint_t b, mpd_uint_t m)
{
mpd_uint_t d;
a = (a >= m) ? a - m : a;
b = (b >= m) ? b - m : b;
d = a - b;
d = (a < b) ? d + m : d;
return d;
}
/*
* Reduce double word modulo m.
* Restrictions: m != 0
* ACL2 proof: umodarith.lisp: section dw-reduce
*/
static inline mpd_uint_t
dw_reduce(mpd_uint_t hi, mpd_uint_t lo, mpd_uint_t m)
{
mpd_uint_t r1, r2, w;
_mpd_div_word(&w, &r1, hi, m);
_mpd_div_words(&w, &r2, r1, lo, m);
return r2;
}
/*
* Subtract double word from a.
* Restrictions: a < m
* ACL2 proof: umodarith.lisp: section dw-submod
*/
static inline mpd_uint_t
dw_submod(mpd_uint_t a, mpd_uint_t hi, mpd_uint_t lo, mpd_uint_t m)
{
mpd_uint_t d, r;
r = dw_reduce(hi, lo, m);
d = a - r;
d = (a < r) ? d + m : d;
return d;
}
/**
* Calculates (a à b) % ð where ð is special
*
* In the whole comment, "â©" stands for "is congruent with".
*
* Result of a à b in terms of high/low words:
*
* (1) hi à 2â¶â´ + lo = a à b
*
* Special primes:
*
* (2) ð = 2â¶â´ - z + 1, where z = 2â¿
*
* i.e. 0xfffffffffffffc01
* 0xfffffffffffff001
* 0xffffffffff000001
* 0xffffffff00000001
* 0xfffffffc00000001
* 0xffffff0000000001
* 0xffffff0000000001
*
* Single step modular reduction:
*
* (3) R(hi, lo) = hi à z - hi + lo
*
*
* Strategy
* --------
*
* a) Set (hi, lo) to the result of a à b.
*
* b) Set (hiâ², loâ²) to the result of R(hi, lo).
*
* c) Repeat step b) until 0 ⤠hiâ² Ã 2â¶â´ + loâ² < ð¸Ãð.
*
* d) If the result is less than ð, return loâ². Otherwise return loâ² - ð.
*
*
* The reduction step b) preserves congruence
* ------------------------------------------
*
* hi à 2â¶â´ + lo â© hi à z - hi + lo (mod ð)
*
* Proof:
* ~~~~~~
*
* hi à 2â¶â´ + lo = (2â¶â´ - z + 1) à hi + z à hi - hi + lo
*
* = ð à hi + z à hi - hi + lo
*
* â© z à hi - hi + lo (mod ð)
*
*
* Maximum numbers of step b)
* --------------------------
*
* To avoid unnecessary formalism, define:
*
* def R(hi, lo, z):
* return divmod(hi * z - hi + lo, 2**64)
*
* For simplicity, assume hi=2â¶â´-1, lo=2â¶â´-1 after the
* initial multiplication a à b. This is of course impossible
* but certainly covers all cases.
*
* Then, for p1:
*
* z = 2³²
* hi = 2â¶â´-1
* lo = 2â¶â´-1
* p1 = 2â¶â´ - z + 1
* hi, lo = R(hi, lo, z) # First reduction
* hi, lo = R(hi, lo, z) # Second reduction
* hi à 2â¶â´ + lo < 2 à p1 # True
*
* For p2:
*
* z = 2³â´
* hi = 2â¶â´-1
* lo = 2â¶â´-1
* p2 = 2â¶â´ - z + 1
* hi, lo = R(hi, lo, z) # First reduction
* hi, lo = R(hi, lo, z) # Second reduction
* hi, lo = R(hi, lo, z) # Third reduction
* hi à 2â¶â´ + lo < 2 à p2 # True
*
* For p3:
*
* z = 2â´â°
* hi = 2â¶â´-1
* lo = 2â¶â´-1
* p3 = 2â¶â´ - z + 1
* hi, lo = R(hi, lo, z) # First reduction
* hi, lo = R(hi, lo, z) # Second reduction
* hi, lo = R(hi, lo, z) # Third reduction
* hi à 2â¶â´ + lo < 2 à p3 # True
*
* Step d) preserves congruence and yields a result < ð
* ----------------------------------------------------
*
* Case hi = 0:
*
* Case lo < ð: trivial.
*
* Case lo ⥠ð:
*
* lo â© lo - ð (mod ð) # result is congruent
*
* ð ⤠lo < ð¸Ãð â 0 ⤠lo - ð < ð # result is in the correct range
*
* Case hi = 1:
*
* ð < 2â¶â´ Î 2â¶â´ + lo < ð¸Ãð â lo < ð # lo is always less than ð
*
* 2â¶â´ + lo â© 2â¶â´ + (lo - ð) (mod ð) # result is congruent
*
* = lo - ð # exactly the same value as the previous RHS
* # in uint64_t arithmetic.
*
* ð < 2â¶â´ + lo < ð¸Ãð â 0 < 2â¶â´ + (lo - ð) < ð # correct range
*
*
* [1] http://www.apfloat.org/apfloat/2.40/apfloat.pdf
*/
static inline mpd_uint_t
x64_mulmod(mpd_uint_t a, mpd_uint_t b, mpd_uint_t m)
{
mpd_uint_t hi, lo, x, y;
_mpd_mul_words(&hi, &lo, a, b);
if (m & (1ULL<<32)) { /* P1 */
/* first reduction */
x = y = hi;
hi >>= 32;
x = lo - x;
if (x > lo) hi--;
y <<= 32;
lo = y + x;
if (lo < y) hi++;
/* second reduction */
x = y = hi;
hi >>= 32;
x = lo - x;
if (x > lo) hi--;
y <<= 32;
lo = y + x;
if (lo < y) hi++;
return hi || lo >= m ? lo - m : lo;
}
else if (m & (1ULL<<34)) { /* P2 */
/* first reduction */
x = y = hi;
hi >>= 30;
x = lo - x;
if (x > lo) hi--;
y <<= 34;
lo = y + x;
if (lo < y) hi++;
/* second reduction */
x = y = hi;
hi >>= 30;
x = lo - x;
if (x > lo) hi--;
y <<= 34;
lo = y + x;
if (lo < y) hi++;
/* third reduction */
x = y = hi;
hi >>= 30;
x = lo - x;
if (x > lo) hi--;
y <<= 34;
lo = y + x;
if (lo < y) hi++;
return hi || lo >= m ? lo - m : lo;
}
else { /* P3 */
/* first reduction */
x = y = hi;
hi >>= 24;
x = lo - x;
if (x > lo) hi--;
y <<= 40;
lo = y + x;
if (lo < y) hi++;
/* second reduction */
x = y = hi;
hi >>= 24;
x = lo - x;
if (x > lo) hi--;
y <<= 40;
lo = y + x;
if (lo < y) hi++;
/* third reduction */
x = y = hi;
hi >>= 24;
x = lo - x;
if (x > lo) hi--;
y <<= 40;
lo = y + x;
if (lo < y) hi++;
return hi || lo >= m ? lo - m : lo;
}
}
static inline void
x64_mulmod2c(mpd_uint_t *a, mpd_uint_t *b, mpd_uint_t w, mpd_uint_t m)
{
*a = x64_mulmod(*a, w, m);
*b = x64_mulmod(*b, w, m);
}
static inline void
x64_mulmod2(mpd_uint_t *a0, mpd_uint_t b0, mpd_uint_t *a1, mpd_uint_t b1,
mpd_uint_t m)
{
*a0 = x64_mulmod(*a0, b0, m);
*a1 = x64_mulmod(*a1, b1, m);
}
static inline mpd_uint_t
x64_powmod(mpd_uint_t base, mpd_uint_t exp, mpd_uint_t umod)
{
mpd_uint_t r = 1;
while (exp > 0) {
if (exp & 1)
r = x64_mulmod(r, base, umod);
base = x64_mulmod(base, base, umod);
exp >>= 1;
}
return r;
}
#endif /* UMODARITH_H */
| 7,771 | 315 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Modules/_decimal/tests/randdec.py | #
# Copyright (c) 2008-2012 Stefan Krah. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# 1. Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS "AS IS" AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
# OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
# OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
# SUCH DAMAGE.
#
# Generate test cases for deccheck.py.
#
# Grammar from http://speleotrove.com/decimal/daconvs.html
#
# sign ::= '+' | '-'
# digit ::= '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' |
# '8' | '9'
# indicator ::= 'e' | 'E'
# digits ::= digit [digit]...
# decimal-part ::= digits '.' [digits] | ['.'] digits
# exponent-part ::= indicator [sign] digits
# infinity ::= 'Infinity' | 'Inf'
# nan ::= 'NaN' [digits] | 'sNaN' [digits]
# numeric-value ::= decimal-part [exponent-part] | infinity
# numeric-string ::= [sign] numeric-value | [sign] nan
#
from random import randrange, sample
from fractions import Fraction
from randfloat import un_randfloat, bin_randfloat, tern_randfloat
def sign():
if randrange(2):
if randrange(2): return '+'
return ''
return '-'
def indicator():
return "eE"[randrange(2)]
def digits(maxprec):
if maxprec == 0: return ''
return str(randrange(10**maxprec))
def dot():
if randrange(2): return '.'
return ''
def decimal_part(maxprec):
if randrange(100) > 60: # integers
return digits(maxprec)
if randrange(2):
intlen = randrange(1, maxprec+1)
fraclen = maxprec-intlen
intpart = digits(intlen)
fracpart = digits(fraclen)
return ''.join((intpart, '.', fracpart))
else:
return ''.join((dot(), digits(maxprec)))
def expdigits(maxexp):
return str(randrange(maxexp))
def exponent_part(maxexp):
return ''.join((indicator(), sign(), expdigits(maxexp)))
def infinity():
if randrange(2): return 'Infinity'
return 'Inf'
def nan():
d = ''
if randrange(2):
d = digits(randrange(99))
if randrange(2):
return ''.join(('NaN', d))
else:
return ''.join(('sNaN', d))
def numeric_value(maxprec, maxexp):
if randrange(100) > 90:
return infinity()
exp_part = ''
if randrange(100) > 60:
exp_part = exponent_part(maxexp)
return ''.join((decimal_part(maxprec), exp_part))
def numeric_string(maxprec, maxexp):
if randrange(100) > 95:
return ''.join((sign(), nan()))
else:
return ''.join((sign(), numeric_value(maxprec, maxexp)))
def randdec(maxprec, maxexp):
return numeric_string(maxprec, maxexp)
def rand_adjexp(maxprec, maxadjexp):
d = digits(maxprec)
maxexp = maxadjexp-len(d)+1
if maxexp == 0: maxexp = 1
exp = str(randrange(maxexp-2*(abs(maxexp)), maxexp))
return ''.join((sign(), d, 'E', exp))
def ndigits(n):
if n < 1: return 0
return randrange(10**(n-1), 10**n)
def randtuple(maxprec, maxexp):
n = randrange(100)
sign = randrange(2)
coeff = ndigits(maxprec)
if n >= 95:
coeff = ()
exp = 'F'
elif n >= 85:
coeff = tuple(map(int, str(ndigits(maxprec))))
exp = "nN"[randrange(2)]
else:
coeff = tuple(map(int, str(ndigits(maxprec))))
exp = randrange(-maxexp, maxexp)
return (sign, coeff, exp)
def from_triple(sign, coeff, exp):
return ''.join((str(sign*coeff), indicator(), str(exp)))
# Close to 10**n
def un_close_to_pow10(prec, maxexp, itr=None):
if itr is None:
lst = range(prec+30)
else:
lst = sample(range(prec+30), itr)
nines = [10**n - 1 for n in lst]
pow10 = [10**n for n in lst]
for coeff in nines:
yield coeff
yield -coeff
yield from_triple(1, coeff, randrange(2*maxexp))
yield from_triple(-1, coeff, randrange(2*maxexp))
for coeff in pow10:
yield coeff
yield -coeff
# Close to 10**n
def bin_close_to_pow10(prec, maxexp, itr=None):
if itr is None:
lst = range(prec+30)
else:
lst = sample(range(prec+30), itr)
nines = [10**n - 1 for n in lst]
pow10 = [10**n for n in lst]
for coeff in nines:
yield coeff, 1
yield -coeff, -1
yield 1, coeff
yield -1, -coeff
yield from_triple(1, coeff, randrange(2*maxexp)), 1
yield from_triple(-1, coeff, randrange(2*maxexp)), -1
yield 1, from_triple(1, coeff, -randrange(2*maxexp))
yield -1, from_triple(-1, coeff, -randrange(2*maxexp))
for coeff in pow10:
yield coeff, -1
yield -coeff, 1
yield 1, -coeff
yield -coeff, 1
# Close to 1:
def close_to_one_greater(prec, emax, emin):
rprec = 10**prec
return ''.join(("1.", '0'*randrange(prec),
str(randrange(rprec))))
def close_to_one_less(prec, emax, emin):
rprec = 10**prec
return ''.join(("0.9", '9'*randrange(prec),
str(randrange(rprec))))
# Close to 0:
def close_to_zero_greater(prec, emax, emin):
rprec = 10**prec
return ''.join(("0.", '0'*randrange(prec),
str(randrange(rprec))))
def close_to_zero_less(prec, emax, emin):
rprec = 10**prec
return ''.join(("-0.", '0'*randrange(prec),
str(randrange(rprec))))
# Close to emax:
def close_to_emax_less(prec, emax, emin):
rprec = 10**prec
return ''.join(("9.", '9'*randrange(prec),
str(randrange(rprec)), "E", str(emax)))
def close_to_emax_greater(prec, emax, emin):
rprec = 10**prec
return ''.join(("1.", '0'*randrange(prec),
str(randrange(rprec)), "E", str(emax+1)))
# Close to emin:
def close_to_emin_greater(prec, emax, emin):
rprec = 10**prec
return ''.join(("1.", '0'*randrange(prec),
str(randrange(rprec)), "E", str(emin)))
def close_to_emin_less(prec, emax, emin):
rprec = 10**prec
return ''.join(("9.", '9'*randrange(prec),
str(randrange(rprec)), "E", str(emin-1)))
# Close to etiny:
def close_to_etiny_greater(prec, emax, emin):
rprec = 10**prec
etiny = emin - (prec - 1)
return ''.join(("1.", '0'*randrange(prec),
str(randrange(rprec)), "E", str(etiny)))
def close_to_etiny_less(prec, emax, emin):
rprec = 10**prec
etiny = emin - (prec - 1)
return ''.join(("9.", '9'*randrange(prec),
str(randrange(rprec)), "E", str(etiny-1)))
def close_to_min_etiny_greater(prec, max_prec, min_emin):
rprec = 10**prec
etiny = min_emin - (max_prec - 1)
return ''.join(("1.", '0'*randrange(prec),
str(randrange(rprec)), "E", str(etiny)))
def close_to_min_etiny_less(prec, max_prec, min_emin):
rprec = 10**prec
etiny = min_emin - (max_prec - 1)
return ''.join(("9.", '9'*randrange(prec),
str(randrange(rprec)), "E", str(etiny-1)))
close_funcs = [
close_to_one_greater, close_to_one_less, close_to_zero_greater,
close_to_zero_less, close_to_emax_less, close_to_emax_greater,
close_to_emin_greater, close_to_emin_less, close_to_etiny_greater,
close_to_etiny_less, close_to_min_etiny_greater, close_to_min_etiny_less
]
def un_close_numbers(prec, emax, emin, itr=None):
if itr is None:
itr = 1000
for _ in range(itr):
for func in close_funcs:
yield func(prec, emax, emin)
def bin_close_numbers(prec, emax, emin, itr=None):
if itr is None:
itr = 1000
for _ in range(itr):
for func1 in close_funcs:
for func2 in close_funcs:
yield func1(prec, emax, emin), func2(prec, emax, emin)
for func in close_funcs:
yield randdec(prec, emax), func(prec, emax, emin)
yield func(prec, emax, emin), randdec(prec, emax)
def tern_close_numbers(prec, emax, emin, itr):
if itr is None:
itr = 1000
for _ in range(itr):
for func1 in close_funcs:
for func2 in close_funcs:
for func3 in close_funcs:
yield (func1(prec, emax, emin), func2(prec, emax, emin),
func3(prec, emax, emin))
for func in close_funcs:
yield (randdec(prec, emax), func(prec, emax, emin),
func(prec, emax, emin))
yield (func(prec, emax, emin), randdec(prec, emax),
func(prec, emax, emin))
yield (func(prec, emax, emin), func(prec, emax, emin),
randdec(prec, emax))
for func in close_funcs:
yield (randdec(prec, emax), randdec(prec, emax),
func(prec, emax, emin))
yield (randdec(prec, emax), func(prec, emax, emin),
randdec(prec, emax))
yield (func(prec, emax, emin), randdec(prec, emax),
randdec(prec, emax))
# If itr == None, test all digit lengths up to prec + 30
def un_incr_digits(prec, maxexp, itr):
if itr is None:
lst = range(prec+30)
else:
lst = sample(range(prec+30), itr)
for m in lst:
yield from_triple(1, ndigits(m), 0)
yield from_triple(-1, ndigits(m), 0)
yield from_triple(1, ndigits(m), randrange(maxexp))
yield from_triple(-1, ndigits(m), randrange(maxexp))
# If itr == None, test all digit lengths up to prec + 30
# Also output decimals im tuple form.
def un_incr_digits_tuple(prec, maxexp, itr):
if itr is None:
lst = range(prec+30)
else:
lst = sample(range(prec+30), itr)
for m in lst:
yield from_triple(1, ndigits(m), 0)
yield from_triple(-1, ndigits(m), 0)
yield from_triple(1, ndigits(m), randrange(maxexp))
yield from_triple(-1, ndigits(m), randrange(maxexp))
# test from tuple
yield (0, tuple(map(int, str(ndigits(m)))), 0)
yield (1, tuple(map(int, str(ndigits(m)))), 0)
yield (0, tuple(map(int, str(ndigits(m)))), randrange(maxexp))
yield (1, tuple(map(int, str(ndigits(m)))), randrange(maxexp))
# If itr == None, test all combinations of digit lengths up to prec + 30
def bin_incr_digits(prec, maxexp, itr):
if itr is None:
lst1 = range(prec+30)
lst2 = range(prec+30)
else:
lst1 = sample(range(prec+30), itr)
lst2 = sample(range(prec+30), itr)
for m in lst1:
x = from_triple(1, ndigits(m), 0)
yield x, x
x = from_triple(-1, ndigits(m), 0)
yield x, x
x = from_triple(1, ndigits(m), randrange(maxexp))
yield x, x
x = from_triple(-1, ndigits(m), randrange(maxexp))
yield x, x
for m in lst1:
for n in lst2:
x = from_triple(1, ndigits(m), 0)
y = from_triple(1, ndigits(n), 0)
yield x, y
x = from_triple(-1, ndigits(m), 0)
y = from_triple(1, ndigits(n), 0)
yield x, y
x = from_triple(1, ndigits(m), 0)
y = from_triple(-1, ndigits(n), 0)
yield x, y
x = from_triple(-1, ndigits(m), 0)
y = from_triple(-1, ndigits(n), 0)
yield x, y
x = from_triple(1, ndigits(m), randrange(maxexp))
y = from_triple(1, ndigits(n), randrange(maxexp))
yield x, y
x = from_triple(-1, ndigits(m), randrange(maxexp))
y = from_triple(1, ndigits(n), randrange(maxexp))
yield x, y
x = from_triple(1, ndigits(m), randrange(maxexp))
y = from_triple(-1, ndigits(n), randrange(maxexp))
yield x, y
x = from_triple(-1, ndigits(m), randrange(maxexp))
y = from_triple(-1, ndigits(n), randrange(maxexp))
yield x, y
def randsign():
return (1, -1)[randrange(2)]
# If itr == None, test all combinations of digit lengths up to prec + 30
def tern_incr_digits(prec, maxexp, itr):
if itr is None:
lst1 = range(prec+30)
lst2 = range(prec+30)
lst3 = range(prec+30)
else:
lst1 = sample(range(prec+30), itr)
lst2 = sample(range(prec+30), itr)
lst3 = sample(range(prec+30), itr)
for m in lst1:
for n in lst2:
for p in lst3:
x = from_triple(randsign(), ndigits(m), 0)
y = from_triple(randsign(), ndigits(n), 0)
z = from_triple(randsign(), ndigits(p), 0)
yield x, y, z
# Tests for the 'logical' functions
def bindigits(prec):
z = 0
for i in range(prec):
z += randrange(2) * 10**i
return z
def logical_un_incr_digits(prec, itr):
if itr is None:
lst = range(prec+30)
else:
lst = sample(range(prec+30), itr)
for m in lst:
yield from_triple(1, bindigits(m), 0)
def logical_bin_incr_digits(prec, itr):
if itr is None:
lst1 = range(prec+30)
lst2 = range(prec+30)
else:
lst1 = sample(range(prec+30), itr)
lst2 = sample(range(prec+30), itr)
for m in lst1:
x = from_triple(1, bindigits(m), 0)
yield x, x
for m in lst1:
for n in lst2:
x = from_triple(1, bindigits(m), 0)
y = from_triple(1, bindigits(n), 0)
yield x, y
def randint():
p = randrange(1, 100)
return ndigits(p) * (1,-1)[randrange(2)]
def randfloat():
p = randrange(1, 100)
s = numeric_value(p, 383)
try:
f = float(numeric_value(p, 383))
except ValueError:
f = 0.0
return f
def randcomplex():
real = randfloat()
if randrange(100) > 30:
imag = 0.0
else:
imag = randfloat()
return complex(real, imag)
def randfraction():
num = randint()
denom = randint()
if denom == 0:
denom = 1
return Fraction(num, denom)
number_funcs = [randint, randfloat, randcomplex, randfraction]
def un_random_mixed_op(itr=None):
if itr is None:
itr = 1000
for _ in range(itr):
for func in number_funcs:
yield func()
# Test garbage input
for x in (['x'], ('y',), {'z'}, {1:'z'}):
yield x
def bin_random_mixed_op(prec, emax, emin, itr=None):
if itr is None:
itr = 1000
for _ in range(itr):
for func in number_funcs:
yield randdec(prec, emax), func()
yield func(), randdec(prec, emax)
for number in number_funcs:
for dec in close_funcs:
yield dec(prec, emax, emin), number()
# Test garbage input
for x in (['x'], ('y',), {'z'}, {1:'z'}):
for y in (['x'], ('y',), {'z'}, {1:'z'}):
yield x, y
def tern_random_mixed_op(prec, emax, emin, itr):
if itr is None:
itr = 1000
for _ in range(itr):
for func in number_funcs:
yield randdec(prec, emax), randdec(prec, emax), func()
yield randdec(prec, emax), func(), func()
yield func(), func(), func()
# Test garbage input
for x in (['x'], ('y',), {'z'}, {1:'z'}):
for y in (['x'], ('y',), {'z'}, {1:'z'}):
for z in (['x'], ('y',), {'z'}, {1:'z'}):
yield x, y, z
def all_unary(prec, exp_range, itr):
for a in un_close_to_pow10(prec, exp_range, itr):
yield (a,)
for a in un_close_numbers(prec, exp_range, -exp_range, itr):
yield (a,)
for a in un_incr_digits_tuple(prec, exp_range, itr):
yield (a,)
for a in un_randfloat():
yield (a,)
for a in un_random_mixed_op(itr):
yield (a,)
for a in logical_un_incr_digits(prec, itr):
yield (a,)
for _ in range(100):
yield (randdec(prec, exp_range),)
for _ in range(100):
yield (randtuple(prec, exp_range),)
def unary_optarg(prec, exp_range, itr):
for _ in range(100):
yield randdec(prec, exp_range), None
yield randdec(prec, exp_range), None, None
def all_binary(prec, exp_range, itr):
for a, b in bin_close_to_pow10(prec, exp_range, itr):
yield a, b
for a, b in bin_close_numbers(prec, exp_range, -exp_range, itr):
yield a, b
for a, b in bin_incr_digits(prec, exp_range, itr):
yield a, b
for a, b in bin_randfloat():
yield a, b
for a, b in bin_random_mixed_op(prec, exp_range, -exp_range, itr):
yield a, b
for a, b in logical_bin_incr_digits(prec, itr):
yield a, b
for _ in range(100):
yield randdec(prec, exp_range), randdec(prec, exp_range)
def binary_optarg(prec, exp_range, itr):
for _ in range(100):
yield randdec(prec, exp_range), randdec(prec, exp_range), None
yield randdec(prec, exp_range), randdec(prec, exp_range), None, None
def all_ternary(prec, exp_range, itr):
for a, b, c in tern_close_numbers(prec, exp_range, -exp_range, itr):
yield a, b, c
for a, b, c in tern_incr_digits(prec, exp_range, itr):
yield a, b, c
for a, b, c in tern_randfloat():
yield a, b, c
for a, b, c in tern_random_mixed_op(prec, exp_range, -exp_range, itr):
yield a, b, c
for _ in range(100):
a = randdec(prec, 2*exp_range)
b = randdec(prec, 2*exp_range)
c = randdec(prec, 2*exp_range)
yield a, b, c
def ternary_optarg(prec, exp_range, itr):
for _ in range(100):
a = randdec(prec, 2*exp_range)
b = randdec(prec, 2*exp_range)
c = randdec(prec, 2*exp_range)
yield a, b, c, None
yield a, b, c, None, None
| 18,442 | 576 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Modules/_decimal/tests/README.txt |
This directory contains extended tests and a benchmark against decimal.py:
bench.py -> Benchmark for small and large precisions.
Usage: ../../../python bench.py
formathelper.py ->
randdec.py -> Generate test cases for deccheck.py.
randfloat.py ->
deccheck.py -> Run extended tests.
Usage: ../../../python deccheck.py [--short|--medium|--long|--all]
| 389 | 16 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Modules/_decimal/tests/deccheck.py | #
# Copyright (c) 2008-2012 Stefan Krah. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# 1. Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS "AS IS" AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
# OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
# OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
# SUCH DAMAGE.
#
#
# Usage: python deccheck.py [--short|--medium|--long|--all]
#
import sys, random
from copy import copy
from collections import defaultdict
from test.support import import_fresh_module
from randdec import randfloat, all_unary, all_binary, all_ternary
from randdec import unary_optarg, binary_optarg, ternary_optarg
from formathelper import rand_format, rand_locale
from _pydecimal import _dec_from_triple
C = import_fresh_module('decimal', fresh=['_decimal'])
P = import_fresh_module('decimal', blocked=['_decimal'])
EXIT_STATUS = 0
# Contains all categories of Decimal methods.
Functions = {
# Plain unary:
'unary': (
'__abs__', '__bool__', '__ceil__', '__complex__', '__copy__',
'__floor__', '__float__', '__hash__', '__int__', '__neg__',
'__pos__', '__reduce__', '__repr__', '__str__', '__trunc__',
'adjusted', 'as_integer_ratio', 'as_tuple', 'canonical', 'conjugate',
'copy_abs', 'copy_negate', 'is_canonical', 'is_finite', 'is_infinite',
'is_nan', 'is_qnan', 'is_signed', 'is_snan', 'is_zero', 'radix'
),
# Unary with optional context:
'unary_ctx': (
'exp', 'is_normal', 'is_subnormal', 'ln', 'log10', 'logb',
'logical_invert', 'next_minus', 'next_plus', 'normalize',
'number_class', 'sqrt', 'to_eng_string'
),
# Unary with optional rounding mode and context:
'unary_rnd_ctx': ('to_integral', 'to_integral_exact', 'to_integral_value'),
# Plain binary:
'binary': (
'__add__', '__divmod__', '__eq__', '__floordiv__', '__ge__', '__gt__',
'__le__', '__lt__', '__mod__', '__mul__', '__ne__', '__pow__',
'__radd__', '__rdivmod__', '__rfloordiv__', '__rmod__', '__rmul__',
'__rpow__', '__rsub__', '__rtruediv__', '__sub__', '__truediv__',
'compare_total', 'compare_total_mag', 'copy_sign', 'quantize',
'same_quantum'
),
# Binary with optional context:
'binary_ctx': (
'compare', 'compare_signal', 'logical_and', 'logical_or', 'logical_xor',
'max', 'max_mag', 'min', 'min_mag', 'next_toward', 'remainder_near',
'rotate', 'scaleb', 'shift'
),
# Plain ternary:
'ternary': ('__pow__',),
# Ternary with optional context:
'ternary_ctx': ('fma',),
# Special:
'special': ('__format__', '__reduce_ex__', '__round__', 'from_float',
'quantize'),
# Properties:
'property': ('real', 'imag')
}
# Contains all categories of Context methods. The n-ary classification
# applies to the number of Decimal arguments.
ContextFunctions = {
# Plain nullary:
'nullary': ('context.__hash__', 'context.__reduce__', 'context.radix'),
# Plain unary:
'unary': ('context.abs', 'context.canonical', 'context.copy_abs',
'context.copy_decimal', 'context.copy_negate',
'context.create_decimal', 'context.exp', 'context.is_canonical',
'context.is_finite', 'context.is_infinite', 'context.is_nan',
'context.is_normal', 'context.is_qnan', 'context.is_signed',
'context.is_snan', 'context.is_subnormal', 'context.is_zero',
'context.ln', 'context.log10', 'context.logb',
'context.logical_invert', 'context.minus', 'context.next_minus',
'context.next_plus', 'context.normalize', 'context.number_class',
'context.plus', 'context.sqrt', 'context.to_eng_string',
'context.to_integral', 'context.to_integral_exact',
'context.to_integral_value', 'context.to_sci_string'
),
# Plain binary:
'binary': ('context.add', 'context.compare', 'context.compare_signal',
'context.compare_total', 'context.compare_total_mag',
'context.copy_sign', 'context.divide', 'context.divide_int',
'context.divmod', 'context.logical_and', 'context.logical_or',
'context.logical_xor', 'context.max', 'context.max_mag',
'context.min', 'context.min_mag', 'context.multiply',
'context.next_toward', 'context.power', 'context.quantize',
'context.remainder', 'context.remainder_near', 'context.rotate',
'context.same_quantum', 'context.scaleb', 'context.shift',
'context.subtract'
),
# Plain ternary:
'ternary': ('context.fma', 'context.power'),
# Special:
'special': ('context.__reduce_ex__', 'context.create_decimal_from_float')
}
# Functions that require a restricted exponent range for reasonable runtimes.
UnaryRestricted = [
'__ceil__', '__floor__', '__int__', '__trunc__',
'as_integer_ratio', 'to_integral', 'to_integral_value'
]
BinaryRestricted = ['__round__']
TernaryRestricted = ['__pow__', 'context.power']
# ======================================================================
# Unified Context
# ======================================================================
# Translate symbols.
CondMap = {
C.Clamped: P.Clamped,
C.ConversionSyntax: P.ConversionSyntax,
C.DivisionByZero: P.DivisionByZero,
C.DivisionImpossible: P.InvalidOperation,
C.DivisionUndefined: P.DivisionUndefined,
C.Inexact: P.Inexact,
C.InvalidContext: P.InvalidContext,
C.InvalidOperation: P.InvalidOperation,
C.Overflow: P.Overflow,
C.Rounded: P.Rounded,
C.Subnormal: P.Subnormal,
C.Underflow: P.Underflow,
C.FloatOperation: P.FloatOperation,
}
RoundModes = [C.ROUND_UP, C.ROUND_DOWN, C.ROUND_CEILING, C.ROUND_FLOOR,
C.ROUND_HALF_UP, C.ROUND_HALF_DOWN, C.ROUND_HALF_EVEN,
C.ROUND_05UP]
class Context(object):
"""Provides a convenient way of syncing the C and P contexts"""
__slots__ = ['c', 'p']
def __init__(self, c_ctx=None, p_ctx=None):
"""Initialization is from the C context"""
self.c = C.getcontext() if c_ctx is None else c_ctx
self.p = P.getcontext() if p_ctx is None else p_ctx
self.p.prec = self.c.prec
self.p.Emin = self.c.Emin
self.p.Emax = self.c.Emax
self.p.rounding = self.c.rounding
self.p.capitals = self.c.capitals
self.settraps([sig for sig in self.c.traps if self.c.traps[sig]])
self.setstatus([sig for sig in self.c.flags if self.c.flags[sig]])
self.p.clamp = self.c.clamp
def __str__(self):
return str(self.c) + '\n' + str(self.p)
def getprec(self):
assert(self.c.prec == self.p.prec)
return self.c.prec
def setprec(self, val):
self.c.prec = val
self.p.prec = val
def getemin(self):
assert(self.c.Emin == self.p.Emin)
return self.c.Emin
def setemin(self, val):
self.c.Emin = val
self.p.Emin = val
def getemax(self):
assert(self.c.Emax == self.p.Emax)
return self.c.Emax
def setemax(self, val):
self.c.Emax = val
self.p.Emax = val
def getround(self):
assert(self.c.rounding == self.p.rounding)
return self.c.rounding
def setround(self, val):
self.c.rounding = val
self.p.rounding = val
def getcapitals(self):
assert(self.c.capitals == self.p.capitals)
return self.c.capitals
def setcapitals(self, val):
self.c.capitals = val
self.p.capitals = val
def getclamp(self):
assert(self.c.clamp == self.p.clamp)
return self.c.clamp
def setclamp(self, val):
self.c.clamp = val
self.p.clamp = val
prec = property(getprec, setprec)
Emin = property(getemin, setemin)
Emax = property(getemax, setemax)
rounding = property(getround, setround)
clamp = property(getclamp, setclamp)
capitals = property(getcapitals, setcapitals)
def clear_traps(self):
self.c.clear_traps()
for trap in self.p.traps:
self.p.traps[trap] = False
def clear_status(self):
self.c.clear_flags()
self.p.clear_flags()
def settraps(self, lst):
"""lst: C signal list"""
self.clear_traps()
for signal in lst:
self.c.traps[signal] = True
self.p.traps[CondMap[signal]] = True
def setstatus(self, lst):
"""lst: C signal list"""
self.clear_status()
for signal in lst:
self.c.flags[signal] = True
self.p.flags[CondMap[signal]] = True
def assert_eq_status(self):
"""assert equality of C and P status"""
for signal in self.c.flags:
if self.c.flags[signal] == (not self.p.flags[CondMap[signal]]):
return False
return True
# We don't want exceptions so that we can compare the status flags.
context = Context()
context.Emin = C.MIN_EMIN
context.Emax = C.MAX_EMAX
context.clear_traps()
# When creating decimals, _decimal is ultimately limited by the maximum
# context values. We emulate this restriction for decimal.py.
maxcontext = P.Context(
prec=C.MAX_PREC,
Emin=C.MIN_EMIN,
Emax=C.MAX_EMAX,
rounding=P.ROUND_HALF_UP,
capitals=1
)
maxcontext.clamp = 0
def RestrictedDecimal(value):
maxcontext.traps = copy(context.p.traps)
maxcontext.clear_flags()
if isinstance(value, str):
value = value.strip()
dec = maxcontext.create_decimal(value)
if maxcontext.flags[P.Inexact] or \
maxcontext.flags[P.Rounded] or \
maxcontext.flags[P.Clamped] or \
maxcontext.flags[P.InvalidOperation]:
return context.p._raise_error(P.InvalidOperation)
if maxcontext.flags[P.FloatOperation]:
context.p.flags[P.FloatOperation] = True
return dec
# ======================================================================
# TestSet: Organize data and events during a single test case
# ======================================================================
class RestrictedList(list):
"""List that can only be modified by appending items."""
def __getattribute__(self, name):
if name != 'append':
raise AttributeError("unsupported operation")
return list.__getattribute__(self, name)
def unsupported(self, *_):
raise AttributeError("unsupported operation")
__add__ = __delattr__ = __delitem__ = __iadd__ = __imul__ = unsupported
__mul__ = __reversed__ = __rmul__ = __setattr__ = __setitem__ = unsupported
class TestSet(object):
"""A TestSet contains the original input operands, converted operands,
Python exceptions that occurred either during conversion or during
execution of the actual function, and the final results.
For safety, most attributes are lists that only support the append
operation.
If a function name is prefixed with 'context.', the corresponding
context method is called.
"""
def __init__(self, funcname, operands):
if funcname.startswith("context."):
self.funcname = funcname.replace("context.", "")
self.contextfunc = True
else:
self.funcname = funcname
self.contextfunc = False
self.op = operands # raw operand tuple
self.context = context # context used for the operation
self.cop = RestrictedList() # converted C.Decimal operands
self.cex = RestrictedList() # Python exceptions for C.Decimal
self.cresults = RestrictedList() # C.Decimal results
self.pop = RestrictedList() # converted P.Decimal operands
self.pex = RestrictedList() # Python exceptions for P.Decimal
self.presults = RestrictedList() # P.Decimal results
# ======================================================================
# SkipHandler: skip known discrepancies
# ======================================================================
class SkipHandler:
"""Handle known discrepancies between decimal.py and _decimal.so.
These are either ULP differences in the power function or
extremely minor issues."""
def __init__(self):
self.ulpdiff = 0
self.powmod_zeros = 0
self.maxctx = P.Context(Emax=10**18, Emin=-10**18)
def default(self, t):
return False
__ge__ = __gt__ = __le__ = __lt__ = __ne__ = __eq__ = default
__reduce__ = __format__ = __repr__ = __str__ = default
def harrison_ulp(self, dec):
"""ftp://ftp.inria.fr/INRIA/publication/publi-pdf/RR/RR-5504.pdf"""
a = dec.next_plus()
b = dec.next_minus()
return abs(a - b)
def standard_ulp(self, dec, prec):
return _dec_from_triple(0, '1', dec._exp+len(dec._int)-prec)
def rounding_direction(self, x, mode):
"""Determine the effective direction of the rounding when
the exact result x is rounded according to mode.
Return -1 for downwards, 0 for undirected, 1 for upwards,
2 for ROUND_05UP."""
cmp = 1 if x.compare_total(P.Decimal("+0")) >= 0 else -1
if mode in (P.ROUND_HALF_EVEN, P.ROUND_HALF_UP, P.ROUND_HALF_DOWN):
return 0
elif mode == P.ROUND_CEILING:
return 1
elif mode == P.ROUND_FLOOR:
return -1
elif mode == P.ROUND_UP:
return cmp
elif mode == P.ROUND_DOWN:
return -cmp
elif mode == P.ROUND_05UP:
return 2
else:
raise ValueError("Unexpected rounding mode: %s" % mode)
def check_ulpdiff(self, exact, rounded):
# current precision
p = context.p.prec
# Convert infinities to the largest representable number + 1.
x = exact
if exact.is_infinite():
x = _dec_from_triple(exact._sign, '10', context.p.Emax)
y = rounded
if rounded.is_infinite():
y = _dec_from_triple(rounded._sign, '10', context.p.Emax)
# err = (rounded - exact) / ulp(rounded)
self.maxctx.prec = p * 2
t = self.maxctx.subtract(y, x)
if context.c.flags[C.Clamped] or \
context.c.flags[C.Underflow]:
# The standard ulp does not work in Underflow territory.
ulp = self.harrison_ulp(y)
else:
ulp = self.standard_ulp(y, p)
# Error in ulps.
err = self.maxctx.divide(t, ulp)
dir = self.rounding_direction(x, context.p.rounding)
if dir == 0:
if P.Decimal("-0.6") < err < P.Decimal("0.6"):
return True
elif dir == 1: # directed, upwards
if P.Decimal("-0.1") < err < P.Decimal("1.1"):
return True
elif dir == -1: # directed, downwards
if P.Decimal("-1.1") < err < P.Decimal("0.1"):
return True
else: # ROUND_05UP
if P.Decimal("-1.1") < err < P.Decimal("1.1"):
return True
print("ulp: %s error: %s exact: %s c_rounded: %s"
% (ulp, err, exact, rounded))
return False
def bin_resolve_ulp(self, t):
"""Check if results of _decimal's power function are within the
allowed ulp ranges."""
# NaNs are beyond repair.
if t.rc.is_nan() or t.rp.is_nan():
return False
# "exact" result, double precision, half_even
self.maxctx.prec = context.p.prec * 2
op1, op2 = t.pop[0], t.pop[1]
if t.contextfunc:
exact = getattr(self.maxctx, t.funcname)(op1, op2)
else:
exact = getattr(op1, t.funcname)(op2, context=self.maxctx)
# _decimal's rounded result
rounded = P.Decimal(t.cresults[0])
self.ulpdiff += 1
return self.check_ulpdiff(exact, rounded)
############################ Correct rounding #############################
def resolve_underflow(self, t):
"""In extremely rare cases where the infinite precision result is just
below etiny, cdecimal does not set Subnormal/Underflow. Example:
setcontext(Context(prec=21, rounding=ROUND_UP, Emin=-55, Emax=85))
Decimal("1.00000000000000000000000000000000000000000000000"
"0000000100000000000000000000000000000000000000000"
"0000000000000025").ln()
"""
if t.cresults != t.presults:
return False # Results must be identical.
if context.c.flags[C.Rounded] and \
context.c.flags[C.Inexact] and \
context.p.flags[P.Rounded] and \
context.p.flags[P.Inexact]:
return True # Subnormal/Underflow may be missing.
return False
def exp(self, t):
"""Resolve Underflow or ULP difference."""
return self.resolve_underflow(t)
def log10(self, t):
"""Resolve Underflow or ULP difference."""
return self.resolve_underflow(t)
def ln(self, t):
"""Resolve Underflow or ULP difference."""
return self.resolve_underflow(t)
def __pow__(self, t):
"""Always calls the resolve function. C.Decimal does not have correct
rounding for the power function."""
if context.c.flags[C.Rounded] and \
context.c.flags[C.Inexact] and \
context.p.flags[P.Rounded] and \
context.p.flags[P.Inexact]:
return self.bin_resolve_ulp(t)
else:
return False
power = __rpow__ = __pow__
############################## Technicalities #############################
def __float__(self, t):
"""NaN comparison in the verify() function obviously gives an
incorrect answer: nan == nan -> False"""
if t.cop[0].is_nan() and t.pop[0].is_nan():
return True
return False
__complex__ = __float__
def __radd__(self, t):
"""decimal.py gives precedence to the first NaN; this is
not important, as __radd__ will not be called for
two decimal arguments."""
if t.rc.is_nan() and t.rp.is_nan():
return True
return False
__rmul__ = __radd__
################################ Various ##################################
def __round__(self, t):
"""Exception: Decimal('1').__round__(-100000000000000000000000000)
Should it really be InvalidOperation?"""
if t.rc is None and t.rp.is_nan():
return True
return False
shandler = SkipHandler()
def skip_error(t):
return getattr(shandler, t.funcname, shandler.default)(t)
# ======================================================================
# Handling verification errors
# ======================================================================
class VerifyError(Exception):
"""Verification failed."""
pass
def function_as_string(t):
if t.contextfunc:
cargs = t.cop
pargs = t.pop
cfunc = "c_func: %s(" % t.funcname
pfunc = "p_func: %s(" % t.funcname
else:
cself, cargs = t.cop[0], t.cop[1:]
pself, pargs = t.pop[0], t.pop[1:]
cfunc = "c_func: %s.%s(" % (repr(cself), t.funcname)
pfunc = "p_func: %s.%s(" % (repr(pself), t.funcname)
err = cfunc
for arg in cargs:
err += "%s, " % repr(arg)
err = err.rstrip(", ")
err += ")\n"
err += pfunc
for arg in pargs:
err += "%s, " % repr(arg)
err = err.rstrip(", ")
err += ")"
return err
def raise_error(t):
global EXIT_STATUS
if skip_error(t):
return
EXIT_STATUS = 1
err = "Error in %s:\n\n" % t.funcname
err += "input operands: %s\n\n" % (t.op,)
err += function_as_string(t)
err += "\n\nc_result: %s\np_result: %s\n\n" % (t.cresults, t.presults)
err += "c_exceptions: %s\np_exceptions: %s\n\n" % (t.cex, t.pex)
err += "%s\n\n" % str(t.context)
raise VerifyError(err)
# ======================================================================
# Main testing functions
#
# The procedure is always (t is the TestSet):
#
# convert(t) -> Initialize the TestSet as necessary.
#
# Return 0 for early abortion (e.g. if a TypeError
# occurs during conversion, there is nothing to test).
#
# Return 1 for continuing with the test case.
#
# callfuncs(t) -> Call the relevant function for each implementation
# and record the results in the TestSet.
#
# verify(t) -> Verify the results. If verification fails, details
# are printed to stdout.
# ======================================================================
def convert(t, convstr=True):
""" t is the testset. At this stage the testset contains a tuple of
operands t.op of various types. For decimal methods the first
operand (self) is always converted to Decimal. If 'convstr' is
true, string operands are converted as well.
Context operands are of type deccheck.Context, rounding mode
operands are given as a tuple (C.rounding, P.rounding).
Other types (float, int, etc.) are left unchanged.
"""
for i, op in enumerate(t.op):
context.clear_status()
if op in RoundModes:
t.cop.append(op)
t.pop.append(op)
elif not t.contextfunc and i == 0 or \
convstr and isinstance(op, str):
try:
c = C.Decimal(op)
cex = None
except (TypeError, ValueError, OverflowError) as e:
c = None
cex = e.__class__
try:
p = RestrictedDecimal(op)
pex = None
except (TypeError, ValueError, OverflowError) as e:
p = None
pex = e.__class__
t.cop.append(c)
t.cex.append(cex)
t.pop.append(p)
t.pex.append(pex)
if cex is pex:
if str(c) != str(p) or not context.assert_eq_status():
raise_error(t)
if cex and pex:
# nothing to test
return 0
else:
raise_error(t)
elif isinstance(op, Context):
t.context = op
t.cop.append(op.c)
t.pop.append(op.p)
else:
t.cop.append(op)
t.pop.append(op)
return 1
def callfuncs(t):
""" t is the testset. At this stage the testset contains operand lists
t.cop and t.pop for the C and Python versions of decimal.
For Decimal methods, the first operands are of type C.Decimal and
P.Decimal respectively. The remaining operands can have various types.
For Context methods, all operands can have any type.
t.rc and t.rp are the results of the operation.
"""
context.clear_status()
try:
if t.contextfunc:
cargs = t.cop
t.rc = getattr(context.c, t.funcname)(*cargs)
else:
cself = t.cop[0]
cargs = t.cop[1:]
t.rc = getattr(cself, t.funcname)(*cargs)
t.cex.append(None)
except (TypeError, ValueError, OverflowError, MemoryError) as e:
t.rc = None
t.cex.append(e.__class__)
try:
if t.contextfunc:
pargs = t.pop
t.rp = getattr(context.p, t.funcname)(*pargs)
else:
pself = t.pop[0]
pargs = t.pop[1:]
t.rp = getattr(pself, t.funcname)(*pargs)
t.pex.append(None)
except (TypeError, ValueError, OverflowError, MemoryError) as e:
t.rp = None
t.pex.append(e.__class__)
def verify(t, stat):
""" t is the testset. At this stage the testset contains the following
tuples:
t.op: original operands
t.cop: C.Decimal operands (see convert for details)
t.pop: P.Decimal operands (see convert for details)
t.rc: C result
t.rp: Python result
t.rc and t.rp can have various types.
"""
t.cresults.append(str(t.rc))
t.presults.append(str(t.rp))
if isinstance(t.rc, C.Decimal) and isinstance(t.rp, P.Decimal):
# General case: both results are Decimals.
t.cresults.append(t.rc.to_eng_string())
t.cresults.append(t.rc.as_tuple())
t.cresults.append(str(t.rc.imag))
t.cresults.append(str(t.rc.real))
t.presults.append(t.rp.to_eng_string())
t.presults.append(t.rp.as_tuple())
t.presults.append(str(t.rp.imag))
t.presults.append(str(t.rp.real))
nc = t.rc.number_class().lstrip('+-s')
stat[nc] += 1
else:
# Results from e.g. __divmod__ can only be compared as strings.
if not isinstance(t.rc, tuple) and not isinstance(t.rp, tuple):
if t.rc != t.rp:
raise_error(t)
stat[type(t.rc).__name__] += 1
# The return value lists must be equal.
if t.cresults != t.presults:
raise_error(t)
# The Python exception lists (TypeError, etc.) must be equal.
if t.cex != t.pex:
raise_error(t)
# The context flags must be equal.
if not t.context.assert_eq_status():
raise_error(t)
# ======================================================================
# Main test loops
#
# test_method(method, testspecs, testfunc) ->
#
# Loop through various context settings. The degree of
# thoroughness is determined by 'testspec'. For each
# setting, call 'testfunc'. Generally, 'testfunc' itself
# a loop, iterating through many test cases generated
# by the functions in randdec.py.
#
# test_n-ary(method, prec, exp_range, restricted_range, itr, stat) ->
#
# 'test_unary', 'test_binary' and 'test_ternary' are the
# main test functions passed to 'test_method'. They deal
# with the regular cases. The thoroughness of testing is
# determined by 'itr'.
#
# 'prec', 'exp_range' and 'restricted_range' are passed
# to the test-generating functions and limit the generated
# values. In some cases, for reasonable run times a
# maximum exponent of 9999 is required.
#
# The 'stat' parameter is passed down to the 'verify'
# function, which records statistics for the result values.
# ======================================================================
def log(fmt, args=None):
if args:
sys.stdout.write(''.join((fmt, '\n')) % args)
else:
sys.stdout.write(''.join((str(fmt), '\n')))
sys.stdout.flush()
def test_method(method, testspecs, testfunc):
"""Iterate a test function through many context settings."""
log("testing %s ...", method)
stat = defaultdict(int)
for spec in testspecs:
if 'samples' in spec:
spec['prec'] = sorted(random.sample(range(1, 101),
spec['samples']))
for prec in spec['prec']:
context.prec = prec
for expts in spec['expts']:
emin, emax = expts
if emin == 'rand':
context.Emin = random.randrange(-1000, 0)
context.Emax = random.randrange(prec, 1000)
else:
context.Emin, context.Emax = emin, emax
if prec > context.Emax: continue
log(" prec: %d emin: %d emax: %d",
(context.prec, context.Emin, context.Emax))
restr_range = 9999 if context.Emax > 9999 else context.Emax+99
for rounding in RoundModes:
context.rounding = rounding
context.capitals = random.randrange(2)
if spec['clamp'] == 'rand':
context.clamp = random.randrange(2)
else:
context.clamp = spec['clamp']
exprange = context.c.Emax
testfunc(method, prec, exprange, restr_range,
spec['iter'], stat)
log(" result types: %s" % sorted([t for t in stat.items()]))
def test_unary(method, prec, exp_range, restricted_range, itr, stat):
"""Iterate a unary function through many test cases."""
if method in UnaryRestricted:
exp_range = restricted_range
for op in all_unary(prec, exp_range, itr):
t = TestSet(method, op)
try:
if not convert(t):
continue
callfuncs(t)
verify(t, stat)
except VerifyError as err:
log(err)
if not method.startswith('__'):
for op in unary_optarg(prec, exp_range, itr):
t = TestSet(method, op)
try:
if not convert(t):
continue
callfuncs(t)
verify(t, stat)
except VerifyError as err:
log(err)
def test_binary(method, prec, exp_range, restricted_range, itr, stat):
"""Iterate a binary function through many test cases."""
if method in BinaryRestricted:
exp_range = restricted_range
for op in all_binary(prec, exp_range, itr):
t = TestSet(method, op)
try:
if not convert(t):
continue
callfuncs(t)
verify(t, stat)
except VerifyError as err:
log(err)
if not method.startswith('__'):
for op in binary_optarg(prec, exp_range, itr):
t = TestSet(method, op)
try:
if not convert(t):
continue
callfuncs(t)
verify(t, stat)
except VerifyError as err:
log(err)
def test_ternary(method, prec, exp_range, restricted_range, itr, stat):
"""Iterate a ternary function through many test cases."""
if method in TernaryRestricted:
exp_range = restricted_range
for op in all_ternary(prec, exp_range, itr):
t = TestSet(method, op)
try:
if not convert(t):
continue
callfuncs(t)
verify(t, stat)
except VerifyError as err:
log(err)
if not method.startswith('__'):
for op in ternary_optarg(prec, exp_range, itr):
t = TestSet(method, op)
try:
if not convert(t):
continue
callfuncs(t)
verify(t, stat)
except VerifyError as err:
log(err)
def test_format(method, prec, exp_range, restricted_range, itr, stat):
"""Iterate the __format__ method through many test cases."""
for op in all_unary(prec, exp_range, itr):
fmt1 = rand_format(chr(random.randrange(0, 128)), 'EeGgn')
fmt2 = rand_locale()
for fmt in (fmt1, fmt2):
fmtop = (op[0], fmt)
t = TestSet(method, fmtop)
try:
if not convert(t, convstr=False):
continue
callfuncs(t)
verify(t, stat)
except VerifyError as err:
log(err)
for op in all_unary(prec, 9999, itr):
fmt1 = rand_format(chr(random.randrange(0, 128)), 'Ff%')
fmt2 = rand_locale()
for fmt in (fmt1, fmt2):
fmtop = (op[0], fmt)
t = TestSet(method, fmtop)
try:
if not convert(t, convstr=False):
continue
callfuncs(t)
verify(t, stat)
except VerifyError as err:
log(err)
def test_round(method, prec, exprange, restricted_range, itr, stat):
"""Iterate the __round__ method through many test cases."""
for op in all_unary(prec, 9999, itr):
n = random.randrange(10)
roundop = (op[0], n)
t = TestSet(method, roundop)
try:
if not convert(t):
continue
callfuncs(t)
verify(t, stat)
except VerifyError as err:
log(err)
def test_from_float(method, prec, exprange, restricted_range, itr, stat):
"""Iterate the __float__ method through many test cases."""
for rounding in RoundModes:
context.rounding = rounding
for i in range(1000):
f = randfloat()
op = (f,) if method.startswith("context.") else ("sNaN", f)
t = TestSet(method, op)
try:
if not convert(t):
continue
callfuncs(t)
verify(t, stat)
except VerifyError as err:
log(err)
def randcontext(exprange):
c = Context(C.Context(), P.Context())
c.Emax = random.randrange(1, exprange+1)
c.Emin = random.randrange(-exprange, 0)
maxprec = 100 if c.Emax >= 100 else c.Emax
c.prec = random.randrange(1, maxprec+1)
c.clamp = random.randrange(2)
c.clear_traps()
return c
def test_quantize_api(method, prec, exprange, restricted_range, itr, stat):
"""Iterate the 'quantize' method through many test cases, using
the optional arguments."""
for op in all_binary(prec, restricted_range, itr):
for rounding in RoundModes:
c = randcontext(exprange)
quantizeop = (op[0], op[1], rounding, c)
t = TestSet(method, quantizeop)
try:
if not convert(t):
continue
callfuncs(t)
verify(t, stat)
except VerifyError as err:
log(err)
def check_untested(funcdict, c_cls, p_cls):
"""Determine untested, C-only and Python-only attributes.
Uncomment print lines for debugging."""
c_attr = set(dir(c_cls))
p_attr = set(dir(p_cls))
intersect = c_attr & p_attr
funcdict['c_only'] = tuple(sorted(c_attr-intersect))
funcdict['p_only'] = tuple(sorted(p_attr-intersect))
tested = set()
for lst in funcdict.values():
for v in lst:
v = v.replace("context.", "") if c_cls == C.Context else v
tested.add(v)
funcdict['untested'] = tuple(sorted(intersect-tested))
#for key in ('untested', 'c_only', 'p_only'):
# s = 'Context' if c_cls == C.Context else 'Decimal'
# print("\n%s %s:\n%s" % (s, key, funcdict[key]))
if __name__ == '__main__':
import time
randseed = int(time.time())
random.seed(randseed)
# Set up the testspecs list. A testspec is simply a dictionary
# that determines the amount of different contexts that 'test_method'
# will generate.
base_expts = [(C.MIN_EMIN, C.MAX_EMAX)]
if C.MAX_EMAX == 999999999999999999:
base_expts.append((-999999999, 999999999))
# Basic contexts.
base = {
'expts': base_expts,
'prec': [],
'clamp': 'rand',
'iter': None,
'samples': None,
}
# Contexts with small values for prec, emin, emax.
small = {
'prec': [1, 2, 3, 4, 5],
'expts': [(-1, 1), (-2, 2), (-3, 3), (-4, 4), (-5, 5)],
'clamp': 'rand',
'iter': None
}
# IEEE interchange format.
ieee = [
# DECIMAL32
{'prec': [7], 'expts': [(-95, 96)], 'clamp': 1, 'iter': None},
# DECIMAL64
{'prec': [16], 'expts': [(-383, 384)], 'clamp': 1, 'iter': None},
# DECIMAL128
{'prec': [34], 'expts': [(-6143, 6144)], 'clamp': 1, 'iter': None}
]
if '--medium' in sys.argv:
base['expts'].append(('rand', 'rand'))
# 5 random precisions
base['samples'] = 5
testspecs = [small] + ieee + [base]
if '--long' in sys.argv:
base['expts'].append(('rand', 'rand'))
# 10 random precisions
base['samples'] = 10
testspecs = [small] + ieee + [base]
elif '--all' in sys.argv:
base['expts'].append(('rand', 'rand'))
# All precisions in [1, 100]
base['samples'] = 100
testspecs = [small] + ieee + [base]
else: # --short
rand_ieee = random.choice(ieee)
base['iter'] = small['iter'] = rand_ieee['iter'] = 1
# 1 random precision and exponent pair
base['samples'] = 1
base['expts'] = [random.choice(base_expts)]
# 1 random precision and exponent pair
prec = random.randrange(1, 6)
small['prec'] = [prec]
small['expts'] = [(-prec, prec)]
testspecs = [small, rand_ieee, base]
check_untested(Functions, C.Decimal, P.Decimal)
check_untested(ContextFunctions, C.Context, P.Context)
log("\n\nRandom seed: %d\n\n", randseed)
# Decimal methods:
for method in Functions['unary'] + Functions['unary_ctx'] + \
Functions['unary_rnd_ctx']:
test_method(method, testspecs, test_unary)
for method in Functions['binary'] + Functions['binary_ctx']:
test_method(method, testspecs, test_binary)
for method in Functions['ternary'] + Functions['ternary_ctx']:
test_method(method, testspecs, test_ternary)
test_method('__format__', testspecs, test_format)
test_method('__round__', testspecs, test_round)
test_method('from_float', testspecs, test_from_float)
test_method('quantize', testspecs, test_quantize_api)
# Context methods:
for method in ContextFunctions['unary']:
test_method(method, testspecs, test_unary)
for method in ContextFunctions['binary']:
test_method(method, testspecs, test_binary)
for method in ContextFunctions['ternary']:
test_method(method, testspecs, test_ternary)
test_method('context.create_decimal_from_float', testspecs, test_from_float)
sys.exit(EXIT_STATUS)
| 38,999 | 1,101 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Modules/_decimal/tests/bench.py | #
# Copyright (C) 2001-2012 Python Software Foundation. All Rights Reserved.
# Modified and extended by Stefan Krah.
#
# Usage: ../../../python bench.py
import time
from math import log, ceil
try:
from test.support import import_fresh_module
except ImportError:
from test.test_support import import_fresh_module
C = import_fresh_module('decimal', fresh=['_decimal'])
P = import_fresh_module('decimal', blocked=['_decimal'])
#
# NOTE: This is the pi function from the decimal documentation, modified
# for benchmarking purposes. Since floats do not have a context, the higher
# intermediate precision from the original is NOT used, so the modified
# algorithm only gives an approximation to the correctly rounded result.
# For serious use, refer to the documentation or the appropriate literature.
#
def pi_float():
"""native float"""
lasts, t, s, n, na, d, da = 0, 3.0, 3, 1, 0, 0, 24
while s != lasts:
lasts = s
n, na = n+na, na+8
d, da = d+da, da+32
t = (t * n) / d
s += t
return s
def pi_cdecimal():
"""cdecimal"""
D = C.Decimal
lasts, t, s, n, na, d, da = D(0), D(3), D(3), D(1), D(0), D(0), D(24)
while s != lasts:
lasts = s
n, na = n+na, na+8
d, da = d+da, da+32
t = (t * n) / d
s += t
return s
def pi_decimal():
"""decimal"""
D = P.Decimal
lasts, t, s, n, na, d, da = D(0), D(3), D(3), D(1), D(0), D(0), D(24)
while s != lasts:
lasts = s
n, na = n+na, na+8
d, da = d+da, da+32
t = (t * n) / d
s += t
return s
def factorial(n, m):
if (n > m):
return factorial(m, n)
elif m == 0:
return 1
elif n == m:
return n
else:
return factorial(n, (n+m)//2) * factorial((n+m)//2 + 1, m)
print("\n# ======================================================================")
print("# Calculating pi, 10000 iterations")
print("# ======================================================================\n")
to_benchmark = [pi_float, pi_decimal]
if C is not None:
to_benchmark.insert(1, pi_cdecimal)
for prec in [9, 19]:
print("\nPrecision: %d decimal digits\n" % prec)
for func in to_benchmark:
start = time.time()
if C is not None:
C.getcontext().prec = prec
P.getcontext().prec = prec
for i in range(10000):
x = func()
print("%s:" % func.__name__.replace("pi_", ""))
print("result: %s" % str(x))
print("time: %fs\n" % (time.time()-start))
print("\n# ======================================================================")
print("# Factorial")
print("# ======================================================================\n")
if C is not None:
c = C.getcontext()
c.prec = C.MAX_PREC
c.Emax = C.MAX_EMAX
c.Emin = C.MIN_EMIN
for n in [100000, 1000000]:
print("n = %d\n" % n)
if C is not None:
# C version of decimal
start_calc = time.time()
x = factorial(C.Decimal(n), 0)
end_calc = time.time()
start_conv = time.time()
sx = str(x)
end_conv = time.time()
print("cdecimal:")
print("calculation time: %fs" % (end_calc-start_calc))
print("conversion time: %fs\n" % (end_conv-start_conv))
# Python integers
start_calc = time.time()
y = factorial(n, 0)
end_calc = time.time()
start_conv = time.time()
sy = str(y)
end_conv = time.time()
print("int:")
print("calculation time: %fs" % (end_calc-start_calc))
print("conversion time: %fs\n\n" % (end_conv-start_conv))
if C is not None:
assert(sx == sy)
| 3,731 | 134 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Modules/_decimal/tests/bignum.py | #
# These tests require gmpy and test the limits of the 32-bit build. The
# limits of the 64-bit build are so large that they cannot be tested
# on accessible hardware.
#
import sys
from decimal import *
from gmpy import mpz
_PyHASH_MODULUS = sys.hash_info.modulus
# hash values to use for positive and negative infinities, and nans
_PyHASH_INF = sys.hash_info.inf
_PyHASH_NAN = sys.hash_info.nan
# _PyHASH_10INV is the inverse of 10 modulo the prime _PyHASH_MODULUS
_PyHASH_10INV = pow(10, _PyHASH_MODULUS - 2, _PyHASH_MODULUS)
def xhash(coeff, exp):
sign = 1
if coeff < 0:
sign = -1
coeff = -coeff
if exp >= 0:
exp_hash = pow(10, exp, _PyHASH_MODULUS)
else:
exp_hash = pow(_PyHASH_10INV, -exp, _PyHASH_MODULUS)
hash_ = coeff * exp_hash % _PyHASH_MODULUS
ans = hash_ if sign == 1 else -hash_
return -2 if ans == -1 else ans
x = mpz(10) ** 425000000 - 1
coeff = int(x)
d = Decimal('9' * 425000000 + 'e-849999999')
h1 = xhash(coeff, -849999999)
h2 = hash(d)
assert h2 == h1
| 1,043 | 43 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Modules/_decimal/tests/runall-memorydebugger.sh | #!/bin/sh
#
# Purpose: test with and without threads, all machine configurations, pydebug,
# refleaks, release build and release build with valgrind.
#
# Synopsis: ./runall-memorydebugger.sh [--all-configs64 | --all-configs32]
#
# Requirements: valgrind
#
# Set additional CFLAGS and LDFLAGS for ./configure
ADD_CFLAGS=
ADD_LDFLAGS=
CONFIGS_64="x64 uint128 ansi64 universal"
CONFIGS_32="ppro ansi32 ansi-legacy universal"
VALGRIND="valgrind --tool=memcheck --leak-resolution=high \
--db-attach=yes --suppressions=Misc/valgrind-python.supp"
# Get args
case $@ in
*--all-configs64*)
CONFIGS=$CONFIGS_64
;;
*--all-configs32*)
CONFIGS=$CONFIGS_32
;;
*)
CONFIGS="auto"
;;
esac
# gmake required
GMAKE=`which gmake`
if [ X"$GMAKE" = X"" ]; then
GMAKE=make
fi
# Pretty print configurations
print_config ()
{
len=`echo $@ | wc -c`
margin="#%"`expr \( 74 - $len \) / 2`"s"
echo ""
echo "# ========================================================================"
printf $margin ""
echo $@
echo "# ========================================================================"
echo ""
}
cd ..
# test_decimal: refleak, regular and Valgrind tests
for args in "--without-threads" ""; do
for config in $CONFIGS; do
unset PYTHON_DECIMAL_WITH_MACHINE
libmpdec_config=$config
if [ X"$config" != X"auto" ]; then
PYTHON_DECIMAL_WITH_MACHINE=$config
export PYTHON_DECIMAL_WITH_MACHINE
else
libmpdec_config=""
fi
############ refleak tests ###########
print_config "refleak tests: config=$config" $args
printf "\nbuilding python ...\n\n"
cd ../../
$GMAKE distclean > /dev/null 2>&1
./configure CFLAGS="$ADD_CFLAGS" LDFLAGS="$ADD_LDFLAGS" --with-pydebug $args > /dev/null 2>&1
$GMAKE | grep _decimal
printf "\n\n# ======================== refleak tests ===========================\n\n"
./python -m test -uall -R 2:2 test_decimal
############ regular tests ###########
print_config "regular tests: config=$config" $args
printf "\nbuilding python ...\n\n"
$GMAKE distclean > /dev/null 2>&1
./configure CFLAGS="$ADD_CFLAGS" LDFLAGS="$ADD_LDFLAGS" $args > /dev/null 2>&1
$GMAKE | grep _decimal
printf "\n\n# ======================== regular tests ===========================\n\n"
./python -m test -uall test_decimal
########### valgrind tests ###########
valgrind=$VALGRIND
case "$config" in
# Valgrind has no support for 80 bit long double arithmetic.
ppro) valgrind= ;;
auto) case `uname -m` in
i386|i486|i586|i686) valgrind= ;;
esac
esac
print_config "valgrind tests: config=$config" $args
printf "\nbuilding python ...\n\n"
$GMAKE distclean > /dev/null 2>&1
./configure CFLAGS="$ADD_CFLAGS" LDFLAGS="$ADD_LDFLAGS" --without-pymalloc $args > /dev/null 2>&1
$GMAKE | grep _decimal
printf "\n\n# ======================== valgrind tests ===========================\n\n"
$valgrind ./python -m test -uall test_decimal
cd Modules/_decimal
done
done
# deccheck
cd ../../
for config in $CONFIGS; do
for args in "--without-threads" ""; do
unset PYTHON_DECIMAL_WITH_MACHINE
if [ X"$config" != X"auto" ]; then
PYTHON_DECIMAL_WITH_MACHINE=$config
export PYTHON_DECIMAL_WITH_MACHINE
fi
############ debug ############
print_config "deccheck: config=$config --with-pydebug" $args
printf "\nbuilding python ...\n\n"
$GMAKE distclean > /dev/null 2>&1
./configure CFLAGS="$ADD_CFLAGS" LDFLAGS="$ADD_LDFLAGS" --with-pydebug $args > /dev/null 2>&1
$GMAKE | grep _decimal
printf "\n\n# ========================== debug ===========================\n\n"
./python Modules/_decimal/tests/deccheck.py
########### regular ###########
print_config "deccheck: config=$config " $args
printf "\nbuilding python ...\n\n"
$GMAKE distclean > /dev/null 2>&1
./configure CFLAGS="$ADD_CFLAGS" LDFLAGS="$ADD_LDFLAGS" $args > /dev/null 2>&1
$GMAKE | grep _decimal
printf "\n\n# ======================== regular ===========================\n\n"
./python Modules/_decimal/tests/deccheck.py
########### valgrind ###########
valgrind=$VALGRIND
case "$config" in
# Valgrind has no support for 80 bit long double arithmetic.
ppro) valgrind= ;;
auto) case `uname -m` in
i386|i486|i586|i686) valgrind= ;;
esac
esac
print_config "valgrind deccheck: config=$config " $args
printf "\nbuilding python ...\n\n"
$GMAKE distclean > /dev/null 2>&1
./configure CFLAGS="$ADD_CFLAGS" LDFLAGS="$ADD_LDFLAGS" --without-pymalloc $args > /dev/null 2>&1
$GMAKE | grep _decimal
printf "\n\n# ======================== valgrind ==========================\n\n"
$valgrind ./python Modules/_decimal/tests/deccheck.py
done
done
| 5,334 | 177 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Modules/_decimal/tests/randfloat.py | # Copyright (c) 2010 Python Software Foundation. All Rights Reserved.
# Adapted from Python's Lib/test/test_strtod.py (by Mark Dickinson)
# More test cases for deccheck.py.
import random
TEST_SIZE = 2
def test_short_halfway_cases():
# exact halfway cases with a small number of significant digits
for k in 0, 5, 10, 15, 20:
# upper = smallest integer >= 2**54/5**k
upper = -(-2**54//5**k)
# lower = smallest odd number >= 2**53/5**k
lower = -(-2**53//5**k)
if lower % 2 == 0:
lower += 1
for i in range(10 * TEST_SIZE):
# Select a random odd n in [2**53/5**k,
# 2**54/5**k). Then n * 10**k gives a halfway case
# with small number of significant digits.
n, e = random.randrange(lower, upper, 2), k
# Remove any additional powers of 5.
while n % 5 == 0:
n, e = n // 5, e + 1
assert n % 10 in (1, 3, 7, 9)
# Try numbers of the form n * 2**p2 * 10**e, p2 >= 0,
# until n * 2**p2 has more than 20 significant digits.
digits, exponent = n, e
while digits < 10**20:
s = '{}e{}'.format(digits, exponent)
yield s
# Same again, but with extra trailing zeros.
s = '{}e{}'.format(digits * 10**40, exponent - 40)
yield s
digits *= 2
# Try numbers of the form n * 5**p2 * 10**(e - p5), p5
# >= 0, with n * 5**p5 < 10**20.
digits, exponent = n, e
while digits < 10**20:
s = '{}e{}'.format(digits, exponent)
yield s
# Same again, but with extra trailing zeros.
s = '{}e{}'.format(digits * 10**40, exponent - 40)
yield s
digits *= 5
exponent -= 1
def test_halfway_cases():
# test halfway cases for the round-half-to-even rule
for i in range(1000):
for j in range(TEST_SIZE):
# bit pattern for a random finite positive (or +0.0) float
bits = random.randrange(2047*2**52)
# convert bit pattern to a number of the form m * 2**e
e, m = divmod(bits, 2**52)
if e:
m, e = m + 2**52, e - 1
e -= 1074
# add 0.5 ulps
m, e = 2*m + 1, e - 1
# convert to a decimal string
if e >= 0:
digits = m << e
exponent = 0
else:
# m * 2**e = (m * 5**-e) * 10**e
digits = m * 5**-e
exponent = e
s = '{}e{}'.format(digits, exponent)
yield s
def test_boundaries():
# boundaries expressed as triples (n, e, u), where
# n*10**e is an approximation to the boundary value and
# u*10**e is 1ulp
boundaries = [
(10000000000000000000, -19, 1110), # a power of 2 boundary (1.0)
(17976931348623159077, 289, 1995), # overflow boundary (2.**1024)
(22250738585072013831, -327, 4941), # normal/subnormal (2.**-1022)
(0, -327, 4941), # zero
]
for n, e, u in boundaries:
for j in range(1000):
for i in range(TEST_SIZE):
digits = n + random.randrange(-3*u, 3*u)
exponent = e
s = '{}e{}'.format(digits, exponent)
yield s
n *= 10
u *= 10
e -= 1
def test_underflow_boundary():
# test values close to 2**-1075, the underflow boundary; similar
# to boundary_tests, except that the random error doesn't scale
# with n
for exponent in range(-400, -320):
base = 10**-exponent // 2**1075
for j in range(TEST_SIZE):
digits = base + random.randrange(-1000, 1000)
s = '{}e{}'.format(digits, exponent)
yield s
def test_bigcomp():
for ndigs in 5, 10, 14, 15, 16, 17, 18, 19, 20, 40, 41, 50:
dig10 = 10**ndigs
for i in range(100 * TEST_SIZE):
digits = random.randrange(dig10)
exponent = random.randrange(-400, 400)
s = '{}e{}'.format(digits, exponent)
yield s
def test_parsing():
# make '0' more likely to be chosen than other digits
digits = '000000123456789'
signs = ('+', '-', '')
# put together random short valid strings
# \d*[.\d*]?e
for i in range(1000):
for j in range(TEST_SIZE):
s = random.choice(signs)
intpart_len = random.randrange(5)
s += ''.join(random.choice(digits) for _ in range(intpart_len))
if random.choice([True, False]):
s += '.'
fracpart_len = random.randrange(5)
s += ''.join(random.choice(digits)
for _ in range(fracpart_len))
else:
fracpart_len = 0
if random.choice([True, False]):
s += random.choice(['e', 'E'])
s += random.choice(signs)
exponent_len = random.randrange(1, 4)
s += ''.join(random.choice(digits)
for _ in range(exponent_len))
if intpart_len + fracpart_len:
yield s
test_particular = [
# squares
'1.00000000100000000025',
'1.0000000000000000000000000100000000000000000000000' #...
'00025',
'1.0000000000000000000000000000000000000000000010000' #...
'0000000000000000000000000000000000000000025',
'1.0000000000000000000000000000000000000000000000000' #...
'000001000000000000000000000000000000000000000000000' #...
'000000000025',
'0.99999999900000000025',
'0.9999999999999999999999999999999999999999999999999' #...
'999000000000000000000000000000000000000000000000000' #...
'000025',
'0.9999999999999999999999999999999999999999999999999' #...
'999999999999999999999999999999999999999999999999999' #...
'999999999999999999999999999999999999999990000000000' #...
'000000000000000000000000000000000000000000000000000' #...
'000000000000000000000000000000000000000000000000000' #...
'0000000000000000000000000000025',
'1.0000000000000000000000000000000000000000000000000' #...
'000000000000000000000000000000000000000000000000000' #...
'100000000000000000000000000000000000000000000000000' #...
'000000000000000000000000000000000000000000000000001',
'1.0000000000000000000000000000000000000000000000000' #...
'000000000000000000000000000000000000000000000000000' #...
'500000000000000000000000000000000000000000000000000' #...
'000000000000000000000000000000000000000000000000005',
'1.0000000000000000000000000000000000000000000000000' #...
'000000000100000000000000000000000000000000000000000' #...
'000000000000000000250000000000000002000000000000000' #...
'000000000000000000000000000000000000000000010000000' #...
'000000000000000000000000000000000000000000000000000' #...
'0000000000000000001',
'1.0000000000000000000000000000000000000000000000000' #...
'000000000100000000000000000000000000000000000000000' #...
'000000000000000000249999999999999999999999999999999' #...
'999999999999979999999999999999999999999999999999999' #...
'999999999999999999999900000000000000000000000000000' #...
'000000000000000000000000000000000000000000000000000' #...
'00000000000000000000000001',
'0.9999999999999999999999999999999999999999999999999' #...
'999999999900000000000000000000000000000000000000000' #...
'000000000000000000249999999999999998000000000000000' #...
'000000000000000000000000000000000000000000010000000' #...
'000000000000000000000000000000000000000000000000000' #...
'0000000000000000001',
'0.9999999999999999999999999999999999999999999999999' #...
'999999999900000000000000000000000000000000000000000' #...
'000000000000000000250000001999999999999999999999999' #...
'999999999999999999999999999999999990000000000000000' #...
'000000000000000000000000000000000000000000000000000' #...
'1',
# tough cases for ln etc.
'1.000000000000000000000000000000000000000000000000' #...
'00000000000000000000000000000000000000000000000000' #...
'00100000000000000000000000000000000000000000000000' #...
'00000000000000000000000000000000000000000000000000' #...
'0001',
'0.999999999999999999999999999999999999999999999999' #...
'99999999999999999999999999999999999999999999999999' #...
'99899999999999999999999999999999999999999999999999' #...
'99999999999999999999999999999999999999999999999999' #...
'99999999999999999999999999999999999999999999999999' #...
'9999'
]
TESTCASES = [
[x for x in test_short_halfway_cases()],
[x for x in test_halfway_cases()],
[x for x in test_boundaries()],
[x for x in test_underflow_boundary()],
[x for x in test_bigcomp()],
[x for x in test_parsing()],
test_particular
]
def un_randfloat():
for i in range(1000):
l = random.choice(TESTCASES[:6])
yield random.choice(l)
for v in test_particular:
yield v
def bin_randfloat():
for i in range(1000):
l1 = random.choice(TESTCASES)
l2 = random.choice(TESTCASES)
yield random.choice(l1), random.choice(l2)
def tern_randfloat():
for i in range(1000):
l1 = random.choice(TESTCASES)
l2 = random.choice(TESTCASES)
l3 = random.choice(TESTCASES)
yield random.choice(l1), random.choice(l2), random.choice(l3)
| 9,668 | 251 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Modules/_decimal/tests/formathelper.py | #
# Copyright (c) 2008-2012 Stefan Krah. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# 1. Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS "AS IS" AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
# OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
# OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
# SUCH DAMAGE.
#
# Generate PEP-3101 format strings.
import os, sys, locale, random
import platform, subprocess
from test.support import import_fresh_module
from distutils.spawn import find_executable
C = import_fresh_module('decimal', fresh=['_decimal'])
P = import_fresh_module('decimal', blocked=['_decimal'])
windows_lang_strings = [
"chinese", "chinese-simplified", "chinese-traditional", "czech", "danish",
"dutch", "belgian", "english", "australian", "canadian", "english-nz",
"english-uk", "english-us", "finnish", "french", "french-belgian",
"french-canadian", "french-swiss", "german", "german-austrian",
"german-swiss", "greek", "hungarian", "icelandic", "italian", "italian-swiss",
"japanese", "korean", "norwegian", "norwegian-bokmal", "norwegian-nynorsk",
"polish", "portuguese", "portuguese-brazil", "russian", "slovak", "spanish",
"spanish-mexican", "spanish-modern", "swedish", "turkish",
]
preferred_encoding = {
'cs_CZ': 'ISO8859-2',
'cs_CZ.iso88592': 'ISO8859-2',
'czech': 'ISO8859-2',
'eesti': 'ISO8859-1',
'estonian': 'ISO8859-1',
'et_EE': 'ISO8859-15',
'et_EE.ISO-8859-15': 'ISO8859-15',
'et_EE.iso885915': 'ISO8859-15',
'et_EE.iso88591': 'ISO8859-1',
'fi_FI.iso88591': 'ISO8859-1',
'fi_FI': 'ISO8859-15',
'fi_FI@euro': 'ISO8859-15',
'fi_FI.iso885915@euro': 'ISO8859-15',
'finnish': 'ISO8859-1',
'lv_LV': 'ISO8859-13',
'lv_LV.iso885913': 'ISO8859-13',
'nb_NO': 'ISO8859-1',
'nb_NO.iso88591': 'ISO8859-1',
'bokmal': 'ISO8859-1',
'nn_NO': 'ISO8859-1',
'nn_NO.iso88591': 'ISO8859-1',
'no_NO': 'ISO8859-1',
'norwegian': 'ISO8859-1',
'nynorsk': 'ISO8859-1',
'ru_RU': 'ISO8859-5',
'ru_RU.iso88595': 'ISO8859-5',
'russian': 'ISO8859-5',
'ru_RU.KOI8-R': 'KOI8-R',
'ru_RU.koi8r': 'KOI8-R',
'ru_RU.CP1251': 'CP1251',
'ru_RU.cp1251': 'CP1251',
'sk_SK': 'ISO8859-2',
'sk_SK.iso88592': 'ISO8859-2',
'slovak': 'ISO8859-2',
'sv_FI': 'ISO8859-1',
'sv_FI.iso88591': 'ISO8859-1',
'sv_FI@euro': 'ISO8859-15',
'sv_FI.iso885915@euro': 'ISO8859-15',
'uk_UA': 'KOI8-U',
'uk_UA.koi8u': 'KOI8-U'
}
integers = [
"",
"1",
"12",
"123",
"1234",
"12345",
"123456",
"1234567",
"12345678",
"123456789",
"1234567890",
"12345678901",
"123456789012",
"1234567890123",
"12345678901234",
"123456789012345",
"1234567890123456",
"12345678901234567",
"123456789012345678",
"1234567890123456789",
"12345678901234567890",
"123456789012345678901",
"1234567890123456789012",
]
numbers = [
"0", "-0", "+0",
"0.0", "-0.0", "+0.0",
"0e0", "-0e0", "+0e0",
".0", "-.0",
".1", "-.1",
"1.1", "-1.1",
"1e1", "-1e1"
]
# Get the list of available locales.
if platform.system() == 'Windows':
locale_list = windows_lang_strings
else:
locale_list = ['C']
if os.path.isfile("/var/lib/locales/supported.d/local"):
# On Ubuntu, `locale -a` gives the wrong case for some locales,
# so we get the correct names directly:
with open("/var/lib/locales/supported.d/local") as f:
locale_list = [loc.split()[0] for loc in f.readlines() \
if not loc.startswith('#')]
elif find_executable('locale'):
locale_list = subprocess.Popen(["locale", "-a"],
stdout=subprocess.PIPE).communicate()[0]
try:
locale_list = locale_list.decode()
except UnicodeDecodeError:
# Some distributions insist on using latin-1 characters
# in their locale names.
locale_list = locale_list.decode('latin-1')
locale_list = locale_list.split('\n')
try:
locale_list.remove('')
except ValueError:
pass
# Debian
if os.path.isfile("/etc/locale.alias"):
with open("/etc/locale.alias") as f:
while 1:
try:
line = f.readline()
except UnicodeDecodeError:
continue
if line == "":
break
if line.startswith('#'):
continue
x = line.split()
if len(x) == 2:
if x[0] in locale_list:
locale_list.remove(x[0])
# FreeBSD
if platform.system() == 'FreeBSD':
# http://www.freebsd.org/cgi/query-pr.cgi?pr=142173
# en_GB.US-ASCII has 163 as the currency symbol.
for loc in ['it_CH.ISO8859-1', 'it_CH.ISO8859-15', 'it_CH.UTF-8',
'it_IT.ISO8859-1', 'it_IT.ISO8859-15', 'it_IT.UTF-8',
'sl_SI.ISO8859-2', 'sl_SI.UTF-8',
'en_GB.US-ASCII']:
try:
locale_list.remove(loc)
except ValueError:
pass
# Print a testcase in the format of the IBM tests (for runtest.c):
def get_preferred_encoding():
loc = locale.setlocale(locale.LC_CTYPE)
if loc in preferred_encoding:
return preferred_encoding[loc]
else:
return locale.getpreferredencoding()
def printit(testno, s, fmt, encoding=None):
if not encoding:
encoding = get_preferred_encoding()
try:
result = format(P.Decimal(s), fmt)
fmt = str(fmt.encode(encoding))[2:-1]
result = str(result.encode(encoding))[2:-1]
if "'" in result:
sys.stdout.write("xfmt%d format %s '%s' -> \"%s\"\n"
% (testno, s, fmt, result))
else:
sys.stdout.write("xfmt%d format %s '%s' -> '%s'\n"
% (testno, s, fmt, result))
except Exception as err:
sys.stderr.write("%s %s %s\n" % (err, s, fmt))
# Check if an integer can be converted to a valid fill character.
def check_fillchar(i):
try:
c = chr(i)
c.encode('utf-8').decode()
format(P.Decimal(0), c + '<19g')
return c
except:
return None
# Generate all unicode characters that are accepted as
# fill characters by decimal.py.
def all_fillchars():
for i in range(0, 0x110002):
c = check_fillchar(i)
if c: yield c
# Return random fill character.
def rand_fillchar():
while 1:
i = random.randrange(0, 0x110002)
c = check_fillchar(i)
if c: return c
# Generate random format strings
# [[fill]align][sign][#][0][width][.precision][type]
def rand_format(fill, typespec='EeGgFfn%'):
active = sorted(random.sample(range(7), random.randrange(8)))
have_align = 0
s = ''
for elem in active:
if elem == 0: # fill+align
s += fill
s += random.choice('<>=^')
have_align = 1
elif elem == 1: # sign
s += random.choice('+- ')
elif elem == 2 and not have_align: # zeropad
s += '0'
elif elem == 3: # width
s += str(random.randrange(1, 100))
elif elem == 4: # thousands separator
s += ','
elif elem == 5: # prec
s += '.'
s += str(random.randrange(100))
elif elem == 6:
if 4 in active: c = typespec.replace('n', '')
else: c = typespec
s += random.choice(c)
return s
# Partially brute force all possible format strings containing a thousands
# separator. Fall back to random where the runtime would become excessive.
# [[fill]align][sign][#][0][width][,][.precision][type]
def all_format_sep():
for align in ('', '<', '>', '=', '^'):
for fill in ('', 'x'):
if align == '': fill = ''
for sign in ('', '+', '-', ' '):
for zeropad in ('', '0'):
if align != '': zeropad = ''
for width in ['']+[str(y) for y in range(1, 15)]+['101']:
for prec in ['']+['.'+str(y) for y in range(15)]:
# for type in ('', 'E', 'e', 'G', 'g', 'F', 'f', '%'):
type = random.choice(('', 'E', 'e', 'G', 'g', 'F', 'f', '%'))
yield ''.join((fill, align, sign, zeropad, width, ',', prec, type))
# Partially brute force all possible format strings with an 'n' specifier.
# [[fill]align][sign][#][0][width][,][.precision][type]
def all_format_loc():
for align in ('', '<', '>', '=', '^'):
for fill in ('', 'x'):
if align == '': fill = ''
for sign in ('', '+', '-', ' '):
for zeropad in ('', '0'):
if align != '': zeropad = ''
for width in ['']+[str(y) for y in range(1, 20)]+['101']:
for prec in ['']+['.'+str(y) for y in range(1, 20)]:
yield ''.join((fill, align, sign, zeropad, width, prec, 'n'))
# Generate random format strings with a unicode fill character
# [[fill]align][sign][#][0][width][,][.precision][type]
def randfill(fill):
active = sorted(random.sample(range(5), random.randrange(6)))
s = ''
s += str(fill)
s += random.choice('<>=^')
for elem in active:
if elem == 0: # sign
s += random.choice('+- ')
elif elem == 1: # width
s += str(random.randrange(1, 100))
elif elem == 2: # thousands separator
s += ','
elif elem == 3: # prec
s += '.'
s += str(random.randrange(100))
elif elem == 4:
if 2 in active: c = 'EeGgFf%'
else: c = 'EeGgFfn%'
s += random.choice(c)
return s
# Generate random format strings with random locale setting
# [[fill]align][sign][#][0][width][,][.precision][type]
def rand_locale():
try:
loc = random.choice(locale_list)
locale.setlocale(locale.LC_ALL, loc)
except locale.Error as err:
pass
active = sorted(random.sample(range(5), random.randrange(6)))
s = ''
have_align = 0
for elem in active:
if elem == 0: # fill+align
s += chr(random.randrange(32, 128))
s += random.choice('<>=^')
have_align = 1
elif elem == 1: # sign
s += random.choice('+- ')
elif elem == 2 and not have_align: # zeropad
s += '0'
elif elem == 3: # width
s += str(random.randrange(1, 100))
elif elem == 4: # prec
s += '.'
s += str(random.randrange(100))
s += 'n'
return s
| 11,559 | 343 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Modules/_decimal/tests/runall.bat | @ECHO OFF
rem Test all machine configurations, pydebug, refleaks, release build.
cd ..\..\..\
echo.
echo # ======================================================================
echo # Building Python
echo # ======================================================================
echo.
call "%VS100COMNTOOLS%\..\..\VC\vcvarsall.bat" x64
msbuild /noconsolelogger /target:clean PCbuild\pcbuild.sln /p:Configuration=Release /p:PlatformTarget=x64
msbuild /noconsolelogger /target:clean PCbuild\pcbuild.sln /p:Configuration=Debug /p:PlatformTarget=x64
msbuild /noconsolelogger PCbuild\pcbuild.sln /p:Configuration=Release /p:Platform=x64
msbuild /noconsolelogger PCbuild\pcbuild.sln /p:Configuration=Debug /p:Platform=x64
call "%VS100COMNTOOLS%\..\..\VC\vcvarsall.bat" x86
msbuild /noconsolelogger PCbuild\pcbuild.sln /p:Configuration=Release /p:Platform=Win32
msbuild /noconsolelogger PCbuild\pcbuild.sln /p:Configuration=Debug /p:Platform=Win32
echo.
echo.
echo.
echo # ======================================================================
echo # test_decimal: platform=x64
echo # ======================================================================
echo.
cd PCbuild\amd64
echo # ==================== refleak tests =======================
echo.
python_d.exe -m test -uall -R 2:2 test_decimal
echo.
echo.
echo # ==================== regular tests =======================
echo.
python.exe -m test -uall test_decimal
echo.
echo.
cd ..
echo.
echo # ======================================================================
echo # test_decimal: platform=x86
echo # ======================================================================
echo.
echo # ==================== refleak tests =======================
echo.
python_d.exe -m test -uall -R 2:2 test_decimal
echo.
echo.
echo # ==================== regular tests =======================
echo.
python.exe -m test -uall test_decimal
echo.
echo.
cd amd64
echo.
echo # ======================================================================
echo # deccheck: platform=x64
echo # ======================================================================
echo.
echo # ==================== debug build =======================
echo.
python_d.exe ..\..\Modules\_decimal\tests\deccheck.py
echo.
echo.
echo # =================== release build ======================
echo.
python.exe ..\..\Modules\_decimal\tests\deccheck.py
echo.
echo.
cd ..
echo.
echo # ======================================================================
echo # deccheck: platform=x86
echo # ======================================================================
echo.
echo.
echo # ==================== debug build =======================
echo.
python_d.exe ..\Modules\_decimal\tests\deccheck.py
echo.
echo.
echo # =================== release build ======================
echo.
python.exe ..\Modules\_decimal\tests\deccheck.py
echo.
echo.
cd ..\Modules\_decimal\tests
| 3,012 | 112 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Modules/_sqlite/prepare_protocol.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:8;coding:utf-8 -*-â
âvi: set net ft=c ts=4 sts=4 sw=4 fenc=utf-8 :viâ
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ¡
â â
â Copyright (C) 2005-2010 Gerhard Häring <[email protected]> â
â â
â This file is part of pysqlite. â
â â
â This software is provided 'as-is', without any express or implied â
â warranty. In no event will the authors be held liable for any damages â
â arising from the use of this software. â
â â
â Permission is granted to anyone to use this software for any purpose, â
â including commercial applications, and to alter it and redistribute it â
â freely, subject to the following restrictions: â
â â
â 1. The origin of this software must not be misrepresented; you must not â
â claim that you wrote the original software. If you use this software â
â in a product, an acknowledgment in the product documentation would be â
â appreciated but is not required. â
â 2. Altered source versions must be plainly marked as such, and must not be â
â misrepresented as being the original software. â
â 3. This notice may not be removed or altered from any source distribution. â
â â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
#include "third_party/python/Modules/_sqlite/prepare_protocol.h"
asm(".ident\t\"\\n\\n\
pysqlite (zlib license)\\n\
Copyright (C) 2005-2010 Gerhard Häring <[email protected]>\"");
asm(".include \"libc/disclaimer.inc\"");
/* clang-format off */
int pysqlite_prepare_protocol_init(pysqlite_PrepareProtocol* self, PyObject* args, PyObject* kwargs)
{
return 0;
}
void pysqlite_prepare_protocol_dealloc(pysqlite_PrepareProtocol* self)
{
Py_TYPE(self)->tp_free((PyObject*)self);
}
PyTypeObject pysqlite_PrepareProtocolType= {
PyVarObject_HEAD_INIT(NULL, 0)
"sqlite3.PrepareProtocol", /* tp_name */
sizeof(pysqlite_PrepareProtocol), /* tp_basicsize */
0, /* tp_itemsize */
(destructor)pysqlite_prepare_protocol_dealloc, /* tp_dealloc */
0, /* tp_print */
0, /* tp_getattr */
0, /* tp_setattr */
0, /* tp_reserved */
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 */
(initproc)pysqlite_prepare_protocol_init, /* tp_init */
0, /* tp_alloc */
0, /* tp_new */
0 /* tp_free */
};
extern int pysqlite_prepare_protocol_setup_types(void)
{
pysqlite_PrepareProtocolType.tp_new = PyType_GenericNew;
Py_TYPE(&pysqlite_PrepareProtocolType)= &PyType_Type;
return PyType_Ready(&pysqlite_PrepareProtocolType);
}
| 6,002 | 92 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Modules/_sqlite/util.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:8;coding:utf-8 -*-â
âvi: set net ft=c ts=4 sts=4 sw=4 fenc=utf-8 :viâ
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ¡
â â
â Copyright (C) 2005-2010 Gerhard Häring <[email protected]> â
â â
â This file is part of pysqlite. â
â â
â This software is provided 'as-is', without any express or implied â
â warranty. In no event will the authors be held liable for any damages â
â arising from the use of this software. â
â â
â Permission is granted to anyone to use this software for any purpose, â
â including commercial applications, and to alter it and redistribute it â
â freely, subject to the following restrictions: â
â â
â 1. The origin of this software must not be misrepresented; you must not â
â claim that you wrote the original software. If you use this software â
â in a product, an acknowledgment in the product documentation would be â
â appreciated but is not required. â
â 2. Altered source versions must be plainly marked as such, and must not be â
â misrepresented as being the original software. â
â 3. This notice may not be removed or altered from any source distribution. â
â â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
#include "third_party/python/Modules/_sqlite/connection.h"
#include "third_party/python/Modules/_sqlite/module.h"
asm(".ident\t\"\\n\\n\
pysqlite (zlib license)\\n\
Copyright (C) 2005-2010 Gerhard Häring <[email protected]>\"");
asm(".include \"libc/disclaimer.inc\"");
/* clang-format off */
int pysqlite_step(sqlite3_stmt* statement, pysqlite_Connection* connection)
{
int rc;
if (statement == NULL) {
/* this is a workaround for SQLite 3.5 and later. it now apparently
* returns NULL for "no-operation" statements */
rc = SQLITE_OK;
} else {
Py_BEGIN_ALLOW_THREADS
rc = sqlite3_step(statement);
Py_END_ALLOW_THREADS
}
return rc;
}
/**
* Checks the SQLite error code and sets the appropriate DB-API exception.
* Returns the error code (0 means no error occurred).
*/
int _pysqlite_seterror(sqlite3* db, sqlite3_stmt* st)
{
int errorcode;
/* SQLite often doesn't report anything useful, unless you reset the statement first */
if (st != NULL) {
(void)sqlite3_reset(st);
}
errorcode = sqlite3_errcode(db);
switch (errorcode)
{
case SQLITE_OK:
PyErr_Clear();
break;
case SQLITE_INTERNAL:
case SQLITE_NOTFOUND:
PyErr_SetString(pysqlite_InternalError, sqlite3_errmsg(db));
break;
case SQLITE_NOMEM:
(void)PyErr_NoMemory();
break;
case SQLITE_ERROR:
case SQLITE_PERM:
case SQLITE_ABORT:
case SQLITE_BUSY:
case SQLITE_LOCKED:
case SQLITE_READONLY:
case SQLITE_INTERRUPT:
case SQLITE_IOERR:
case SQLITE_FULL:
case SQLITE_CANTOPEN:
case SQLITE_PROTOCOL:
case SQLITE_EMPTY:
case SQLITE_SCHEMA:
PyErr_SetString(pysqlite_OperationalError, sqlite3_errmsg(db));
break;
case SQLITE_CORRUPT:
PyErr_SetString(pysqlite_DatabaseError, sqlite3_errmsg(db));
break;
case SQLITE_TOOBIG:
PyErr_SetString(pysqlite_DataError, sqlite3_errmsg(db));
break;
case SQLITE_CONSTRAINT:
case SQLITE_MISMATCH:
PyErr_SetString(pysqlite_IntegrityError, sqlite3_errmsg(db));
break;
case SQLITE_MISUSE:
PyErr_SetString(pysqlite_ProgrammingError, sqlite3_errmsg(db));
break;
default:
PyErr_SetString(pysqlite_DatabaseError, sqlite3_errmsg(db));
break;
}
return errorcode;
}
#ifdef WORDS_BIGENDIAN
# define IS_LITTLE_ENDIAN 0
#else
# define IS_LITTLE_ENDIAN 1
#endif
PyObject *
_pysqlite_long_from_int64(sqlite_int64 value)
{
# if SIZEOF_LONG_LONG < 8
if (value > PY_LLONG_MAX || value < PY_LLONG_MIN) {
return _PyLong_FromByteArray(&value, sizeof(value),
IS_LITTLE_ENDIAN, 1 /* signed */);
}
# endif
# if SIZEOF_LONG < SIZEOF_LONG_LONG
if (value > LONG_MAX || value < LONG_MIN)
return PyLong_FromLongLong(value);
# endif
return PyLong_FromLong(Py_SAFE_DOWNCAST(value, sqlite_int64, long));
}
sqlite_int64
_pysqlite_long_as_int64(PyObject * py_val)
{
int overflow;
long long value = PyLong_AsLongLongAndOverflow(py_val, &overflow);
if (value == -1 && PyErr_Occurred())
return -1;
if (!overflow) {
# if SIZEOF_LONG_LONG > 8
if (-0x8000000000000000LL <= value && value <= 0x7FFFFFFFFFFFFFFFLL)
# endif
return value;
}
else if (sizeof(value) < sizeof(sqlite_int64)) {
sqlite_int64 int64val;
if (_PyLong_AsByteArray((PyLongObject *)py_val,
(unsigned char *)&int64val, sizeof(int64val),
IS_LITTLE_ENDIAN, 1 /* signed */) >= 0) {
return int64val;
}
}
PyErr_SetString(PyExc_OverflowError,
"Python int too large to convert to SQLite INTEGER");
return -1;
}
| 6,420 | 162 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Modules/_sqlite/util.h | #ifndef PYSQLITE_UTIL_H
#define PYSQLITE_UTIL_H
/* clang-format off */
#include "third_party/python/Include/Python.h"
#include "third_party/python/Include/pythread.h"
#include "third_party/python/Modules/_sqlite/connection.h"
#include "third_party/sqlite3/sqlite3.h"
int pysqlite_step(sqlite3_stmt* statement, pysqlite_Connection* connection);
/**
* Checks the SQLite error code and sets the appropriate DB-API exception.
* Returns the error code (0 means no error occurred).
*/
int _pysqlite_seterror(sqlite3* db, sqlite3_stmt* st);
PyObject * _pysqlite_long_from_int64(sqlite_int64 value);
sqlite_int64 _pysqlite_long_as_int64(PyObject * value);
#endif
| 662 | 21 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Modules/_sqlite/statement.h | #ifndef PYSQLITE_STATEMENT_H
#define PYSQLITE_STATEMENT_H
#include "third_party/python/Include/Python.h"
#include "third_party/python/Modules/_sqlite/connection.h"
#include "third_party/sqlite3/sqlite3.h"
/* clang-format off */
#define PYSQLITE_TOO_MUCH_SQL (-100)
#define PYSQLITE_SQL_WRONG_TYPE (-101)
typedef struct
{
PyObject_HEAD
sqlite3* db;
sqlite3_stmt* st;
PyObject* sql;
int in_use;
int is_dml;
PyObject* in_weakreflist; /* List of weak references */
} pysqlite_Statement;
extern PyTypeObject pysqlite_StatementType;
int pysqlite_statement_create(pysqlite_Statement* self, pysqlite_Connection* connection, PyObject* sql);
void pysqlite_statement_dealloc(pysqlite_Statement* self);
int pysqlite_statement_bind_parameter(pysqlite_Statement* self, int pos, PyObject* parameter);
void pysqlite_statement_bind_parameters(pysqlite_Statement* self, PyObject* parameters);
int pysqlite_statement_recompile(pysqlite_Statement* self, PyObject* parameters);
int pysqlite_statement_finalize(pysqlite_Statement* self);
int pysqlite_statement_reset(pysqlite_Statement* self);
void pysqlite_statement_mark_dirty(pysqlite_Statement* self);
int pysqlite_statement_setup_types(void);
#endif
| 1,219 | 38 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Modules/_sqlite/cache.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:8;coding:utf-8 -*-â
âvi: set net ft=c ts=4 sts=4 sw=4 fenc=utf-8 :viâ
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ¡
â â
â Copyright (C) 2005-2010 Gerhard Häring <[email protected]> â
â â
â This file is part of pysqlite. â
â â
â This software is provided 'as-is', without any express or implied â
â warranty. In no event will the authors be held liable for any damages â
â arising from the use of this software. â
â â
â Permission is granted to anyone to use this software for any purpose, â
â including commercial applications, and to alter it and redistribute it â
â freely, subject to the following restrictions: â
â â
â 1. The origin of this software must not be misrepresented; you must not â
â claim that you wrote the original software. If you use this software â
â in a product, an acknowledgment in the product documentation would be â
â appreciated but is not required. â
â 2. Altered source versions must be plainly marked as such, and must not be â
â misrepresented as being the original software. â
â 3. This notice may not be removed or altered from any source distribution. â
â â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
#include "third_party/python/Modules/_sqlite/cache.h"
asm(".ident\t\"\\n\\n\
pysqlite (zlib license)\\n\
Copyright (C) 2005-2010 Gerhard Häring <[email protected]>\"");
asm(".include \"libc/disclaimer.inc\"");
/* clang-format off */
/* only used internally */
pysqlite_Node* pysqlite_new_node(PyObject* key, PyObject* data)
{
pysqlite_Node* node;
node = (pysqlite_Node*) (pysqlite_NodeType.tp_alloc(&pysqlite_NodeType, 0));
if (!node) {
return NULL;
}
Py_INCREF(key);
node->key = key;
Py_INCREF(data);
node->data = data;
node->prev = NULL;
node->next = NULL;
return node;
}
void pysqlite_node_dealloc(pysqlite_Node* self)
{
Py_DECREF(self->key);
Py_DECREF(self->data);
Py_TYPE(self)->tp_free((PyObject*)self);
}
int pysqlite_cache_init(pysqlite_Cache* self, PyObject* args, PyObject* kwargs)
{
PyObject* factory;
int size = 10;
self->factory = NULL;
if (!PyArg_ParseTuple(args, "O|i", &factory, &size)) {
return -1;
}
/* minimum cache size is 5 entries */
if (size < 5) {
size = 5;
}
self->size = size;
self->first = NULL;
self->last = NULL;
self->mapping = PyDict_New();
if (!self->mapping) {
return -1;
}
Py_INCREF(factory);
self->factory = factory;
self->decref_factory = 1;
return 0;
}
void pysqlite_cache_dealloc(pysqlite_Cache* self)
{
pysqlite_Node* node;
pysqlite_Node* delete_node;
if (!self->factory) {
/* constructor failed, just get out of here */
return;
}
/* iterate over all nodes and deallocate them */
node = self->first;
while (node) {
delete_node = node;
node = node->next;
Py_DECREF(delete_node);
}
if (self->decref_factory) {
Py_DECREF(self->factory);
}
Py_DECREF(self->mapping);
Py_TYPE(self)->tp_free((PyObject*)self);
}
PyObject* pysqlite_cache_get(pysqlite_Cache* self, PyObject* args)
{
PyObject* key = args;
pysqlite_Node* node;
pysqlite_Node* ptr;
PyObject* data;
node = (pysqlite_Node*)PyDict_GetItem(self->mapping, key);
if (node) {
/* an entry for this key already exists in the cache */
/* increase usage counter of the node found */
if (node->count < LONG_MAX) {
node->count++;
}
/* if necessary, reorder entries in the cache by swapping positions */
if (node->prev && node->count > node->prev->count) {
ptr = node->prev;
while (ptr->prev && node->count > ptr->prev->count) {
ptr = ptr->prev;
}
if (node->next) {
node->next->prev = node->prev;
} else {
self->last = node->prev;
}
if (node->prev) {
node->prev->next = node->next;
}
if (ptr->prev) {
ptr->prev->next = node;
} else {
self->first = node;
}
node->next = ptr;
node->prev = ptr->prev;
if (!node->prev) {
self->first = node;
}
ptr->prev = node;
}
} else {
/* There is no entry for this key in the cache, yet. We'll insert a new
* entry in the cache, and make space if necessary by throwing the
* least used item out of the cache. */
if (PyDict_Size(self->mapping) == self->size) {
if (self->last) {
node = self->last;
if (PyDict_DelItem(self->mapping, self->last->key) != 0) {
return NULL;
}
if (node->prev) {
node->prev->next = NULL;
}
self->last = node->prev;
node->prev = NULL;
Py_DECREF(node);
}
}
data = PyObject_CallFunction(self->factory, "O", key);
if (!data) {
return NULL;
}
node = pysqlite_new_node(key, data);
if (!node) {
return NULL;
}
node->prev = self->last;
Py_DECREF(data);
if (PyDict_SetItem(self->mapping, key, (PyObject*)node) != 0) {
Py_DECREF(node);
return NULL;
}
if (self->last) {
self->last->next = node;
} else {
self->first = node;
}
self->last = node;
}
Py_INCREF(node->data);
return node->data;
}
PyObject* pysqlite_cache_display(pysqlite_Cache* self, PyObject* args)
{
pysqlite_Node* ptr;
PyObject* prevkey;
PyObject* nextkey;
PyObject* display_str;
ptr = self->first;
while (ptr) {
if (ptr->prev) {
prevkey = ptr->prev->key;
} else {
prevkey = Py_None;
}
if (ptr->next) {
nextkey = ptr->next->key;
} else {
nextkey = Py_None;
}
display_str = PyUnicode_FromFormat("%S <- %S -> %S\n",
prevkey, ptr->key, nextkey);
if (!display_str) {
return NULL;
}
PyObject_Print(display_str, stdout, Py_PRINT_RAW);
Py_DECREF(display_str);
ptr = ptr->next;
}
Py_RETURN_NONE;
}
static PyMethodDef cache_methods[] = {
{"get", (PyCFunction)pysqlite_cache_get, METH_O,
PyDoc_STR("Gets an entry from the cache or calls the factory function to produce one.")},
{"display", (PyCFunction)pysqlite_cache_display, METH_NOARGS,
PyDoc_STR("For debugging only.")},
{NULL, NULL}
};
PyTypeObject pysqlite_NodeType = {
PyVarObject_HEAD_INIT(NULL, 0)
"sqlite3Node", /* tp_name */
sizeof(pysqlite_Node), /* tp_basicsize */
0, /* tp_itemsize */
(destructor)pysqlite_node_dealloc, /* tp_dealloc */
0, /* tp_print */
0, /* tp_getattr */
0, /* tp_setattr */
0, /* tp_reserved */
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)0, /* tp_init */
0, /* tp_alloc */
0, /* tp_new */
0 /* tp_free */
};
PyTypeObject pysqlite_CacheType = {
PyVarObject_HEAD_INIT(NULL, 0)
"sqlite3.Cache", /* tp_name */
sizeof(pysqlite_Cache), /* tp_basicsize */
0, /* tp_itemsize */
(destructor)pysqlite_cache_dealloc, /* tp_dealloc */
0, /* tp_print */
0, /* tp_getattr */
0, /* tp_setattr */
0, /* tp_reserved */
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 */
cache_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)pysqlite_cache_init, /* tp_init */
0, /* tp_alloc */
0, /* tp_new */
0 /* tp_free */
};
extern int pysqlite_cache_setup_types(void)
{
int rc;
pysqlite_NodeType.tp_new = PyType_GenericNew;
pysqlite_CacheType.tp_new = PyType_GenericNew;
rc = PyType_Ready(&pysqlite_NodeType);
if (rc < 0) {
return rc;
}
rc = PyType_Ready(&pysqlite_CacheType);
return rc;
}
| 14,090 | 364 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Modules/_sqlite/cursor.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:8;coding:utf-8 -*-â
âvi: set net ft=c ts=4 sts=4 sw=4 fenc=utf-8 :viâ
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ¡
â â
â Copyright (C) 2005-2010 Gerhard Häring <[email protected]> â
â â
â This file is part of pysqlite. â
â â
â This software is provided 'as-is', without any express or implied â
â warranty. In no event will the authors be held liable for any damages â
â arising from the use of this software. â
â â
â Permission is granted to anyone to use this software for any purpose, â
â including commercial applications, and to alter it and redistribute it â
â freely, subject to the following restrictions: â
â â
â 1. The origin of this software must not be misrepresented; you must not â
â claim that you wrote the original software. If you use this software â
â in a product, an acknowledgment in the product documentation would be â
â appreciated but is not required. â
â 2. Altered source versions must be plainly marked as such, and must not be â
â misrepresented as being the original software. â
â 3. This notice may not be removed or altered from any source distribution. â
â â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
#include "third_party/python/Modules/_sqlite/cursor.h"
#include "third_party/python/Modules/_sqlite/module.h"
#include "third_party/python/Modules/_sqlite/util.h"
asm(".ident\t\"\\n\\n\
pysqlite (zlib license)\\n\
Copyright (C) 2005-2010 Gerhard Häring <[email protected]>\"");
asm(".include \"libc/disclaimer.inc\"");
/* clang-format off */
PyObject* pysqlite_cursor_iternext(pysqlite_Cursor* self);
static const char errmsg_fetch_across_rollback[] = "Cursor needed to be reset because of commit/rollback and can no longer be fetched from.";
static int pysqlite_cursor_init(pysqlite_Cursor* self, PyObject* args, PyObject* kwargs)
{
pysqlite_Connection* connection;
if (!PyArg_ParseTuple(args, "O!", &pysqlite_ConnectionType, &connection))
{
return -1;
}
Py_INCREF(connection);
Py_XSETREF(self->connection, connection);
Py_CLEAR(self->statement);
Py_CLEAR(self->next_row);
Py_XSETREF(self->row_cast_map, PyList_New(0));
if (!self->row_cast_map) {
return -1;
}
Py_INCREF(Py_None);
Py_XSETREF(self->description, Py_None);
Py_INCREF(Py_None);
Py_XSETREF(self->lastrowid, Py_None);
self->arraysize = 1;
self->closed = 0;
self->reset = 0;
self->rowcount = -1L;
Py_INCREF(Py_None);
Py_XSETREF(self->row_factory, Py_None);
if (!pysqlite_check_thread(self->connection)) {
return -1;
}
if (!pysqlite_connection_register_cursor(connection, (PyObject*)self)) {
return -1;
}
self->initialized = 1;
return 0;
}
static void pysqlite_cursor_dealloc(pysqlite_Cursor* self)
{
/* Reset the statement if the user has not closed the cursor */
if (self->statement) {
pysqlite_statement_reset(self->statement);
Py_DECREF(self->statement);
}
Py_XDECREF(self->connection);
Py_XDECREF(self->row_cast_map);
Py_XDECREF(self->description);
Py_XDECREF(self->lastrowid);
Py_XDECREF(self->row_factory);
Py_XDECREF(self->next_row);
if (self->in_weakreflist != NULL) {
PyObject_ClearWeakRefs((PyObject*)self);
}
Py_TYPE(self)->tp_free((PyObject*)self);
}
PyObject* _pysqlite_get_converter(PyObject* key)
{
PyObject* upcase_key;
PyObject* retval;
_Py_IDENTIFIER(upper);
upcase_key = _PyObject_CallMethodId(key, &PyId_upper, NULL);
if (!upcase_key) {
return NULL;
}
retval = PyDict_GetItem(_pysqlite_converters, upcase_key);
Py_DECREF(upcase_key);
return retval;
}
int pysqlite_build_row_cast_map(pysqlite_Cursor* self)
{
int i;
const char* type_start = (const char*)-1;
const char* pos;
const char* colname;
const char* decltype;
PyObject* py_decltype;
PyObject* converter;
PyObject* key;
if (!self->connection->detect_types) {
return 0;
}
Py_XSETREF(self->row_cast_map, PyList_New(0));
for (i = 0; i < sqlite3_column_count(self->statement->st); i++) {
converter = NULL;
if (self->connection->detect_types & PARSE_COLNAMES) {
colname = sqlite3_column_name(self->statement->st, i);
if (colname) {
for (pos = colname; *pos != 0; pos++) {
if (*pos == '[') {
type_start = pos + 1;
} else if (*pos == ']' && type_start != (const char*)-1) {
key = PyUnicode_FromStringAndSize(type_start, pos - type_start);
if (!key) {
/* creating a string failed, but it is too complicated
* to propagate the error here, we just assume there is
* no converter and proceed */
break;
}
converter = _pysqlite_get_converter(key);
Py_DECREF(key);
break;
}
}
}
}
if (!converter && self->connection->detect_types & PARSE_DECLTYPES) {
decltype = sqlite3_column_decltype(self->statement->st, i);
if (decltype) {
for (pos = decltype;;pos++) {
/* Converter names are split at '(' and blanks.
* This allows 'INTEGER NOT NULL' to be treated as 'INTEGER' and
* 'NUMBER(10)' to be treated as 'NUMBER', for example.
* In other words, it will work as people expect it to work.*/
if (*pos == ' ' || *pos == '(' || *pos == 0) {
py_decltype = PyUnicode_FromStringAndSize(decltype, pos - decltype);
if (!py_decltype) {
return -1;
}
break;
}
}
converter = _pysqlite_get_converter(py_decltype);
Py_DECREF(py_decltype);
}
}
if (!converter) {
converter = Py_None;
}
if (PyList_Append(self->row_cast_map, converter) != 0) {
if (converter != Py_None) {
Py_DECREF(converter);
}
Py_CLEAR(self->row_cast_map);
return -1;
}
}
return 0;
}
PyObject* _pysqlite_build_column_name(const char* colname)
{
const char* pos;
if (!colname) {
Py_RETURN_NONE;
}
for (pos = colname;; pos++) {
if (*pos == 0 || *pos == '[') {
if ((*pos == '[') && (pos > colname) && (*(pos-1) == ' ')) {
pos--;
}
return PyUnicode_FromStringAndSize(colname, pos - colname);
}
}
}
/*
* Returns a row from the currently active SQLite statement
*
* Precondidition:
* - sqlite3_step() has been called before and it returned SQLITE_ROW.
*/
PyObject* _pysqlite_fetch_one_row(pysqlite_Cursor* self)
{
int i, numcols;
PyObject* row;
PyObject* item = NULL;
int coltype;
PyObject* converter;
PyObject* converted;
Py_ssize_t nbytes;
PyObject* buffer;
const char* val_str;
char buf[200];
const char* colname;
PyObject* buf_bytes;
PyObject* error_obj;
if (self->reset) {
PyErr_SetString(pysqlite_InterfaceError, errmsg_fetch_across_rollback);
return NULL;
}
Py_BEGIN_ALLOW_THREADS
numcols = sqlite3_data_count(self->statement->st);
Py_END_ALLOW_THREADS
row = PyTuple_New(numcols);
if (!row)
return NULL;
for (i = 0; i < numcols; i++) {
if (self->connection->detect_types) {
converter = PyList_GetItem(self->row_cast_map, i);
if (!converter) {
converter = Py_None;
}
} else {
converter = Py_None;
}
if (converter != Py_None) {
nbytes = sqlite3_column_bytes(self->statement->st, i);
val_str = (const char*)sqlite3_column_blob(self->statement->st, i);
if (!val_str) {
Py_INCREF(Py_None);
converted = Py_None;
} else {
item = PyBytes_FromStringAndSize(val_str, nbytes);
if (!item)
goto error;
converted = PyObject_CallFunction(converter, "O", item);
Py_DECREF(item);
if (!converted)
break;
}
} else {
Py_BEGIN_ALLOW_THREADS
coltype = sqlite3_column_type(self->statement->st, i);
Py_END_ALLOW_THREADS
if (coltype == SQLITE_NULL) {
Py_INCREF(Py_None);
converted = Py_None;
} else if (coltype == SQLITE_INTEGER) {
converted = _pysqlite_long_from_int64(sqlite3_column_int64(self->statement->st, i));
} else if (coltype == SQLITE_FLOAT) {
converted = PyFloat_FromDouble(sqlite3_column_double(self->statement->st, i));
} else if (coltype == SQLITE_TEXT) {
val_str = (const char*)sqlite3_column_text(self->statement->st, i);
nbytes = sqlite3_column_bytes(self->statement->st, i);
if (self->connection->text_factory == (PyObject*)&PyUnicode_Type) {
converted = PyUnicode_FromStringAndSize(val_str, nbytes);
if (!converted) {
PyErr_Clear();
colname = sqlite3_column_name(self->statement->st, i);
if (!colname) {
colname = "<unknown column name>";
}
PyOS_snprintf(buf, sizeof(buf) - 1, "Could not decode to UTF-8 column '%s' with text '%s'",
colname , val_str);
buf_bytes = PyByteArray_FromStringAndSize(buf, strlen(buf));
if (!buf_bytes) {
PyErr_SetString(pysqlite_OperationalError, "Could not decode to UTF-8");
} else {
error_obj = PyUnicode_FromEncodedObject(buf_bytes, "ascii", "replace");
if (!error_obj) {
PyErr_SetString(pysqlite_OperationalError, "Could not decode to UTF-8");
} else {
PyErr_SetObject(pysqlite_OperationalError, error_obj);
Py_DECREF(error_obj);
}
Py_DECREF(buf_bytes);
}
}
} else if (self->connection->text_factory == (PyObject*)&PyBytes_Type) {
converted = PyBytes_FromStringAndSize(val_str, nbytes);
} else if (self->connection->text_factory == (PyObject*)&PyByteArray_Type) {
converted = PyByteArray_FromStringAndSize(val_str, nbytes);
} else {
converted = PyObject_CallFunction(self->connection->text_factory, "y#", val_str, nbytes);
}
} else {
/* coltype == SQLITE_BLOB */
nbytes = sqlite3_column_bytes(self->statement->st, i);
buffer = PyBytes_FromStringAndSize(
sqlite3_column_blob(self->statement->st, i), nbytes);
if (!buffer)
break;
converted = buffer;
}
}
if (converted) {
PyTuple_SetItem(row, i, converted);
} else {
Py_INCREF(Py_None);
PyTuple_SetItem(row, i, Py_None);
}
}
if (PyErr_Occurred())
goto error;
return row;
error:
Py_DECREF(row);
return NULL;
}
/*
* Checks if a cursor object is usable.
*
* 0 => error; 1 => ok
*/
static int check_cursor(pysqlite_Cursor* cur)
{
if (!cur->initialized) {
PyErr_SetString(pysqlite_ProgrammingError, "Base Cursor.__init__ not called.");
return 0;
}
if (cur->closed) {
PyErr_SetString(pysqlite_ProgrammingError, "Cannot operate on a closed cursor.");
return 0;
}
if (cur->locked) {
PyErr_SetString(pysqlite_ProgrammingError, "Recursive use of cursors not allowed.");
return 0;
}
return pysqlite_check_thread(cur->connection) && pysqlite_check_connection(cur->connection);
}
PyObject* _pysqlite_query_execute(pysqlite_Cursor* self, int multiple, PyObject* args)
{
PyObject* operation;
const char* operation_cstr;
Py_ssize_t operation_len;
PyObject* parameters_list = NULL;
PyObject* parameters_iter = NULL;
PyObject* parameters = NULL;
int i;
int rc;
PyObject* func_args;
PyObject* result;
int numcols;
PyObject* descriptor;
PyObject* second_argument = NULL;
sqlite_int64 lastrowid;
if (!check_cursor(self)) {
goto error;
}
self->locked = 1;
self->reset = 0;
Py_CLEAR(self->next_row);
if (multiple) {
/* executemany() */
if (!PyArg_ParseTuple(args, "OO", &operation, &second_argument)) {
goto error;
}
if (!PyUnicode_Check(operation)) {
PyErr_SetString(PyExc_ValueError, "operation parameter must be str");
goto error;
}
if (PyIter_Check(second_argument)) {
/* iterator */
Py_INCREF(second_argument);
parameters_iter = second_argument;
} else {
/* sequence */
parameters_iter = PyObject_GetIter(second_argument);
if (!parameters_iter) {
goto error;
}
}
} else {
/* execute() */
if (!PyArg_ParseTuple(args, "O|O", &operation, &second_argument)) {
goto error;
}
if (!PyUnicode_Check(operation)) {
PyErr_SetString(PyExc_ValueError, "operation parameter must be str");
goto error;
}
parameters_list = PyList_New(0);
if (!parameters_list) {
goto error;
}
if (second_argument == NULL) {
second_argument = PyTuple_New(0);
if (!second_argument) {
goto error;
}
} else {
Py_INCREF(second_argument);
}
if (PyList_Append(parameters_list, second_argument) != 0) {
Py_DECREF(second_argument);
goto error;
}
Py_DECREF(second_argument);
parameters_iter = PyObject_GetIter(parameters_list);
if (!parameters_iter) {
goto error;
}
}
if (self->statement != NULL) {
/* There is an active statement */
pysqlite_statement_reset(self->statement);
}
operation_cstr = PyUnicode_AsUTF8AndSize(operation, &operation_len);
if (operation_cstr == NULL)
goto error;
/* reset description and rowcount */
Py_INCREF(Py_None);
Py_SETREF(self->description, Py_None);
self->rowcount = 0L;
func_args = PyTuple_New(1);
if (!func_args) {
goto error;
}
Py_INCREF(operation);
if (PyTuple_SetItem(func_args, 0, operation) != 0) {
goto error;
}
if (self->statement) {
(void)pysqlite_statement_reset(self->statement);
}
Py_XSETREF(self->statement,
(pysqlite_Statement *)pysqlite_cache_get(self->connection->statement_cache, func_args));
Py_DECREF(func_args);
if (!self->statement) {
goto error;
}
if (self->statement->in_use) {
Py_SETREF(self->statement,
PyObject_New(pysqlite_Statement, &pysqlite_StatementType));
if (!self->statement) {
goto error;
}
rc = pysqlite_statement_create(self->statement, self->connection, operation);
if (rc != SQLITE_OK) {
Py_CLEAR(self->statement);
goto error;
}
}
pysqlite_statement_reset(self->statement);
pysqlite_statement_mark_dirty(self->statement);
/* We start a transaction implicitly before a DML statement.
SELECT is the only exception. See #9924. */
if (self->connection->begin_statement && self->statement->is_dml) {
if (sqlite3_get_autocommit(self->connection->db)) {
result = _pysqlite_connection_begin(self->connection);
if (!result) {
goto error;
}
Py_DECREF(result);
}
}
while (1) {
parameters = PyIter_Next(parameters_iter);
if (!parameters) {
break;
}
pysqlite_statement_mark_dirty(self->statement);
pysqlite_statement_bind_parameters(self->statement, parameters);
if (PyErr_Occurred()) {
goto error;
}
/* Keep trying the SQL statement until the schema stops changing. */
while (1) {
/* Actually execute the SQL statement. */
rc = pysqlite_step(self->statement->st, self->connection);
if (PyErr_Occurred()) {
(void)pysqlite_statement_reset(self->statement);
goto error;
}
if (rc == SQLITE_DONE || rc == SQLITE_ROW) {
/* If it worked, let's get out of the loop */
break;
}
/* Something went wrong. Re-set the statement and try again. */
rc = pysqlite_statement_reset(self->statement);
if (rc == SQLITE_SCHEMA) {
/* If this was a result of the schema changing, let's try
again. */
rc = pysqlite_statement_recompile(self->statement, parameters);
if (rc == SQLITE_OK) {
continue;
} else {
/* If the database gave us an error, promote it to Python. */
(void)pysqlite_statement_reset(self->statement);
_pysqlite_seterror(self->connection->db, NULL);
goto error;
}
} else {
if (PyErr_Occurred()) {
/* there was an error that occurred in a user-defined callback */
if (_pysqlite_enable_callback_tracebacks) {
PyErr_Print();
} else {
PyErr_Clear();
}
}
(void)pysqlite_statement_reset(self->statement);
_pysqlite_seterror(self->connection->db, NULL);
goto error;
}
}
if (pysqlite_build_row_cast_map(self) != 0) {
PyErr_SetString(pysqlite_OperationalError, "Error while building row_cast_map");
goto error;
}
if (rc == SQLITE_ROW || rc == SQLITE_DONE) {
Py_BEGIN_ALLOW_THREADS
numcols = sqlite3_column_count(self->statement->st);
Py_END_ALLOW_THREADS
if (self->description == Py_None && numcols > 0) {
Py_SETREF(self->description, PyTuple_New(numcols));
if (!self->description) {
goto error;
}
for (i = 0; i < numcols; i++) {
descriptor = PyTuple_New(7);
if (!descriptor) {
goto error;
}
PyTuple_SetItem(descriptor, 0, _pysqlite_build_column_name(sqlite3_column_name(self->statement->st, i)));
Py_INCREF(Py_None); PyTuple_SetItem(descriptor, 1, Py_None);
Py_INCREF(Py_None); PyTuple_SetItem(descriptor, 2, Py_None);
Py_INCREF(Py_None); PyTuple_SetItem(descriptor, 3, Py_None);
Py_INCREF(Py_None); PyTuple_SetItem(descriptor, 4, Py_None);
Py_INCREF(Py_None); PyTuple_SetItem(descriptor, 5, Py_None);
Py_INCREF(Py_None); PyTuple_SetItem(descriptor, 6, Py_None);
PyTuple_SetItem(self->description, i, descriptor);
}
}
}
if (self->statement->is_dml) {
self->rowcount += (long)sqlite3_changes(self->connection->db);
} else {
self->rowcount= -1L;
}
if (!multiple) {
Py_DECREF(self->lastrowid);
Py_BEGIN_ALLOW_THREADS
lastrowid = sqlite3_last_insert_rowid(self->connection->db);
Py_END_ALLOW_THREADS
self->lastrowid = _pysqlite_long_from_int64(lastrowid);
}
if (rc == SQLITE_ROW) {
if (multiple) {
PyErr_SetString(pysqlite_ProgrammingError, "executemany() can only execute DML statements.");
goto error;
}
self->next_row = _pysqlite_fetch_one_row(self);
if (self->next_row == NULL)
goto error;
} else if (rc == SQLITE_DONE && !multiple) {
pysqlite_statement_reset(self->statement);
Py_CLEAR(self->statement);
}
if (multiple) {
pysqlite_statement_reset(self->statement);
}
Py_XDECREF(parameters);
}
error:
Py_XDECREF(parameters);
Py_XDECREF(parameters_iter);
Py_XDECREF(parameters_list);
self->locked = 0;
if (PyErr_Occurred()) {
self->rowcount = -1L;
return NULL;
} else {
Py_INCREF(self);
return (PyObject*)self;
}
}
PyObject* pysqlite_cursor_execute(pysqlite_Cursor* self, PyObject* args)
{
return _pysqlite_query_execute(self, 0, args);
}
PyObject* pysqlite_cursor_executemany(pysqlite_Cursor* self, PyObject* args)
{
return _pysqlite_query_execute(self, 1, args);
}
PyObject* pysqlite_cursor_executescript(pysqlite_Cursor* self, PyObject* args)
{
PyObject* script_obj;
PyObject* script_str = NULL;
const char* script_cstr;
sqlite3_stmt* statement;
int rc;
PyObject* result;
if (!PyArg_ParseTuple(args, "O", &script_obj)) {
return NULL;
}
if (!check_cursor(self)) {
return NULL;
}
self->reset = 0;
if (PyUnicode_Check(script_obj)) {
script_cstr = PyUnicode_AsUTF8(script_obj);
if (!script_cstr) {
return NULL;
}
} else {
PyErr_SetString(PyExc_ValueError, "script argument must be unicode.");
return NULL;
}
/* commit first */
result = pysqlite_connection_commit(self->connection, NULL);
if (!result) {
goto error;
}
Py_DECREF(result);
while (1) {
Py_BEGIN_ALLOW_THREADS
rc = sqlite3_prepare(self->connection->db,
script_cstr,
-1,
&statement,
&script_cstr);
Py_END_ALLOW_THREADS
if (rc != SQLITE_OK) {
_pysqlite_seterror(self->connection->db, NULL);
goto error;
}
/* execute statement, and ignore results of SELECT statements */
rc = SQLITE_ROW;
while (rc == SQLITE_ROW) {
rc = pysqlite_step(statement, self->connection);
if (PyErr_Occurred()) {
(void)sqlite3_finalize(statement);
goto error;
}
}
if (rc != SQLITE_DONE) {
(void)sqlite3_finalize(statement);
_pysqlite_seterror(self->connection->db, NULL);
goto error;
}
rc = sqlite3_finalize(statement);
if (rc != SQLITE_OK) {
_pysqlite_seterror(self->connection->db, NULL);
goto error;
}
if (*script_cstr == (char)0) {
break;
}
}
error:
Py_XDECREF(script_str);
if (PyErr_Occurred()) {
return NULL;
} else {
Py_INCREF(self);
return (PyObject*)self;
}
}
PyObject* pysqlite_cursor_getiter(pysqlite_Cursor *self)
{
Py_INCREF(self);
return (PyObject*)self;
}
PyObject* pysqlite_cursor_iternext(pysqlite_Cursor *self)
{
PyObject* next_row_tuple;
PyObject* next_row;
int rc;
if (!check_cursor(self)) {
return NULL;
}
if (self->reset) {
PyErr_SetString(pysqlite_InterfaceError, errmsg_fetch_across_rollback);
return NULL;
}
if (!self->next_row) {
if (self->statement) {
(void)pysqlite_statement_reset(self->statement);
Py_CLEAR(self->statement);
}
return NULL;
}
next_row_tuple = self->next_row;
assert(next_row_tuple != NULL);
self->next_row = NULL;
if (self->row_factory != Py_None) {
next_row = PyObject_CallFunction(self->row_factory, "OO", self, next_row_tuple);
if (next_row == NULL) {
self->next_row = next_row_tuple;
return NULL;
}
Py_DECREF(next_row_tuple);
} else {
next_row = next_row_tuple;
}
if (self->statement) {
rc = pysqlite_step(self->statement->st, self->connection);
if (PyErr_Occurred()) {
(void)pysqlite_statement_reset(self->statement);
Py_DECREF(next_row);
return NULL;
}
if (rc != SQLITE_DONE && rc != SQLITE_ROW) {
(void)pysqlite_statement_reset(self->statement);
Py_DECREF(next_row);
_pysqlite_seterror(self->connection->db, NULL);
return NULL;
}
if (rc == SQLITE_ROW) {
self->next_row = _pysqlite_fetch_one_row(self);
if (self->next_row == NULL) {
(void)pysqlite_statement_reset(self->statement);
return NULL;
}
}
}
return next_row;
}
PyObject* pysqlite_cursor_fetchone(pysqlite_Cursor* self, PyObject* args)
{
PyObject* row;
row = pysqlite_cursor_iternext(self);
if (!row && !PyErr_Occurred()) {
Py_RETURN_NONE;
}
return row;
}
PyObject* pysqlite_cursor_fetchmany(pysqlite_Cursor* self, PyObject* args, PyObject* kwargs)
{
static char *kwlist[] = {"size", NULL, NULL};
PyObject* row;
PyObject* list;
int maxrows = self->arraysize;
int counter = 0;
if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|i:fetchmany", kwlist, &maxrows)) {
return NULL;
}
list = PyList_New(0);
if (!list) {
return NULL;
}
/* just make sure we enter the loop */
row = Py_None;
while (row) {
row = pysqlite_cursor_iternext(self);
if (row) {
PyList_Append(list, row);
Py_DECREF(row);
} else {
break;
}
if (++counter == maxrows) {
break;
}
}
if (PyErr_Occurred()) {
Py_DECREF(list);
return NULL;
} else {
return list;
}
}
PyObject* pysqlite_cursor_fetchall(pysqlite_Cursor* self, PyObject* args)
{
PyObject* row;
PyObject* list;
list = PyList_New(0);
if (!list) {
return NULL;
}
/* just make sure we enter the loop */
row = (PyObject*)Py_None;
while (row) {
row = pysqlite_cursor_iternext(self);
if (row) {
PyList_Append(list, row);
Py_DECREF(row);
}
}
if (PyErr_Occurred()) {
Py_DECREF(list);
return NULL;
} else {
return list;
}
}
PyObject* pysqlite_noop(pysqlite_Connection* self, PyObject* args)
{
/* don't care, return None */
Py_RETURN_NONE;
}
PyObject* pysqlite_cursor_close(pysqlite_Cursor* self, PyObject* args)
{
if (!self->connection) {
PyErr_SetString(pysqlite_ProgrammingError,
"Base Cursor.__init__ not called.");
return NULL;
}
if (!pysqlite_check_thread(self->connection) || !pysqlite_check_connection(self->connection)) {
return NULL;
}
if (self->statement) {
(void)pysqlite_statement_reset(self->statement);
Py_CLEAR(self->statement);
}
self->closed = 1;
Py_RETURN_NONE;
}
static PyMethodDef cursor_methods[] = {
{"execute", (PyCFunction)pysqlite_cursor_execute, METH_VARARGS,
PyDoc_STR("Executes a SQL statement.")},
{"executemany", (PyCFunction)pysqlite_cursor_executemany, METH_VARARGS,
PyDoc_STR("Repeatedly executes a SQL statement.")},
{"executescript", (PyCFunction)pysqlite_cursor_executescript, METH_VARARGS,
PyDoc_STR("Executes a multiple SQL statements at once. Non-standard.")},
{"fetchone", (PyCFunction)pysqlite_cursor_fetchone, METH_NOARGS,
PyDoc_STR("Fetches one row from the resultset.")},
{"fetchmany", (PyCFunction)pysqlite_cursor_fetchmany, METH_VARARGS|METH_KEYWORDS,
PyDoc_STR("Fetches several rows from the resultset.")},
{"fetchall", (PyCFunction)pysqlite_cursor_fetchall, METH_NOARGS,
PyDoc_STR("Fetches all rows from the resultset.")},
{"close", (PyCFunction)pysqlite_cursor_close, METH_NOARGS,
PyDoc_STR("Closes the cursor.")},
{"setinputsizes", (PyCFunction)pysqlite_noop, METH_VARARGS,
PyDoc_STR("Required by DB-API. Does nothing in pysqlite.")},
{"setoutputsize", (PyCFunction)pysqlite_noop, METH_VARARGS,
PyDoc_STR("Required by DB-API. Does nothing in pysqlite.")},
{NULL, NULL}
};
static struct PyMemberDef cursor_members[] =
{
{"connection", T_OBJECT, offsetof(pysqlite_Cursor, connection), READONLY},
{"description", T_OBJECT, offsetof(pysqlite_Cursor, description), READONLY},
{"arraysize", T_INT, offsetof(pysqlite_Cursor, arraysize), 0},
{"lastrowid", T_OBJECT, offsetof(pysqlite_Cursor, lastrowid), READONLY},
{"rowcount", T_LONG, offsetof(pysqlite_Cursor, rowcount), READONLY},
{"row_factory", T_OBJECT, offsetof(pysqlite_Cursor, row_factory), 0},
{NULL}
};
static const char cursor_doc[] =
PyDoc_STR("SQLite database cursor class.");
PyTypeObject pysqlite_CursorType = {
PyVarObject_HEAD_INIT(NULL, 0)
"sqlite3.Cursor", /* tp_name */
sizeof(pysqlite_Cursor), /* tp_basicsize */
0, /* tp_itemsize */
(destructor)pysqlite_cursor_dealloc, /* tp_dealloc */
0, /* tp_print */
0, /* tp_getattr */
0, /* tp_setattr */
0, /* tp_reserved */
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 */
cursor_doc, /* tp_doc */
0, /* tp_traverse */
0, /* tp_clear */
0, /* tp_richcompare */
offsetof(pysqlite_Cursor, in_weakreflist), /* tp_weaklistoffset */
(getiterfunc)pysqlite_cursor_getiter, /* tp_iter */
(iternextfunc)pysqlite_cursor_iternext, /* tp_iternext */
cursor_methods, /* tp_methods */
cursor_members, /* tp_members */
0, /* tp_getset */
0, /* tp_base */
0, /* tp_dict */
0, /* tp_descr_get */
0, /* tp_descr_set */
0, /* tp_dictoffset */
(initproc)pysqlite_cursor_init, /* tp_init */
0, /* tp_alloc */
0, /* tp_new */
0 /* tp_free */
};
extern int pysqlite_cursor_setup_types(void)
{
pysqlite_CursorType.tp_new = PyType_GenericNew;
return PyType_Ready(&pysqlite_CursorType);
}
| 34,340 | 1,029 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Modules/_sqlite/module.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:8;coding:utf-8 -*-â
âvi: set net ft=c ts=4 sts=4 sw=4 fenc=utf-8 :viâ
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ¡
â â
â Copyright (C) 2005-2010 Gerhard Häring <[email protected]> â
â â
â This file is part of pysqlite. â
â â
â This software is provided 'as-is', without any express or implied â
â warranty. In no event will the authors be held liable for any damages â
â arising from the use of this software. â
â â
â Permission is granted to anyone to use this software for any purpose, â
â including commercial applications, and to alter it and redistribute it â
â freely, subject to the following restrictions: â
â â
â 1. The origin of this software must not be misrepresented; you must not â
â claim that you wrote the original software. If you use this software â
â in a product, an acknowledgment in the product documentation would be â
â appreciated but is not required. â
â 2. Altered source versions must be plainly marked as such, and must not be â
â misrepresented as being the original software. â
â 3. This notice may not be removed or altered from any source distribution. â
â â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
#include "third_party/python/Include/yoink.h"
#include "third_party/python/Modules/_sqlite/cache.h"
#include "third_party/python/Modules/_sqlite/connection.h"
#include "third_party/python/Modules/_sqlite/cursor.h"
#include "third_party/python/Modules/_sqlite/microprotocols.h"
#include "third_party/python/Modules/_sqlite/prepare_protocol.h"
#include "third_party/python/Modules/_sqlite/row.h"
#include "third_party/python/Modules/_sqlite/statement.h"
PYTHON_PROVIDE("_sqlite3");
asm(".ident\t\"\\n\\n\
pysqlite (zlib license)\\n\
Copyright (C) 2005-2010 Gerhard Häring <[email protected]>\"");
asm(".include \"libc/disclaimer.inc\"");
/* clang-format off */
/* #if SQLITE_VERSION_NUMBER >= 3003003 */
/* #define HAVE_SHARED_CACHE */
/* #endif */
/* static objects at module-level */
PyObject* pysqlite_Error, *pysqlite_Warning, *pysqlite_InterfaceError, *pysqlite_DatabaseError,
*pysqlite_InternalError, *pysqlite_OperationalError, *pysqlite_ProgrammingError,
*pysqlite_IntegrityError, *pysqlite_DataError, *pysqlite_NotSupportedError;
PyObject* _pysqlite_converters;
int _pysqlite_enable_callback_tracebacks;
int pysqlite_BaseTypeAdapted;
static PyObject* module_connect(PyObject* self, PyObject* args, PyObject*
kwargs)
{
/* Python seems to have no way of extracting a single keyword-arg at
* C-level, so this code is redundant with the one in connection_init in
* connection.c and must always be copied from there ... */
static char *kwlist[] = {
"database", "timeout", "detect_types", "isolation_level",
"check_same_thread", "factory", "cached_statements", "uri",
NULL
};
char* database;
int detect_types = 0;
PyObject* isolation_level;
PyObject* factory = NULL;
int check_same_thread = 1;
int cached_statements;
int uri = 0;
double timeout = 5.0;
PyObject* result;
if (!PyArg_ParseTupleAndKeywords(args, kwargs, "s|diOiOip", kwlist,
&database, &timeout, &detect_types,
&isolation_level, &check_same_thread,
&factory, &cached_statements, &uri))
{
return NULL;
}
if (factory == NULL) {
factory = (PyObject*)&pysqlite_ConnectionType;
}
result = PyObject_Call(factory, args, kwargs);
return result;
}
PyDoc_STRVAR(module_connect_doc,
"connect(database[, timeout, detect_types, isolation_level,\n\
check_same_thread, factory, cached_statements, uri])\n\
\n\
Opens a connection to the SQLite database file *database*. You can use\n\
\":memory:\" to open a database connection to a database that resides in\n\
RAM instead of on disk.");
static PyObject* module_complete(PyObject* self, PyObject* args, PyObject*
kwargs)
{
static char *kwlist[] = {"statement", NULL, NULL};
char* statement;
PyObject* result;
if (!PyArg_ParseTupleAndKeywords(args, kwargs, "s", kwlist, &statement))
{
return NULL;
}
if (sqlite3_complete(statement)) {
result = Py_True;
} else {
result = Py_False;
}
Py_INCREF(result);
return result;
}
PyDoc_STRVAR(module_complete_doc,
"complete_statement(sql)\n\
\n\
Checks if a string contains a complete SQL statement. Non-standard.");
#ifdef HAVE_SHARED_CACHE
static PyObject* module_enable_shared_cache(PyObject* self, PyObject* args, PyObject*
kwargs)
{
static char *kwlist[] = {"do_enable", NULL, NULL};
int do_enable;
int rc;
if (!PyArg_ParseTupleAndKeywords(args, kwargs, "i", kwlist, &do_enable))
{
return NULL;
}
rc = sqlite3_enable_shared_cache(do_enable);
if (rc != SQLITE_OK) {
PyErr_SetString(pysqlite_OperationalError, "Changing the shared_cache flag failed");
return NULL;
} else {
Py_RETURN_NONE;
}
}
PyDoc_STRVAR(module_enable_shared_cache_doc,
"enable_shared_cache(do_enable)\n\
\n\
Enable or disable shared cache mode for the calling thread.\n\
Experimental/Non-standard.");
#endif /* HAVE_SHARED_CACHE */
static PyObject* module_register_adapter(PyObject* self, PyObject* args)
{
PyTypeObject* type;
PyObject* caster;
int rc;
if (!PyArg_ParseTuple(args, "OO", &type, &caster)) {
return NULL;
}
/* a basic type is adapted; there's a performance optimization if that's not the case
* (99 % of all usages) */
if (type == &PyLong_Type || type == &PyFloat_Type
|| type == &PyUnicode_Type || type == &PyByteArray_Type) {
pysqlite_BaseTypeAdapted = 1;
}
rc = pysqlite_microprotocols_add(type, (PyObject*)&pysqlite_PrepareProtocolType, caster);
if (rc == -1)
return NULL;
Py_RETURN_NONE;
}
PyDoc_STRVAR(module_register_adapter_doc,
"register_adapter(type, callable)\n\
\n\
Registers an adapter with pysqlite's adapter registry. Non-standard.");
static PyObject* module_register_converter(PyObject* self, PyObject* args)
{
PyObject* orig_name;
PyObject* name = NULL;
PyObject* callable;
PyObject* retval = NULL;
_Py_IDENTIFIER(upper);
if (!PyArg_ParseTuple(args, "UO", &orig_name, &callable)) {
return NULL;
}
/* convert the name to upper case */
name = _PyObject_CallMethodId(orig_name, &PyId_upper, NULL);
if (!name) {
goto error;
}
if (PyDict_SetItem(_pysqlite_converters, name, callable) != 0) {
goto error;
}
Py_INCREF(Py_None);
retval = Py_None;
error:
Py_XDECREF(name);
return retval;
}
PyDoc_STRVAR(module_register_converter_doc,
"register_converter(typename, callable)\n\
\n\
Registers a converter with pysqlite. Non-standard.");
static PyObject* enable_callback_tracebacks(PyObject* self, PyObject* args)
{
if (!PyArg_ParseTuple(args, "i", &_pysqlite_enable_callback_tracebacks)) {
return NULL;
}
Py_RETURN_NONE;
}
PyDoc_STRVAR(enable_callback_tracebacks_doc,
"enable_callback_tracebacks(flag)\n\
\n\
Enable or disable callback functions throwing errors to stderr.");
static void converters_init(PyObject* dict)
{
_pysqlite_converters = PyDict_New();
if (!_pysqlite_converters) {
return;
}
PyDict_SetItemString(dict, "converters", _pysqlite_converters);
}
static PyMethodDef module_methods[] = {
{"connect", (PyCFunction)module_connect,
METH_VARARGS | METH_KEYWORDS, module_connect_doc},
{"complete_statement", (PyCFunction)module_complete,
METH_VARARGS | METH_KEYWORDS, module_complete_doc},
#ifdef HAVE_SHARED_CACHE
{"enable_shared_cache", (PyCFunction)module_enable_shared_cache,
METH_VARARGS | METH_KEYWORDS, module_enable_shared_cache_doc},
#endif
{"register_adapter", (PyCFunction)module_register_adapter,
METH_VARARGS, module_register_adapter_doc},
{"register_converter", (PyCFunction)module_register_converter,
METH_VARARGS, module_register_converter_doc},
{"adapt", (PyCFunction)pysqlite_adapt, METH_VARARGS,
pysqlite_adapt_doc},
{"enable_callback_tracebacks", (PyCFunction)enable_callback_tracebacks,
METH_VARARGS, enable_callback_tracebacks_doc},
{NULL, NULL}
};
struct _IntConstantPair {
const char *constant_name;
int constant_value;
};
typedef struct _IntConstantPair IntConstantPair;
static const IntConstantPair _int_constants[] = {
{"PARSE_DECLTYPES", PARSE_DECLTYPES},
{"PARSE_COLNAMES", PARSE_COLNAMES},
{"SQLITE_OK", SQLITE_OK},
{"SQLITE_DENY", SQLITE_DENY},
{"SQLITE_IGNORE", SQLITE_IGNORE},
{"SQLITE_CREATE_INDEX", SQLITE_CREATE_INDEX},
{"SQLITE_CREATE_TABLE", SQLITE_CREATE_TABLE},
{"SQLITE_CREATE_TEMP_INDEX", SQLITE_CREATE_TEMP_INDEX},
{"SQLITE_CREATE_TEMP_TABLE", SQLITE_CREATE_TEMP_TABLE},
{"SQLITE_CREATE_TEMP_TRIGGER", SQLITE_CREATE_TEMP_TRIGGER},
{"SQLITE_CREATE_TEMP_VIEW", SQLITE_CREATE_TEMP_VIEW},
{"SQLITE_CREATE_TRIGGER", SQLITE_CREATE_TRIGGER},
{"SQLITE_CREATE_VIEW", SQLITE_CREATE_VIEW},
{"SQLITE_DELETE", SQLITE_DELETE},
{"SQLITE_DROP_INDEX", SQLITE_DROP_INDEX},
{"SQLITE_DROP_TABLE", SQLITE_DROP_TABLE},
{"SQLITE_DROP_TEMP_INDEX", SQLITE_DROP_TEMP_INDEX},
{"SQLITE_DROP_TEMP_TABLE", SQLITE_DROP_TEMP_TABLE},
{"SQLITE_DROP_TEMP_TRIGGER", SQLITE_DROP_TEMP_TRIGGER},
{"SQLITE_DROP_TEMP_VIEW", SQLITE_DROP_TEMP_VIEW},
{"SQLITE_DROP_TRIGGER", SQLITE_DROP_TRIGGER},
{"SQLITE_DROP_VIEW", SQLITE_DROP_VIEW},
{"SQLITE_INSERT", SQLITE_INSERT},
{"SQLITE_PRAGMA", SQLITE_PRAGMA},
{"SQLITE_READ", SQLITE_READ},
{"SQLITE_SELECT", SQLITE_SELECT},
{"SQLITE_TRANSACTION", SQLITE_TRANSACTION},
{"SQLITE_UPDATE", SQLITE_UPDATE},
{"SQLITE_ATTACH", SQLITE_ATTACH},
{"SQLITE_DETACH", SQLITE_DETACH},
#if SQLITE_VERSION_NUMBER >= 3002001
{"SQLITE_ALTER_TABLE", SQLITE_ALTER_TABLE},
{"SQLITE_REINDEX", SQLITE_REINDEX},
#endif
#if SQLITE_VERSION_NUMBER >= 3003000
{"SQLITE_ANALYZE", SQLITE_ANALYZE},
#endif
{(char*)NULL, 0}
};
static struct PyModuleDef _sqlite3module = {
PyModuleDef_HEAD_INIT,
"_sqlite3",
NULL,
-1,
module_methods,
NULL,
NULL,
NULL,
NULL
};
PyMODINIT_FUNC PyInit__sqlite3(void)
{
PyObject *module, *dict;
PyObject *tmp_obj;
int i;
sqlite3_initialize();
module = PyModule_Create(&_sqlite3module);
if (!module ||
(pysqlite_row_setup_types() < 0) ||
(pysqlite_cursor_setup_types() < 0) ||
(pysqlite_connection_setup_types() < 0) ||
(pysqlite_cache_setup_types() < 0) ||
(pysqlite_statement_setup_types() < 0) ||
(pysqlite_prepare_protocol_setup_types() < 0)
) {
Py_XDECREF(module);
return NULL;
}
Py_INCREF(&pysqlite_ConnectionType);
PyModule_AddObject(module, "Connection", (PyObject*) &pysqlite_ConnectionType);
Py_INCREF(&pysqlite_CursorType);
PyModule_AddObject(module, "Cursor", (PyObject*) &pysqlite_CursorType);
Py_INCREF(&pysqlite_CacheType);
PyModule_AddObject(module, "Statement", (PyObject*)&pysqlite_StatementType);
Py_INCREF(&pysqlite_StatementType);
PyModule_AddObject(module, "Cache", (PyObject*) &pysqlite_CacheType);
Py_INCREF(&pysqlite_PrepareProtocolType);
PyModule_AddObject(module, "PrepareProtocol", (PyObject*) &pysqlite_PrepareProtocolType);
Py_INCREF(&pysqlite_RowType);
PyModule_AddObject(module, "Row", (PyObject*) &pysqlite_RowType);
if (!(dict = PyModule_GetDict(module))) {
goto error;
}
/*** Create DB-API Exception hierarchy */
if (!(pysqlite_Error = PyErr_NewException("sqlite3.Error", PyExc_Exception, NULL))) {
goto error;
}
PyDict_SetItemString(dict, "Error", pysqlite_Error);
if (!(pysqlite_Warning = PyErr_NewException("sqlite3.Warning", PyExc_Exception, NULL))) {
goto error;
}
PyDict_SetItemString(dict, "Warning", pysqlite_Warning);
/* Error subclasses */
if (!(pysqlite_InterfaceError = PyErr_NewException("sqlite3.InterfaceError", pysqlite_Error, NULL))) {
goto error;
}
PyDict_SetItemString(dict, "InterfaceError", pysqlite_InterfaceError);
if (!(pysqlite_DatabaseError = PyErr_NewException("sqlite3.DatabaseError", pysqlite_Error, NULL))) {
goto error;
}
PyDict_SetItemString(dict, "DatabaseError", pysqlite_DatabaseError);
/* pysqlite_DatabaseError subclasses */
if (!(pysqlite_InternalError = PyErr_NewException("sqlite3.InternalError", pysqlite_DatabaseError, NULL))) {
goto error;
}
PyDict_SetItemString(dict, "InternalError", pysqlite_InternalError);
if (!(pysqlite_OperationalError = PyErr_NewException("sqlite3.OperationalError", pysqlite_DatabaseError, NULL))) {
goto error;
}
PyDict_SetItemString(dict, "OperationalError", pysqlite_OperationalError);
if (!(pysqlite_ProgrammingError = PyErr_NewException("sqlite3.ProgrammingError", pysqlite_DatabaseError, NULL))) {
goto error;
}
PyDict_SetItemString(dict, "ProgrammingError", pysqlite_ProgrammingError);
if (!(pysqlite_IntegrityError = PyErr_NewException("sqlite3.IntegrityError", pysqlite_DatabaseError,NULL))) {
goto error;
}
PyDict_SetItemString(dict, "IntegrityError", pysqlite_IntegrityError);
if (!(pysqlite_DataError = PyErr_NewException("sqlite3.DataError", pysqlite_DatabaseError, NULL))) {
goto error;
}
PyDict_SetItemString(dict, "DataError", pysqlite_DataError);
if (!(pysqlite_NotSupportedError = PyErr_NewException("sqlite3.NotSupportedError", pysqlite_DatabaseError, NULL))) {
goto error;
}
PyDict_SetItemString(dict, "NotSupportedError", pysqlite_NotSupportedError);
/* In Python 2.x, setting Connection.text_factory to
OptimizedUnicode caused Unicode objects to be returned for
non-ASCII data and bytestrings to be returned for ASCII data.
Now OptimizedUnicode is an alias for str, so it has no
effect. */
Py_INCREF((PyObject*)&PyUnicode_Type);
PyDict_SetItemString(dict, "OptimizedUnicode", (PyObject*)&PyUnicode_Type);
/* Set integer constants */
for (i = 0; _int_constants[i].constant_name != 0; i++) {
tmp_obj = PyLong_FromLong(_int_constants[i].constant_value);
if (!tmp_obj) {
goto error;
}
PyDict_SetItemString(dict, _int_constants[i].constant_name, tmp_obj);
Py_DECREF(tmp_obj);
}
if (!(tmp_obj = PyUnicode_FromString(PYSQLITE_VERSION))) {
goto error;
}
PyDict_SetItemString(dict, "version", tmp_obj);
Py_DECREF(tmp_obj);
if (!(tmp_obj = PyUnicode_FromString(sqlite3_libversion()))) {
goto error;
}
PyDict_SetItemString(dict, "sqlite_version", tmp_obj);
Py_DECREF(tmp_obj);
/* initialize microprotocols layer */
pysqlite_microprotocols_init(dict);
/* initialize the default converters */
converters_init(dict);
_pysqlite_enable_callback_tracebacks = 0;
pysqlite_BaseTypeAdapted = 0;
/* Original comment from _bsddb.c in the Python core. This is also still
* needed nowadays for Python 2.3/2.4.
*
* PyEval_InitThreads is called here due to a quirk in python 1.5
* - 2.2.1 (at least) according to Russell Williamson <[email protected]>:
* The global interpreter lock is not initialized until the first
* thread is created using thread.start_new_thread() or fork() is
* called. that would cause the ALLOW_THREADS here to segfault due
* to a null pointer reference if no threads or child processes
* have been created. This works around that and is a no-op if
* threads have already been initialized.
* (see pybsddb-users mailing list post on 2002-08-07)
*/
#ifdef WITH_THREAD
PyEval_InitThreads();
#endif
error:
if (PyErr_Occurred())
{
PyErr_SetString(PyExc_ImportError, "sqlite3: init failed");
Py_DECREF(module);
module = NULL;
}
return module;
}
_Section(".rodata.pytab.1") const struct _inittab _PyImport_Inittab__sqlite3 = {
"_sqlite3",
PyInit__sqlite3,
};
| 17,556 | 499 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Modules/_sqlite/cursor.h | #ifndef PYSQLITE_CURSOR_H
#define PYSQLITE_CURSOR_H
#include "third_party/python/Include/Python.h"
/* clang-format off */
#include "third_party/python/Modules/_sqlite/statement.h"
#include "third_party/python/Modules/_sqlite/connection.h"
#include "third_party/python/Modules/_sqlite/module.h"
#include "third_party/python/Modules/_sqlite/connection.h"
typedef struct
{
PyObject_HEAD
pysqlite_Connection* connection;
PyObject* description;
PyObject* row_cast_map;
int arraysize;
PyObject* lastrowid;
long rowcount;
PyObject* row_factory;
pysqlite_Statement* statement;
int closed;
int reset;
int locked;
int initialized;
/* the next row to be returned, NULL if no next row available */
PyObject* next_row;
PyObject* in_weakreflist; /* List of weak references */
} pysqlite_Cursor;
extern PyTypeObject pysqlite_CursorType;
PyObject* pysqlite_cursor_execute(pysqlite_Cursor* self, PyObject* args);
PyObject* pysqlite_cursor_executemany(pysqlite_Cursor* self, PyObject* args);
PyObject* pysqlite_cursor_getiter(pysqlite_Cursor *self);
PyObject* pysqlite_cursor_iternext(pysqlite_Cursor *self);
PyObject* pysqlite_cursor_fetchone(pysqlite_Cursor* self, PyObject* args);
PyObject* pysqlite_cursor_fetchmany(pysqlite_Cursor* self, PyObject* args, PyObject* kwargs);
PyObject* pysqlite_cursor_fetchall(pysqlite_Cursor* self, PyObject* args);
PyObject* pysqlite_noop(pysqlite_Connection* self, PyObject* args);
PyObject* pysqlite_cursor_close(pysqlite_Cursor* self, PyObject* args);
int pysqlite_cursor_setup_types(void);
#define UNKNOWN (-1)
#endif
| 1,614 | 49 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Modules/_sqlite/module.h | #ifndef PYSQLITE_MODULE_H
#define PYSQLITE_MODULE_H
#include "third_party/python/Include/Python.h"
/* clang-format off */
#define PYSQLITE_VERSION "2.6.0"
extern PyObject* pysqlite_Error;
extern PyObject* pysqlite_Warning;
extern PyObject* pysqlite_InterfaceError;
extern PyObject* pysqlite_DatabaseError;
extern PyObject* pysqlite_InternalError;
extern PyObject* pysqlite_OperationalError;
extern PyObject* pysqlite_ProgrammingError;
extern PyObject* pysqlite_IntegrityError;
extern PyObject* pysqlite_DataError;
extern PyObject* pysqlite_NotSupportedError;
/* A dictionary, mapping column types (INTEGER, VARCHAR, etc.) to converter
* functions, that convert the SQL value to the appropriate Python value.
* The key is uppercase.
*/
extern PyObject* _pysqlite_converters;
extern int _pysqlite_enable_callback_tracebacks;
extern int pysqlite_BaseTypeAdapted;
#define PARSE_DECLTYPES 1
#define PARSE_COLNAMES 2
#endif
| 926 | 31 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Modules/_sqlite/row.h | #ifndef PYSQLITE_ROW_H
#define PYSQLITE_ROW_H
#include "third_party/python/Include/Python.h"
/* clang-format off */
typedef struct _Row
{
PyObject_HEAD
PyObject* data;
PyObject* description;
} pysqlite_Row;
extern PyTypeObject pysqlite_RowType;
int pysqlite_row_setup_types(void);
#endif
| 304 | 18 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Modules/_sqlite/cache.h | #ifndef PYSQLITE_CACHE_H
#define PYSQLITE_CACHE_H
#include "third_party/python/Include/Python.h"
/* clang-format off */
/* The LRU cache is implemented as a combination of a doubly-linked with a
* dictionary. The list items are of type 'Node' and the dictionary has the
* nodes as values. */
typedef struct _pysqlite_Node
{
PyObject_HEAD
PyObject* key;
PyObject* data;
long count;
struct _pysqlite_Node* prev;
struct _pysqlite_Node* next;
} pysqlite_Node;
typedef struct
{
PyObject_HEAD
int size;
/* a dictionary mapping keys to Node entries */
PyObject* mapping;
/* the factory callable */
PyObject* factory;
pysqlite_Node* first;
pysqlite_Node* last;
/* if set, decrement the factory function when the Cache is deallocated.
* this is almost always desirable, but not in the pysqlite context */
int decref_factory;
} pysqlite_Cache;
extern PyTypeObject pysqlite_NodeType;
extern PyTypeObject pysqlite_CacheType;
int pysqlite_node_init(pysqlite_Node* self, PyObject* args, PyObject* kwargs);
void pysqlite_node_dealloc(pysqlite_Node* self);
int pysqlite_cache_init(pysqlite_Cache* self, PyObject* args, PyObject* kwargs);
void pysqlite_cache_dealloc(pysqlite_Cache* self);
PyObject* pysqlite_cache_get(pysqlite_Cache* self, PyObject* args);
int pysqlite_cache_setup_types(void);
#endif
| 1,369 | 52 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Modules/_sqlite/connection.h | #ifndef PYSQLITE_CONNECTION_H
#define PYSQLITE_CONNECTION_H
#include "third_party/python/Include/Python.h"
#include "third_party/python/Include/pythread.h"
#include "third_party/python/Include/structmember.h"
#include "third_party/python/Modules/_sqlite/cache.h"
#include "third_party/python/Modules/_sqlite/module.h"
#include "third_party/sqlite3/sqlite3.h"
/* clang-format off */
typedef struct
{
PyObject_HEAD
sqlite3* db;
/* the type detection mode. Only 0, PARSE_DECLTYPES, PARSE_COLNAMES or a
* bitwise combination thereof makes sense */
int detect_types;
/* the timeout value in seconds for database locks */
double timeout;
/* for internal use in the timeout handler: when did the timeout handler
* first get called with count=0? */
double timeout_started;
/* None for autocommit, otherwise a PyUnicode with the isolation level */
PyObject* isolation_level;
/* NULL for autocommit, otherwise a string with the BEGIN statement */
const char* begin_statement;
/* 1 if a check should be performed for each API call if the connection is
* used from the same thread it was created in */
int check_same_thread;
int initialized;
/* thread identification of the thread the connection was created in */
long thread_ident;
pysqlite_Cache* statement_cache;
/* Lists of weak references to statements and cursors used within this connection */
PyObject* statements;
PyObject* cursors;
/* Counters for how many statements/cursors were created in the connection. May be
* reset to 0 at certain intervals */
int created_statements;
int created_cursors;
PyObject* row_factory;
/* Determines how bytestrings from SQLite are converted to Python objects:
* - PyUnicode_Type: Python Unicode objects are constructed from UTF-8 bytestrings
* - PyBytes_Type: The bytestrings are returned as-is.
* - Any custom callable: Any object returned from the callable called with the bytestring
* as single parameter.
*/
PyObject* text_factory;
/* remember references to functions/classes used in
* create_function/create/aggregate, use these as dictionary keys, so we
* can keep the total system refcount constant by clearing that dictionary
* in connection_dealloc */
PyObject* function_pinboard;
/* a dictionary of registered collation name => collation callable mappings */
PyObject* collations;
/* Exception objects */
PyObject* Warning;
PyObject* Error;
PyObject* InterfaceError;
PyObject* DatabaseError;
PyObject* DataError;
PyObject* OperationalError;
PyObject* IntegrityError;
PyObject* InternalError;
PyObject* ProgrammingError;
PyObject* NotSupportedError;
} pysqlite_Connection;
extern PyTypeObject pysqlite_ConnectionType;
PyObject* pysqlite_connection_alloc(PyTypeObject* type, int aware);
void pysqlite_connection_dealloc(pysqlite_Connection* self);
PyObject* pysqlite_connection_cursor(pysqlite_Connection* self, PyObject* args, PyObject* kwargs);
PyObject* pysqlite_connection_close(pysqlite_Connection* self, PyObject* args);
PyObject* _pysqlite_connection_begin(pysqlite_Connection* self);
PyObject* pysqlite_connection_commit(pysqlite_Connection* self, PyObject* args);
PyObject* pysqlite_connection_rollback(pysqlite_Connection* self, PyObject* args);
PyObject* pysqlite_connection_new(PyTypeObject* type, PyObject* args, PyObject* kw);
int pysqlite_connection_init(pysqlite_Connection* self, PyObject* args, PyObject* kwargs);
int pysqlite_connection_register_cursor(pysqlite_Connection* connection, PyObject* cursor);
int pysqlite_check_thread(pysqlite_Connection* self);
int pysqlite_check_connection(pysqlite_Connection* con);
int pysqlite_connection_setup_types(void);
#endif
| 3,869 | 104 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Modules/_sqlite/statement.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:8;coding:utf-8 -*-â
âvi: set net ft=c ts=4 sts=4 sw=4 fenc=utf-8 :viâ
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ¡
â â
â Copyright (C) 2005-2010 Gerhard Häring <[email protected]> â
â â
â This file is part of pysqlite. â
â â
â This software is provided 'as-is', without any express or implied â
â warranty. In no event will the authors be held liable for any damages â
â arising from the use of this software. â
â â
â Permission is granted to anyone to use this software for any purpose, â
â including commercial applications, and to alter it and redistribute it â
â freely, subject to the following restrictions: â
â â
â 1. The origin of this software must not be misrepresented; you must not â
â claim that you wrote the original software. If you use this software â
â in a product, an acknowledgment in the product documentation would be â
â appreciated but is not required. â
â 2. Altered source versions must be plainly marked as such, and must not be â
â misrepresented as being the original software. â
â 3. This notice may not be removed or altered from any source distribution. â
â â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
#include "third_party/python/Modules/_sqlite/connection.h"
#include "third_party/python/Modules/_sqlite/cursor.h"
#include "third_party/python/Modules/_sqlite/microprotocols.h"
#include "third_party/python/Modules/_sqlite/prepare_protocol.h"
#include "third_party/python/Modules/_sqlite/statement.h"
#include "third_party/python/Modules/_sqlite/util.h"
asm(".ident\t\"\\n\\n\
pysqlite (zlib license)\\n\
Copyright (C) 2005-2010 Gerhard Häring <[email protected]>\"");
asm(".include \"libc/disclaimer.inc\"");
/* clang-format off */
/* prototypes */
static int pysqlite_check_remaining_sql(const char* tail);
typedef enum {
LINECOMMENT_1,
IN_LINECOMMENT,
COMMENTSTART_1,
IN_COMMENT,
COMMENTEND_1,
NORMAL
} parse_remaining_sql_state;
typedef enum {
TYPE_LONG,
TYPE_FLOAT,
TYPE_UNICODE,
TYPE_BUFFER,
TYPE_UNKNOWN
} parameter_type;
int pysqlite_statement_create(pysqlite_Statement* self, pysqlite_Connection* connection, PyObject* sql)
{
const char* tail;
int rc;
const char* sql_cstr;
Py_ssize_t sql_cstr_len;
const char* p;
self->st = NULL;
self->in_use = 0;
sql_cstr = PyUnicode_AsUTF8AndSize(sql, &sql_cstr_len);
if (sql_cstr == NULL) {
rc = PYSQLITE_SQL_WRONG_TYPE;
return rc;
}
if (strlen(sql_cstr) != (size_t)sql_cstr_len) {
PyErr_SetString(PyExc_ValueError, "the query contains a null character");
return PYSQLITE_SQL_WRONG_TYPE;
}
self->in_weakreflist = NULL;
Py_INCREF(sql);
self->sql = sql;
/* Determine if the statement is a DML statement.
SELECT is the only exception. See #9924. */
self->is_dml = 0;
for (p = sql_cstr; *p != 0; p++) {
switch (*p) {
case ' ':
case '\r':
case '\n':
case '\t':
continue;
}
self->is_dml = (PyOS_strnicmp(p, "insert", 6) == 0)
|| (PyOS_strnicmp(p, "update", 6) == 0)
|| (PyOS_strnicmp(p, "delete", 6) == 0)
|| (PyOS_strnicmp(p, "replace", 7) == 0);
break;
}
Py_BEGIN_ALLOW_THREADS
rc = sqlite3_prepare(connection->db,
sql_cstr,
-1,
&self->st,
&tail);
Py_END_ALLOW_THREADS
self->db = connection->db;
if (rc == SQLITE_OK && pysqlite_check_remaining_sql(tail)) {
(void)sqlite3_finalize(self->st);
self->st = NULL;
rc = PYSQLITE_TOO_MUCH_SQL;
}
return rc;
}
int pysqlite_statement_bind_parameter(pysqlite_Statement* self, int pos, PyObject* parameter)
{
int rc = SQLITE_OK;
char* string;
Py_ssize_t buflen;
parameter_type paramtype;
if (parameter == Py_None) {
rc = sqlite3_bind_null(self->st, pos);
goto final;
}
if (PyLong_CheckExact(parameter)) {
paramtype = TYPE_LONG;
} else if (PyFloat_CheckExact(parameter)) {
paramtype = TYPE_FLOAT;
} else if (PyUnicode_CheckExact(parameter)) {
paramtype = TYPE_UNICODE;
} else if (PyLong_Check(parameter)) {
paramtype = TYPE_LONG;
} else if (PyFloat_Check(parameter)) {
paramtype = TYPE_FLOAT;
} else if (PyUnicode_Check(parameter)) {
paramtype = TYPE_UNICODE;
} else if (PyObject_CheckBuffer(parameter)) {
paramtype = TYPE_BUFFER;
} else {
paramtype = TYPE_UNKNOWN;
}
switch (paramtype) {
case TYPE_LONG: {
sqlite_int64 value = _pysqlite_long_as_int64(parameter);
if (value == -1 && PyErr_Occurred())
rc = -1;
else
rc = sqlite3_bind_int64(self->st, pos, value);
break;
}
case TYPE_FLOAT:
rc = sqlite3_bind_double(self->st, pos, PyFloat_AsDouble(parameter));
break;
case TYPE_UNICODE:
string = PyUnicode_AsUTF8AndSize(parameter, &buflen);
if (string == NULL)
return -1;
if (buflen > INT_MAX) {
PyErr_SetString(PyExc_OverflowError,
"string longer than INT_MAX bytes");
return -1;
}
rc = sqlite3_bind_text(self->st, pos, string, (int)buflen, SQLITE_TRANSIENT);
break;
case TYPE_BUFFER: {
Py_buffer view;
if (PyObject_GetBuffer(parameter, &view, PyBUF_SIMPLE) != 0) {
PyErr_SetString(PyExc_ValueError, "could not convert BLOB to buffer");
return -1;
}
if (view.len > INT_MAX) {
PyErr_SetString(PyExc_OverflowError,
"BLOB longer than INT_MAX bytes");
PyBuffer_Release(&view);
return -1;
}
rc = sqlite3_bind_blob(self->st, pos, view.buf, (int)view.len, SQLITE_TRANSIENT);
PyBuffer_Release(&view);
break;
}
case TYPE_UNKNOWN:
rc = -1;
}
final:
return rc;
}
/* returns 0 if the object is one of Python's internal ones that don't need to be adapted */
static int _need_adapt(PyObject* obj)
{
if (pysqlite_BaseTypeAdapted) {
return 1;
}
if (PyLong_CheckExact(obj) || PyFloat_CheckExact(obj)
|| PyUnicode_CheckExact(obj) || PyByteArray_CheckExact(obj)) {
return 0;
} else {
return 1;
}
}
void pysqlite_statement_bind_parameters(pysqlite_Statement* self, PyObject* parameters)
{
PyObject* current_param;
PyObject* adapted;
const char* binding_name;
int i;
int rc;
int num_params_needed;
Py_ssize_t num_params;
Py_BEGIN_ALLOW_THREADS
num_params_needed = sqlite3_bind_parameter_count(self->st);
Py_END_ALLOW_THREADS
if (PyTuple_CheckExact(parameters) || PyList_CheckExact(parameters) || (!PyDict_Check(parameters) && PySequence_Check(parameters))) {
/* parameters passed as sequence */
if (PyTuple_CheckExact(parameters)) {
num_params = PyTuple_GET_SIZE(parameters);
} else if (PyList_CheckExact(parameters)) {
num_params = PyList_GET_SIZE(parameters);
} else {
num_params = PySequence_Size(parameters);
}
if (num_params != num_params_needed) {
PyErr_Format(pysqlite_ProgrammingError,
"Incorrect number of bindings supplied. The current "
"statement uses %d, and there are %zd supplied.",
num_params_needed, num_params);
return;
}
for (i = 0; i < num_params; i++) {
if (PyTuple_CheckExact(parameters)) {
current_param = PyTuple_GET_ITEM(parameters, i);
Py_XINCREF(current_param);
} else if (PyList_CheckExact(parameters)) {
current_param = PyList_GET_ITEM(parameters, i);
Py_XINCREF(current_param);
} else {
current_param = PySequence_GetItem(parameters, i);
}
if (!current_param) {
return;
}
if (!_need_adapt(current_param)) {
adapted = current_param;
} else {
adapted = pysqlite_microprotocols_adapt(current_param, (PyObject*)&pysqlite_PrepareProtocolType, NULL);
if (adapted) {
Py_DECREF(current_param);
} else {
PyErr_Clear();
adapted = current_param;
}
}
rc = pysqlite_statement_bind_parameter(self, i + 1, adapted);
Py_DECREF(adapted);
if (rc != SQLITE_OK) {
if (!PyErr_Occurred()) {
PyErr_Format(pysqlite_InterfaceError, "Error binding parameter %d - probably unsupported type.", i);
}
return;
}
}
} else if (PyDict_Check(parameters)) {
/* parameters passed as dictionary */
for (i = 1; i <= num_params_needed; i++) {
Py_BEGIN_ALLOW_THREADS
binding_name = sqlite3_bind_parameter_name(self->st, i);
Py_END_ALLOW_THREADS
if (!binding_name) {
PyErr_Format(pysqlite_ProgrammingError, "Binding %d has no name, but you supplied a dictionary (which has only names).", i);
return;
}
binding_name++; /* skip first char (the colon) */
if (PyDict_CheckExact(parameters)) {
current_param = PyDict_GetItemString(parameters, binding_name);
Py_XINCREF(current_param);
} else {
current_param = PyMapping_GetItemString(parameters, binding_name);
}
if (!current_param) {
PyErr_Format(pysqlite_ProgrammingError, "You did not supply a value for binding %d.", i);
return;
}
if (!_need_adapt(current_param)) {
adapted = current_param;
} else {
adapted = pysqlite_microprotocols_adapt(current_param, (PyObject*)&pysqlite_PrepareProtocolType, NULL);
if (adapted) {
Py_DECREF(current_param);
} else {
PyErr_Clear();
adapted = current_param;
}
}
rc = pysqlite_statement_bind_parameter(self, i, adapted);
Py_DECREF(adapted);
if (rc != SQLITE_OK) {
if (!PyErr_Occurred()) {
PyErr_Format(pysqlite_InterfaceError, "Error binding parameter :%s - probably unsupported type.", binding_name);
}
return;
}
}
} else {
PyErr_SetString(PyExc_ValueError, "parameters are of unsupported type");
}
}
int pysqlite_statement_recompile(pysqlite_Statement* self, PyObject* params)
{
const char* tail;
int rc;
const char* sql_cstr;
Py_ssize_t sql_len;
sqlite3_stmt* new_st;
sql_cstr = PyUnicode_AsUTF8AndSize(self->sql, &sql_len);
if (sql_cstr == NULL) {
rc = PYSQLITE_SQL_WRONG_TYPE;
return rc;
}
Py_BEGIN_ALLOW_THREADS
rc = sqlite3_prepare(self->db,
sql_cstr,
-1,
&new_st,
&tail);
Py_END_ALLOW_THREADS
if (rc == SQLITE_OK) {
/* The efficient sqlite3_transfer_bindings is only available in SQLite
* version 3.2.2 or later. For older SQLite releases, that might not
* even define SQLITE_VERSION_NUMBER, we do it the manual way.
*/
#ifdef SQLITE_VERSION_NUMBER
#if SQLITE_VERSION_NUMBER >= 3002002
/* The check for the number of parameters is necessary to not trigger a
* bug in certain SQLite versions (experienced in 3.2.8 and 3.3.4). */
if (sqlite3_bind_parameter_count(self->st) > 0) {
(void)sqlite3_transfer_bindings(self->st, new_st);
}
#endif
#else
statement_bind_parameters(self, params);
#endif
(void)sqlite3_finalize(self->st);
self->st = new_st;
}
return rc;
}
int pysqlite_statement_finalize(pysqlite_Statement* self)
{
int rc;
rc = SQLITE_OK;
if (self->st) {
Py_BEGIN_ALLOW_THREADS
rc = sqlite3_finalize(self->st);
Py_END_ALLOW_THREADS
self->st = NULL;
}
self->in_use = 0;
return rc;
}
int pysqlite_statement_reset(pysqlite_Statement* self)
{
int rc;
rc = SQLITE_OK;
if (self->in_use && self->st) {
Py_BEGIN_ALLOW_THREADS
rc = sqlite3_reset(self->st);
Py_END_ALLOW_THREADS
if (rc == SQLITE_OK) {
self->in_use = 0;
}
}
return rc;
}
void pysqlite_statement_mark_dirty(pysqlite_Statement* self)
{
self->in_use = 1;
}
void pysqlite_statement_dealloc(pysqlite_Statement* self)
{
if (self->st) {
Py_BEGIN_ALLOW_THREADS
sqlite3_finalize(self->st);
Py_END_ALLOW_THREADS
}
self->st = NULL;
Py_XDECREF(self->sql);
if (self->in_weakreflist != NULL) {
PyObject_ClearWeakRefs((PyObject*)self);
}
Py_TYPE(self)->tp_free((PyObject*)self);
}
/*
* Checks if there is anything left in an SQL string after SQLite compiled it.
* This is used to check if somebody tried to execute more than one SQL command
* with one execute()/executemany() command, which the DB-API and we don't
* allow.
*
* Returns 1 if there is more left than should be. 0 if ok.
*/
static int pysqlite_check_remaining_sql(const char* tail)
{
const char* pos = tail;
parse_remaining_sql_state state = NORMAL;
for (;;) {
switch (*pos) {
case 0:
return 0;
case '-':
if (state == NORMAL) {
state = LINECOMMENT_1;
} else if (state == LINECOMMENT_1) {
state = IN_LINECOMMENT;
}
break;
case ' ':
case '\t':
break;
case '\n':
case 13:
if (state == IN_LINECOMMENT) {
state = NORMAL;
}
break;
case '/':
if (state == NORMAL) {
state = COMMENTSTART_1;
} else if (state == COMMENTEND_1) {
state = NORMAL;
} else if (state == COMMENTSTART_1) {
return 1;
}
break;
case '*':
if (state == NORMAL) {
return 1;
} else if (state == LINECOMMENT_1) {
return 1;
} else if (state == COMMENTSTART_1) {
state = IN_COMMENT;
} else if (state == IN_COMMENT) {
state = COMMENTEND_1;
}
break;
default:
if (state == COMMENTEND_1) {
state = IN_COMMENT;
} else if (state == IN_LINECOMMENT) {
} else if (state == IN_COMMENT) {
} else {
return 1;
}
}
pos++;
}
return 0;
}
PyTypeObject pysqlite_StatementType = {
PyVarObject_HEAD_INIT(NULL, 0)
"sqlite3.Statement", /* tp_name */
sizeof(pysqlite_Statement), /* tp_basicsize */
0, /* tp_itemsize */
(destructor)pysqlite_statement_dealloc, /* tp_dealloc */
0, /* tp_print */
0, /* tp_getattr */
0, /* tp_setattr */
0, /* tp_reserved */
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 */
offsetof(pysqlite_Statement, in_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 */
(initproc)0, /* tp_init */
0, /* tp_alloc */
0, /* tp_new */
0 /* tp_free */
};
extern int pysqlite_statement_setup_types(void)
{
pysqlite_StatementType.tp_new = PyType_GenericNew;
return PyType_Ready(&pysqlite_StatementType);
}
| 19,919 | 553 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Modules/_sqlite/row.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:8;coding:utf-8 -*-â
âvi: set net ft=c ts=4 sts=4 sw=4 fenc=utf-8 :viâ
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ¡
â â
â Copyright (C) 2005-2010 Gerhard Häring <[email protected]> â
â â
â This file is part of pysqlite. â
â â
â This software is provided 'as-is', without any express or implied â
â warranty. In no event will the authors be held liable for any damages â
â arising from the use of this software. â
â â
â Permission is granted to anyone to use this software for any purpose, â
â including commercial applications, and to alter it and redistribute it â
â freely, subject to the following restrictions: â
â â
â 1. The origin of this software must not be misrepresented; you must not â
â claim that you wrote the original software. If you use this software â
â in a product, an acknowledgment in the product documentation would be â
â appreciated but is not required. â
â 2. Altered source versions must be plainly marked as such, and must not be â
â misrepresented as being the original software. â
â 3. This notice may not be removed or altered from any source distribution. â
â â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
#include "third_party/python/Modules/_sqlite/cursor.h"
#include "third_party/python/Modules/_sqlite/row.h"
asm(".ident\t\"\\n\\n\
pysqlite (zlib license)\\n\
Copyright (C) 2005-2010 Gerhard Häring <[email protected]>\"");
asm(".include \"libc/disclaimer.inc\"");
/* clang-format off */
void pysqlite_row_dealloc(pysqlite_Row* self)
{
Py_XDECREF(self->data);
Py_XDECREF(self->description);
Py_TYPE(self)->tp_free((PyObject*)self);
}
static PyObject *
pysqlite_row_new(PyTypeObject *type, PyObject *args, PyObject *kwargs)
{
pysqlite_Row *self;
PyObject* data;
pysqlite_Cursor* cursor;
assert(type != NULL && type->tp_alloc != NULL);
if (!_PyArg_NoKeywords("Row()", kwargs))
return NULL;
if (!PyArg_ParseTuple(args, "OO", &cursor, &data))
return NULL;
if (!PyObject_TypeCheck((PyObject*)cursor, &pysqlite_CursorType)) {
PyErr_SetString(PyExc_TypeError, "instance of cursor required for first argument");
return NULL;
}
if (!PyTuple_Check(data)) {
PyErr_SetString(PyExc_TypeError, "tuple required for second argument");
return NULL;
}
self = (pysqlite_Row *) type->tp_alloc(type, 0);
if (self == NULL)
return NULL;
Py_INCREF(data);
self->data = data;
Py_INCREF(cursor->description);
self->description = cursor->description;
return (PyObject *) self;
}
PyObject* pysqlite_row_item(pysqlite_Row* self, Py_ssize_t idx)
{
PyObject* item = PyTuple_GetItem(self->data, idx);
Py_XINCREF(item);
return item;
}
PyObject* pysqlite_row_subscript(pysqlite_Row* self, PyObject* idx)
{
Py_ssize_t _idx;
char* key;
Py_ssize_t nitems, i;
char* compare_key;
char* p1;
char* p2;
PyObject* item;
if (PyLong_Check(idx)) {
_idx = PyNumber_AsSsize_t(idx, PyExc_IndexError);
if (_idx == -1 && PyErr_Occurred())
return NULL;
if (_idx < 0)
_idx += PyTuple_GET_SIZE(self->data);
item = PyTuple_GetItem(self->data, _idx);
Py_XINCREF(item);
return item;
} else if (PyUnicode_Check(idx)) {
key = PyUnicode_AsUTF8(idx);
if (key == NULL)
return NULL;
nitems = PyTuple_Size(self->description);
for (i = 0; i < nitems; i++) {
PyObject *obj;
obj = PyTuple_GET_ITEM(self->description, i);
obj = PyTuple_GET_ITEM(obj, 0);
compare_key = PyUnicode_AsUTF8(obj);
if (!compare_key) {
return NULL;
}
p1 = key;
p2 = compare_key;
while (1) {
if ((*p1 == (char)0) || (*p2 == (char)0)) {
break;
}
if ((*p1 | 0x20) != (*p2 | 0x20)) {
break;
}
p1++;
p2++;
}
if ((*p1 == (char)0) && (*p2 == (char)0)) {
/* found item */
item = PyTuple_GetItem(self->data, i);
Py_INCREF(item);
return item;
}
}
PyErr_SetString(PyExc_IndexError, "No item with that key");
return NULL;
}
else if (PySlice_Check(idx)) {
return PyObject_GetItem(self->data, idx);
}
else {
PyErr_SetString(PyExc_IndexError, "Index must be int or string");
return NULL;
}
}
static Py_ssize_t
pysqlite_row_length(pysqlite_Row* self)
{
return PyTuple_GET_SIZE(self->data);
}
PyObject* pysqlite_row_keys(pysqlite_Row* self, PyObject* args, PyObject* kwargs)
{
PyObject* list;
Py_ssize_t nitems, i;
list = PyList_New(0);
if (!list) {
return NULL;
}
nitems = PyTuple_Size(self->description);
for (i = 0; i < nitems; i++) {
if (PyList_Append(list, PyTuple_GET_ITEM(PyTuple_GET_ITEM(self->description, i), 0)) != 0) {
Py_DECREF(list);
return NULL;
}
}
return list;
}
static int pysqlite_row_print(pysqlite_Row* self, FILE *fp, int flags)
{
return (&PyTuple_Type)->tp_print(self->data, fp, flags);
}
static PyObject* pysqlite_iter(pysqlite_Row* self)
{
return PyObject_GetIter(self->data);
}
static Py_hash_t pysqlite_row_hash(pysqlite_Row *self)
{
return PyObject_Hash(self->description) ^ PyObject_Hash(self->data);
}
static PyObject* pysqlite_row_richcompare(pysqlite_Row *self, PyObject *_other, int opid)
{
if (opid != Py_EQ && opid != Py_NE)
Py_RETURN_NOTIMPLEMENTED;
if (PyType_IsSubtype(Py_TYPE(_other), &pysqlite_RowType)) {
pysqlite_Row *other = (pysqlite_Row *)_other;
PyObject *res = PyObject_RichCompare(self->description, other->description, opid);
if ((opid == Py_EQ && res == Py_True)
|| (opid == Py_NE && res == Py_False)) {
Py_DECREF(res);
return PyObject_RichCompare(self->data, other->data, opid);
}
}
Py_RETURN_NOTIMPLEMENTED;
}
PyMappingMethods pysqlite_row_as_mapping = {
/* mp_length */ (lenfunc)pysqlite_row_length,
/* mp_subscript */ (binaryfunc)pysqlite_row_subscript,
/* mp_ass_subscript */ (objobjargproc)0,
};
static PySequenceMethods pysqlite_row_as_sequence = {
/* sq_length */ (lenfunc)pysqlite_row_length,
/* sq_concat */ 0,
/* sq_repeat */ 0,
/* sq_item */ (ssizeargfunc)pysqlite_row_item,
};
static PyMethodDef pysqlite_row_methods[] = {
{"keys", (PyCFunction)pysqlite_row_keys, METH_NOARGS,
PyDoc_STR("Returns the keys of the row.")},
{NULL, NULL}
};
PyTypeObject pysqlite_RowType = {
PyVarObject_HEAD_INIT(NULL, 0)
"sqlite3.Row", /* tp_name */
sizeof(pysqlite_Row), /* tp_basicsize */
0, /* tp_itemsize */
(destructor)pysqlite_row_dealloc, /* tp_dealloc */
(printfunc)pysqlite_row_print, /* tp_print */
0, /* tp_getattr */
0, /* tp_setattr */
0, /* tp_reserved */
0, /* tp_repr */
0, /* tp_as_number */
0, /* tp_as_sequence */
0, /* tp_as_mapping */
(hashfunc)pysqlite_row_hash, /* 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 */
(traverseproc)0, /* tp_traverse */
0, /* tp_clear */
(richcmpfunc)pysqlite_row_richcompare, /* tp_richcompare */
0, /* tp_weaklistoffset */
(getiterfunc)pysqlite_iter, /* tp_iter */
0, /* tp_iternext */
pysqlite_row_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 */
};
extern int pysqlite_row_setup_types(void)
{
pysqlite_RowType.tp_new = pysqlite_row_new;
pysqlite_RowType.tp_as_mapping = &pysqlite_row_as_mapping;
pysqlite_RowType.tp_as_sequence = &pysqlite_row_as_sequence;
return PyType_Ready(&pysqlite_RowType);
}
| 11,166 | 290 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Modules/_sqlite/prepare_protocol.h | #ifndef PYSQLITE_PREPARE_PROTOCOL_H
#define PYSQLITE_PREPARE_PROTOCOL_H
#include "third_party/python/Include/Python.h"
/* clang-format off */
typedef struct
{
PyObject_HEAD
} pysqlite_PrepareProtocol;
extern PyTypeObject pysqlite_PrepareProtocolType;
int pysqlite_prepare_protocol_init(pysqlite_PrepareProtocol* self, PyObject* args, PyObject* kwargs);
void pysqlite_prepare_protocol_dealloc(pysqlite_PrepareProtocol* self);
int pysqlite_prepare_protocol_setup_types(void);
#define UNKNOWN (-1)
#endif
| 511 | 20 | jart/cosmopolitan | false |
cosmopolitan/third_party/python/Modules/_sqlite/connection.c | /*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:4;tab-width:8;coding:utf-8 -*-â
âvi: set net ft=c ts=4 sts=4 sw=4 fenc=utf-8 :viâ
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ¡
â â
â Copyright (C) 2005-2010 Gerhard Häring <[email protected]> â
â â
â This file is part of pysqlite. â
â â
â This software is provided 'as-is', without any express or implied â
â warranty. In no event will the authors be held liable for any damages â
â arising from the use of this software. â
â â
â Permission is granted to anyone to use this software for any purpose, â
â including commercial applications, and to alter it and redistribute it â
â freely, subject to the following restrictions: â
â â
â 1. The origin of this software must not be misrepresented; you must not â
â claim that you wrote the original software. If you use this software â
â in a product, an acknowledgment in the product documentation would be â
â appreciated but is not required. â
â 2. Altered source versions must be plainly marked as such, and must not be â
â misrepresented as being the original software. â
â 3. This notice may not be removed or altered from any source distribution. â
â â
ââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ*/
#include "third_party/python/Include/pythread.h"
#include "third_party/python/Include/structmember.h"
#include "third_party/python/Include/yoink.h"
#include "third_party/python/Modules/_sqlite/cache.h"
#include "third_party/python/Modules/_sqlite/connection.h"
#include "third_party/python/Modules/_sqlite/cursor.h"
#include "third_party/python/Modules/_sqlite/module.h"
#include "third_party/python/Modules/_sqlite/prepare_protocol.h"
#include "third_party/python/Modules/_sqlite/statement.h"
#include "third_party/python/Modules/_sqlite/util.h"
PYTHON_YOINK("sqlite3.dump");
asm(".ident\t\"\\n\\n\
pysqlite (zlib license)\\n\
Copyright (C) 2005-2010 Gerhard Häring <[email protected]>\"");
asm(".include \"libc/disclaimer.inc\"");
/* clang-format off */
#define ACTION_FINALIZE 1
#define ACTION_RESET 2
_Py_IDENTIFIER(cursor);
static const char * const begin_statements[] = {
"BEGIN ",
"BEGIN DEFERRED",
"BEGIN IMMEDIATE",
"BEGIN EXCLUSIVE",
NULL
};
static int pysqlite_connection_set_isolation_level(pysqlite_Connection* self, PyObject* isolation_level, void *Py_UNUSED(ignored));
static void _pysqlite_drop_unused_cursor_references(pysqlite_Connection* self);
static void _sqlite3_result_error(sqlite3_context* ctx, const char* errmsg, int len)
{
/* in older SQLite versions, calling sqlite3_result_error in callbacks
* triggers a bug in SQLite that leads either to irritating results or
* segfaults, depending on the SQLite version */
#if SQLITE_VERSION_NUMBER >= 3003003
sqlite3_result_error(ctx, errmsg, len);
#else
PyErr_SetString(pysqlite_OperationalError, errmsg);
#endif
}
int pysqlite_connection_init(pysqlite_Connection* self, PyObject* args, PyObject* kwargs)
{
static char *kwlist[] = {
"database", "timeout", "detect_types", "isolation_level",
"check_same_thread", "factory", "cached_statements", "uri",
NULL
};
char* database;
int detect_types = 0;
PyObject* isolation_level = NULL;
PyObject* factory = NULL;
int check_same_thread = 1;
int cached_statements = 100;
int uri = 0;
double timeout = 5.0;
int rc;
if (!PyArg_ParseTupleAndKeywords(args, kwargs, "s|diOiOip", kwlist,
&database, &timeout, &detect_types,
&isolation_level, &check_same_thread,
&factory, &cached_statements, &uri))
{
return -1;
}
self->initialized = 1;
self->begin_statement = NULL;
self->statement_cache = NULL;
self->statements = NULL;
self->cursors = NULL;
Py_INCREF(Py_None);
self->row_factory = Py_None;
Py_INCREF(&PyUnicode_Type);
self->text_factory = (PyObject*)&PyUnicode_Type;
#ifdef SQLITE_OPEN_URI
Py_BEGIN_ALLOW_THREADS
rc = sqlite3_open_v2(database, &self->db,
SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE |
(uri ? SQLITE_OPEN_URI : 0), NULL);
#else
if (uri) {
PyErr_SetString(pysqlite_NotSupportedError, "URIs not supported");
return -1;
}
Py_BEGIN_ALLOW_THREADS
rc = sqlite3_open(database, &self->db);
#endif
Py_END_ALLOW_THREADS
if (rc != SQLITE_OK) {
_pysqlite_seterror(self->db, NULL);
return -1;
}
if (!isolation_level) {
isolation_level = PyUnicode_FromString("");
if (!isolation_level) {
return -1;
}
} else {
Py_INCREF(isolation_level);
}
self->isolation_level = NULL;
if (pysqlite_connection_set_isolation_level(self, isolation_level, NULL) < 0) {
Py_DECREF(isolation_level);
return -1;
}
Py_DECREF(isolation_level);
self->statement_cache = (pysqlite_Cache*)PyObject_CallFunction((PyObject*)&pysqlite_CacheType, "Oi", self, cached_statements);
if (PyErr_Occurred()) {
return -1;
}
self->created_statements = 0;
self->created_cursors = 0;
/* Create lists of weak references to statements/cursors */
self->statements = PyList_New(0);
self->cursors = PyList_New(0);
if (!self->statements || !self->cursors) {
return -1;
}
/* By default, the Cache class INCREFs the factory in its initializer, and
* decrefs it in its deallocator method. Since this would create a circular
* reference here, we're breaking it by decrementing self, and telling the
* cache class to not decref the factory (self) in its deallocator.
*/
self->statement_cache->decref_factory = 0;
Py_DECREF(self);
self->detect_types = detect_types;
self->timeout = timeout;
(void)sqlite3_busy_timeout(self->db, (int)(timeout*1000));
#ifdef WITH_THREAD
self->thread_ident = PyThread_get_thread_ident();
#endif
if (!check_same_thread && sqlite3_libversion_number() < 3003001) {
PyErr_SetString(pysqlite_NotSupportedError, "shared connections not available");
return -1;
}
self->check_same_thread = check_same_thread;
self->function_pinboard = PyDict_New();
if (!self->function_pinboard) {
return -1;
}
self->collations = PyDict_New();
if (!self->collations) {
return -1;
}
self->Warning = pysqlite_Warning;
self->Error = pysqlite_Error;
self->InterfaceError = pysqlite_InterfaceError;
self->DatabaseError = pysqlite_DatabaseError;
self->DataError = pysqlite_DataError;
self->OperationalError = pysqlite_OperationalError;
self->IntegrityError = pysqlite_IntegrityError;
self->InternalError = pysqlite_InternalError;
self->ProgrammingError = pysqlite_ProgrammingError;
self->NotSupportedError = pysqlite_NotSupportedError;
return 0;
}
/* action in (ACTION_RESET, ACTION_FINALIZE) */
void pysqlite_do_all_statements(pysqlite_Connection* self, int action, int reset_cursors)
{
int i;
PyObject* weakref;
PyObject* statement;
pysqlite_Cursor* cursor;
for (i = 0; i < PyList_Size(self->statements); i++) {
weakref = PyList_GetItem(self->statements, i);
statement = PyWeakref_GetObject(weakref);
if (statement != Py_None) {
Py_INCREF(statement);
if (action == ACTION_RESET) {
(void)pysqlite_statement_reset((pysqlite_Statement*)statement);
} else {
(void)pysqlite_statement_finalize((pysqlite_Statement*)statement);
}
Py_DECREF(statement);
}
}
if (reset_cursors) {
for (i = 0; i < PyList_Size(self->cursors); i++) {
weakref = PyList_GetItem(self->cursors, i);
cursor = (pysqlite_Cursor*)PyWeakref_GetObject(weakref);
if ((PyObject*)cursor != Py_None) {
cursor->reset = 1;
}
}
}
}
void pysqlite_connection_dealloc(pysqlite_Connection* self)
{
Py_XDECREF(self->statement_cache);
/* Clean up if user has not called .close() explicitly. */
if (self->db) {
Py_BEGIN_ALLOW_THREADS
sqlite3_close(self->db);
Py_END_ALLOW_THREADS
}
Py_XDECREF(self->isolation_level);
Py_XDECREF(self->function_pinboard);
Py_XDECREF(self->row_factory);
Py_XDECREF(self->text_factory);
Py_XDECREF(self->collations);
Py_XDECREF(self->statements);
Py_XDECREF(self->cursors);
Py_TYPE(self)->tp_free((PyObject*)self);
}
/*
* Registers a cursor with the connection.
*
* 0 => error; 1 => ok
*/
int pysqlite_connection_register_cursor(pysqlite_Connection* connection, PyObject* cursor)
{
PyObject* weakref;
weakref = PyWeakref_NewRef((PyObject*)cursor, NULL);
if (!weakref) {
goto error;
}
if (PyList_Append(connection->cursors, weakref) != 0) {
Py_CLEAR(weakref);
goto error;
}
Py_DECREF(weakref);
return 1;
error:
return 0;
}
PyObject* pysqlite_connection_cursor(pysqlite_Connection* self, PyObject* args, PyObject* kwargs)
{
static char *kwlist[] = {"factory", NULL};
PyObject* factory = NULL;
PyObject* cursor;
if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|O", kwlist,
&factory)) {
return NULL;
}
if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
return NULL;
}
if (factory == NULL) {
factory = (PyObject*)&pysqlite_CursorType;
}
cursor = PyObject_CallFunctionObjArgs(factory, (PyObject *)self, NULL);
if (cursor == NULL)
return NULL;
if (!PyObject_TypeCheck(cursor, &pysqlite_CursorType)) {
PyErr_Format(PyExc_TypeError,
"factory must return a cursor, not %.100s",
Py_TYPE(cursor)->tp_name);
Py_DECREF(cursor);
return NULL;
}
_pysqlite_drop_unused_cursor_references(self);
if (cursor && self->row_factory != Py_None) {
Py_INCREF(self->row_factory);
Py_XSETREF(((pysqlite_Cursor *)cursor)->row_factory, self->row_factory);
}
return cursor;
}
PyObject* pysqlite_connection_close(pysqlite_Connection* self, PyObject* args)
{
int rc;
if (!pysqlite_check_thread(self)) {
return NULL;
}
pysqlite_do_all_statements(self, ACTION_FINALIZE, 1);
if (self->db) {
Py_BEGIN_ALLOW_THREADS
rc = sqlite3_close(self->db);
Py_END_ALLOW_THREADS
if (rc != SQLITE_OK) {
_pysqlite_seterror(self->db, NULL);
return NULL;
} else {
self->db = NULL;
}
}
Py_RETURN_NONE;
}
/*
* Checks if a connection object is usable (i. e. not closed).
*
* 0 => error; 1 => ok
*/
int pysqlite_check_connection(pysqlite_Connection* con)
{
if (!con->initialized) {
PyErr_SetString(pysqlite_ProgrammingError, "Base Connection.__init__ not called.");
return 0;
}
if (!con->db) {
PyErr_SetString(pysqlite_ProgrammingError, "Cannot operate on a closed database.");
return 0;
} else {
return 1;
}
}
PyObject* _pysqlite_connection_begin(pysqlite_Connection* self)
{
int rc;
const char* tail;
sqlite3_stmt* statement;
Py_BEGIN_ALLOW_THREADS
rc = sqlite3_prepare(self->db, self->begin_statement, -1, &statement, &tail);
Py_END_ALLOW_THREADS
if (rc != SQLITE_OK) {
_pysqlite_seterror(self->db, statement);
goto error;
}
rc = pysqlite_step(statement, self);
if (rc != SQLITE_DONE) {
_pysqlite_seterror(self->db, statement);
}
Py_BEGIN_ALLOW_THREADS
rc = sqlite3_finalize(statement);
Py_END_ALLOW_THREADS
if (rc != SQLITE_OK && !PyErr_Occurred()) {
_pysqlite_seterror(self->db, NULL);
}
error:
if (PyErr_Occurred()) {
return NULL;
} else {
Py_INCREF(Py_None);
return Py_None;
}
}
PyObject* pysqlite_connection_commit(pysqlite_Connection* self, PyObject* args)
{
int rc;
const char* tail;
sqlite3_stmt* statement;
if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
return NULL;
}
if (!sqlite3_get_autocommit(self->db)) {
Py_BEGIN_ALLOW_THREADS
rc = sqlite3_prepare(self->db, "COMMIT", -1, &statement, &tail);
Py_END_ALLOW_THREADS
if (rc != SQLITE_OK) {
_pysqlite_seterror(self->db, NULL);
goto error;
}
rc = pysqlite_step(statement, self);
if (rc != SQLITE_DONE) {
_pysqlite_seterror(self->db, statement);
}
Py_BEGIN_ALLOW_THREADS
rc = sqlite3_finalize(statement);
Py_END_ALLOW_THREADS
if (rc != SQLITE_OK && !PyErr_Occurred()) {
_pysqlite_seterror(self->db, NULL);
}
}
error:
if (PyErr_Occurred()) {
return NULL;
} else {
Py_INCREF(Py_None);
return Py_None;
}
}
PyObject* pysqlite_connection_rollback(pysqlite_Connection* self, PyObject* args)
{
int rc;
const char* tail;
sqlite3_stmt* statement;
if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
return NULL;
}
if (!sqlite3_get_autocommit(self->db)) {
pysqlite_do_all_statements(self, ACTION_RESET, 1);
Py_BEGIN_ALLOW_THREADS
rc = sqlite3_prepare(self->db, "ROLLBACK", -1, &statement, &tail);
Py_END_ALLOW_THREADS
if (rc != SQLITE_OK) {
_pysqlite_seterror(self->db, NULL);
goto error;
}
rc = pysqlite_step(statement, self);
if (rc != SQLITE_DONE) {
_pysqlite_seterror(self->db, statement);
}
Py_BEGIN_ALLOW_THREADS
rc = sqlite3_finalize(statement);
Py_END_ALLOW_THREADS
if (rc != SQLITE_OK && !PyErr_Occurred()) {
_pysqlite_seterror(self->db, NULL);
}
}
error:
if (PyErr_Occurred()) {
return NULL;
} else {
Py_INCREF(Py_None);
return Py_None;
}
}
static int
_pysqlite_set_result(sqlite3_context* context, PyObject* py_val)
{
if (py_val == Py_None) {
sqlite3_result_null(context);
} else if (PyLong_Check(py_val)) {
sqlite_int64 value = _pysqlite_long_as_int64(py_val);
if (value == -1 && PyErr_Occurred())
return -1;
sqlite3_result_int64(context, value);
} else if (PyFloat_Check(py_val)) {
sqlite3_result_double(context, PyFloat_AsDouble(py_val));
} else if (PyUnicode_Check(py_val)) {
const char *str = PyUnicode_AsUTF8(py_val);
if (str == NULL)
return -1;
sqlite3_result_text(context, str, -1, SQLITE_TRANSIENT);
} else if (PyObject_CheckBuffer(py_val)) {
Py_buffer view;
if (PyObject_GetBuffer(py_val, &view, PyBUF_SIMPLE) != 0) {
PyErr_SetString(PyExc_ValueError,
"could not convert BLOB to buffer");
return -1;
}
if (view.len > INT_MAX) {
PyErr_SetString(PyExc_OverflowError,
"BLOB longer than INT_MAX bytes");
PyBuffer_Release(&view);
return -1;
}
sqlite3_result_blob(context, view.buf, (int)view.len, SQLITE_TRANSIENT);
PyBuffer_Release(&view);
} else {
return -1;
}
return 0;
}
PyObject* _pysqlite_build_py_params(sqlite3_context *context, int argc, sqlite3_value** argv)
{
PyObject* args;
int i;
sqlite3_value* cur_value;
PyObject* cur_py_value;
const char* val_str;
Py_ssize_t buflen;
args = PyTuple_New(argc);
if (!args) {
return NULL;
}
for (i = 0; i < argc; i++) {
cur_value = argv[i];
switch (sqlite3_value_type(argv[i])) {
case SQLITE_INTEGER:
cur_py_value = _pysqlite_long_from_int64(sqlite3_value_int64(cur_value));
break;
case SQLITE_FLOAT:
cur_py_value = PyFloat_FromDouble(sqlite3_value_double(cur_value));
break;
case SQLITE_TEXT:
val_str = (const char*)sqlite3_value_text(cur_value);
cur_py_value = PyUnicode_FromString(val_str);
/* TODO: have a way to show errors here */
if (!cur_py_value) {
PyErr_Clear();
Py_INCREF(Py_None);
cur_py_value = Py_None;
}
break;
case SQLITE_BLOB:
buflen = sqlite3_value_bytes(cur_value);
cur_py_value = PyBytes_FromStringAndSize(
sqlite3_value_blob(cur_value), buflen);
break;
case SQLITE_NULL:
default:
Py_INCREF(Py_None);
cur_py_value = Py_None;
}
if (!cur_py_value) {
Py_DECREF(args);
return NULL;
}
PyTuple_SetItem(args, i, cur_py_value);
}
return args;
}
void _pysqlite_func_callback(sqlite3_context* context, int argc, sqlite3_value** argv)
{
PyObject* args;
PyObject* py_func;
PyObject* py_retval = NULL;
int ok;
#ifdef WITH_THREAD
PyGILState_STATE threadstate;
threadstate = PyGILState_Ensure();
#endif
py_func = (PyObject*)sqlite3_user_data(context);
args = _pysqlite_build_py_params(context, argc, argv);
if (args) {
py_retval = PyObject_CallObject(py_func, args);
Py_DECREF(args);
}
ok = 0;
if (py_retval) {
ok = _pysqlite_set_result(context, py_retval) == 0;
Py_DECREF(py_retval);
}
if (!ok) {
if (_pysqlite_enable_callback_tracebacks) {
PyErr_Print();
} else {
PyErr_Clear();
}
_sqlite3_result_error(context, "user-defined function raised exception", -1);
}
#ifdef WITH_THREAD
PyGILState_Release(threadstate);
#endif
}
static void _pysqlite_step_callback(sqlite3_context *context, int argc, sqlite3_value** params)
{
PyObject* args;
PyObject* function_result = NULL;
PyObject* aggregate_class;
PyObject** aggregate_instance;
PyObject* stepmethod = NULL;
#ifdef WITH_THREAD
PyGILState_STATE threadstate;
threadstate = PyGILState_Ensure();
#endif
aggregate_class = (PyObject*)sqlite3_user_data(context);
aggregate_instance = (PyObject**)sqlite3_aggregate_context(context, sizeof(PyObject*));
if (*aggregate_instance == 0) {
*aggregate_instance = PyObject_CallFunction(aggregate_class, NULL);
if (PyErr_Occurred()) {
*aggregate_instance = 0;
if (_pysqlite_enable_callback_tracebacks) {
PyErr_Print();
} else {
PyErr_Clear();
}
_sqlite3_result_error(context, "user-defined aggregate's '__init__' method raised error", -1);
goto error;
}
}
stepmethod = PyObject_GetAttrString(*aggregate_instance, "step");
if (!stepmethod) {
goto error;
}
args = _pysqlite_build_py_params(context, argc, params);
if (!args) {
goto error;
}
function_result = PyObject_CallObject(stepmethod, args);
Py_DECREF(args);
if (!function_result) {
if (_pysqlite_enable_callback_tracebacks) {
PyErr_Print();
} else {
PyErr_Clear();
}
_sqlite3_result_error(context, "user-defined aggregate's 'step' method raised error", -1);
}
error:
Py_XDECREF(stepmethod);
Py_XDECREF(function_result);
#ifdef WITH_THREAD
PyGILState_Release(threadstate);
#endif
}
void _pysqlite_final_callback(sqlite3_context* context)
{
PyObject* function_result;
PyObject** aggregate_instance;
_Py_IDENTIFIER(finalize);
int ok;
PyObject *exception, *value, *tb;
int restore;
#ifdef WITH_THREAD
PyGILState_STATE threadstate;
threadstate = PyGILState_Ensure();
#endif
aggregate_instance = (PyObject**)sqlite3_aggregate_context(context, sizeof(PyObject*));
if (!*aggregate_instance) {
/* this branch is executed if there was an exception in the aggregate's
* __init__ */
goto error;
}
/* Keep the exception (if any) of the last call to step() */
PyErr_Fetch(&exception, &value, &tb);
restore = 1;
function_result = _PyObject_CallMethodId(*aggregate_instance, &PyId_finalize, NULL);
Py_DECREF(*aggregate_instance);
ok = 0;
if (function_result) {
ok = _pysqlite_set_result(context, function_result) == 0;
Py_DECREF(function_result);
}
if (!ok) {
if (_pysqlite_enable_callback_tracebacks) {
PyErr_Print();
} else {
PyErr_Clear();
}
_sqlite3_result_error(context, "user-defined aggregate's 'finalize' method raised error", -1);
#if SQLITE_VERSION_NUMBER < 3003003
/* with old SQLite versions, _sqlite3_result_error() sets a new Python
exception, so don't restore the previous exception */
restore = 0;
#endif
}
if (restore) {
/* Restore the exception (if any) of the last call to step(),
but clear also the current exception if finalize() failed */
PyErr_Restore(exception, value, tb);
}
error:
#ifdef WITH_THREAD
PyGILState_Release(threadstate);
#endif
/* explicit return to avoid a compilation error if WITH_THREAD
is not defined */
return;
}
static void _pysqlite_drop_unused_statement_references(pysqlite_Connection* self)
{
PyObject* new_list;
PyObject* weakref;
int i;
/* we only need to do this once in a while */
if (self->created_statements++ < 200) {
return;
}
self->created_statements = 0;
new_list = PyList_New(0);
if (!new_list) {
return;
}
for (i = 0; i < PyList_Size(self->statements); i++) {
weakref = PyList_GetItem(self->statements, i);
if (PyWeakref_GetObject(weakref) != Py_None) {
if (PyList_Append(new_list, weakref) != 0) {
Py_DECREF(new_list);
return;
}
}
}
Py_SETREF(self->statements, new_list);
}
static void _pysqlite_drop_unused_cursor_references(pysqlite_Connection* self)
{
PyObject* new_list;
PyObject* weakref;
int i;
/* we only need to do this once in a while */
if (self->created_cursors++ < 200) {
return;
}
self->created_cursors = 0;
new_list = PyList_New(0);
if (!new_list) {
return;
}
for (i = 0; i < PyList_Size(self->cursors); i++) {
weakref = PyList_GetItem(self->cursors, i);
if (PyWeakref_GetObject(weakref) != Py_None) {
if (PyList_Append(new_list, weakref) != 0) {
Py_DECREF(new_list);
return;
}
}
}
Py_SETREF(self->cursors, new_list);
}
PyObject* pysqlite_connection_create_function(pysqlite_Connection* self, PyObject* args, PyObject* kwargs)
{
static char *kwlist[] = {"name", "narg", "func", NULL, NULL};
PyObject* func;
char* name;
int narg;
int rc;
if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
return NULL;
}
if (!PyArg_ParseTupleAndKeywords(args, kwargs, "siO", kwlist,
&name, &narg, &func))
{
return NULL;
}
if (PyDict_SetItem(self->function_pinboard, func, Py_None) == -1) {
return NULL;
}
rc = sqlite3_create_function(self->db, name, narg, SQLITE_UTF8, (void*)func, _pysqlite_func_callback, NULL, NULL);
if (rc != SQLITE_OK) {
/* Workaround for SQLite bug: no error code or string is available here */
PyErr_SetString(pysqlite_OperationalError, "Error creating function");
return NULL;
}
Py_RETURN_NONE;
}
PyObject* pysqlite_connection_create_aggregate(pysqlite_Connection* self, PyObject* args, PyObject* kwargs)
{
PyObject* aggregate_class;
int n_arg;
char* name;
static char *kwlist[] = { "name", "n_arg", "aggregate_class", NULL };
int rc;
if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
return NULL;
}
if (!PyArg_ParseTupleAndKeywords(args, kwargs, "siO:create_aggregate",
kwlist, &name, &n_arg, &aggregate_class)) {
return NULL;
}
if (PyDict_SetItem(self->function_pinboard, aggregate_class, Py_None) == -1) {
return NULL;
}
rc = sqlite3_create_function(self->db, name, n_arg, SQLITE_UTF8, (void*)aggregate_class, 0, &_pysqlite_step_callback, &_pysqlite_final_callback);
if (rc != SQLITE_OK) {
/* Workaround for SQLite bug: no error code or string is available here */
PyErr_SetString(pysqlite_OperationalError, "Error creating aggregate");
return NULL;
}
Py_RETURN_NONE;
}
static int _authorizer_callback(void* user_arg, int action, const char* arg1, const char* arg2 , const char* dbname, const char* access_attempt_source)
{
PyObject *ret;
int rc;
#ifdef WITH_THREAD
PyGILState_STATE gilstate;
gilstate = PyGILState_Ensure();
#endif
ret = PyObject_CallFunction((PyObject*)user_arg, "issss", action, arg1, arg2, dbname, access_attempt_source);
if (ret == NULL) {
if (_pysqlite_enable_callback_tracebacks)
PyErr_Print();
else
PyErr_Clear();
rc = SQLITE_DENY;
}
else {
if (PyLong_Check(ret)) {
rc = _PyLong_AsInt(ret);
if (rc == -1 && PyErr_Occurred()) {
if (_pysqlite_enable_callback_tracebacks)
PyErr_Print();
else
PyErr_Clear();
rc = SQLITE_DENY;
}
}
else {
rc = SQLITE_DENY;
}
Py_DECREF(ret);
}
#ifdef WITH_THREAD
PyGILState_Release(gilstate);
#endif
return rc;
}
static int _progress_handler(void* user_arg)
{
int rc;
PyObject *ret;
#ifdef WITH_THREAD
PyGILState_STATE gilstate;
gilstate = PyGILState_Ensure();
#endif
ret = PyObject_CallFunction((PyObject*)user_arg, NULL);
if (!ret) {
if (_pysqlite_enable_callback_tracebacks) {
PyErr_Print();
} else {
PyErr_Clear();
}
/* abort query if error occurred */
rc = 1;
} else {
rc = (int)PyObject_IsTrue(ret);
Py_DECREF(ret);
}
#ifdef WITH_THREAD
PyGILState_Release(gilstate);
#endif
return rc;
}
static void _trace_callback(void* user_arg, const char* statement_string)
{
PyObject *py_statement = NULL;
PyObject *ret = NULL;
#ifdef WITH_THREAD
PyGILState_STATE gilstate;
gilstate = PyGILState_Ensure();
#endif
py_statement = PyUnicode_DecodeUTF8(statement_string,
strlen(statement_string), "replace");
if (py_statement) {
ret = PyObject_CallFunctionObjArgs((PyObject*)user_arg, py_statement, NULL);
Py_DECREF(py_statement);
}
if (ret) {
Py_DECREF(ret);
} else {
if (_pysqlite_enable_callback_tracebacks) {
PyErr_Print();
} else {
PyErr_Clear();
}
}
#ifdef WITH_THREAD
PyGILState_Release(gilstate);
#endif
}
static PyObject* pysqlite_connection_set_authorizer(pysqlite_Connection* self, PyObject* args, PyObject* kwargs)
{
PyObject* authorizer_cb;
static char *kwlist[] = { "authorizer_callback", NULL };
int rc;
if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
return NULL;
}
if (!PyArg_ParseTupleAndKeywords(args, kwargs, "O:set_authorizer",
kwlist, &authorizer_cb)) {
return NULL;
}
if (PyDict_SetItem(self->function_pinboard, authorizer_cb, Py_None) == -1) {
return NULL;
}
rc = sqlite3_set_authorizer(self->db, _authorizer_callback, (void*)authorizer_cb);
if (rc != SQLITE_OK) {
PyErr_SetString(pysqlite_OperationalError, "Error setting authorizer callback");
return NULL;
}
Py_RETURN_NONE;
}
static PyObject* pysqlite_connection_set_progress_handler(pysqlite_Connection* self, PyObject* args, PyObject* kwargs)
{
PyObject* progress_handler;
int n;
static char *kwlist[] = { "progress_handler", "n", NULL };
if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
return NULL;
}
if (!PyArg_ParseTupleAndKeywords(args, kwargs, "Oi:set_progress_handler",
kwlist, &progress_handler, &n)) {
return NULL;
}
if (progress_handler == Py_None) {
/* None clears the progress handler previously set */
sqlite3_progress_handler(self->db, 0, 0, (void*)0);
} else {
if (PyDict_SetItem(self->function_pinboard, progress_handler, Py_None) == -1)
return NULL;
sqlite3_progress_handler(self->db, n, _progress_handler, progress_handler);
}
Py_RETURN_NONE;
}
static PyObject* pysqlite_connection_set_trace_callback(pysqlite_Connection* self, PyObject* args, PyObject* kwargs)
{
PyObject* trace_callback;
static char *kwlist[] = { "trace_callback", NULL };
if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
return NULL;
}
if (!PyArg_ParseTupleAndKeywords(args, kwargs, "O:set_trace_callback",
kwlist, &trace_callback)) {
return NULL;
}
if (trace_callback == Py_None) {
/* None clears the trace callback previously set */
sqlite3_trace(self->db, 0, (void*)0);
} else {
if (PyDict_SetItem(self->function_pinboard, trace_callback, Py_None) == -1)
return NULL;
sqlite3_trace(self->db, _trace_callback, trace_callback);
}
Py_RETURN_NONE;
}
#ifdef HAVE_LOAD_EXTENSION
static PyObject* pysqlite_enable_load_extension(pysqlite_Connection* self, PyObject* args)
{
int rc;
int onoff;
if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
return NULL;
}
if (!PyArg_ParseTuple(args, "i", &onoff)) {
return NULL;
}
rc = sqlite3_enable_load_extension(self->db, onoff);
if (rc != SQLITE_OK) {
PyErr_SetString(pysqlite_OperationalError, "Error enabling load extension");
return NULL;
} else {
Py_RETURN_NONE;
}
}
static PyObject* pysqlite_load_extension(pysqlite_Connection* self, PyObject* args)
{
int rc;
char* extension_name;
char* errmsg;
if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
return NULL;
}
if (!PyArg_ParseTuple(args, "s", &extension_name)) {
return NULL;
}
rc = sqlite3_load_extension(self->db, extension_name, 0, &errmsg);
if (rc != 0) {
PyErr_SetString(pysqlite_OperationalError, errmsg);
return NULL;
} else {
Py_RETURN_NONE;
}
}
#endif
int pysqlite_check_thread(pysqlite_Connection* self)
{
#ifdef WITH_THREAD
if (self->check_same_thread) {
if (PyThread_get_thread_ident() != self->thread_ident) {
PyErr_Format(pysqlite_ProgrammingError,
"SQLite objects created in a thread can only be used in that same thread. "
"The object was created in thread id %ld and this is thread id %ld.",
self->thread_ident, PyThread_get_thread_ident());
return 0;
}
}
#endif
return 1;
}
static PyObject* pysqlite_connection_get_isolation_level(pysqlite_Connection* self, void* unused)
{
Py_INCREF(self->isolation_level);
return self->isolation_level;
}
static PyObject* pysqlite_connection_get_total_changes(pysqlite_Connection* self, void* unused)
{
if (!pysqlite_check_connection(self)) {
return NULL;
} else {
return Py_BuildValue("i", sqlite3_total_changes(self->db));
}
}
static PyObject* pysqlite_connection_get_in_transaction(pysqlite_Connection* self, void* unused)
{
if (!pysqlite_check_connection(self)) {
return NULL;
}
if (!sqlite3_get_autocommit(self->db)) {
Py_RETURN_TRUE;
}
Py_RETURN_FALSE;
}
static int
pysqlite_connection_set_isolation_level(pysqlite_Connection* self, PyObject* isolation_level, void *Py_UNUSED(ignored))
{
if (isolation_level == Py_None) {
PyObject *res = pysqlite_connection_commit(self, NULL);
if (!res) {
return -1;
}
Py_DECREF(res);
self->begin_statement = NULL;
} else {
const char * const *candidate;
PyObject *uppercase_level;
_Py_IDENTIFIER(upper);
if (!PyUnicode_Check(isolation_level)) {
PyErr_Format(PyExc_TypeError,
"isolation_level must be a string or None, not %.100s",
Py_TYPE(isolation_level)->tp_name);
return -1;
}
uppercase_level = _PyObject_CallMethodIdObjArgs(
(PyObject *)&PyUnicode_Type, &PyId_upper,
isolation_level, NULL);
if (!uppercase_level) {
return -1;
}
for (candidate = begin_statements; *candidate; candidate++) {
if (_PyUnicode_EqualToASCIIString(uppercase_level, *candidate + 6))
break;
}
Py_DECREF(uppercase_level);
if (!*candidate) {
PyErr_SetString(PyExc_ValueError,
"invalid value for isolation_level");
return -1;
}
self->begin_statement = *candidate;
}
Py_INCREF(isolation_level);
Py_XSETREF(self->isolation_level, isolation_level);
return 0;
}
PyObject* pysqlite_connection_call(pysqlite_Connection* self, PyObject* args, PyObject* kwargs)
{
PyObject* sql;
pysqlite_Statement* statement;
PyObject* weakref;
int rc;
if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
return NULL;
}
if (!_PyArg_NoKeywords("sqlite3.Connection()", kwargs))
return NULL;
if (!PyArg_ParseTuple(args, "O", &sql))
return NULL;
_pysqlite_drop_unused_statement_references(self);
statement = PyObject_New(pysqlite_Statement, &pysqlite_StatementType);
if (!statement) {
return NULL;
}
statement->db = NULL;
statement->st = NULL;
statement->sql = NULL;
statement->in_use = 0;
statement->in_weakreflist = NULL;
rc = pysqlite_statement_create(statement, self, sql);
if (rc != SQLITE_OK) {
if (rc == PYSQLITE_TOO_MUCH_SQL) {
PyErr_SetString(pysqlite_Warning, "You can only execute one statement at a time.");
} else if (rc == PYSQLITE_SQL_WRONG_TYPE) {
if (PyErr_ExceptionMatches(PyExc_TypeError))
PyErr_SetString(pysqlite_Warning, "SQL is of wrong type. Must be string.");
} else {
(void)pysqlite_statement_reset(statement);
_pysqlite_seterror(self->db, NULL);
}
goto error;
}
weakref = PyWeakref_NewRef((PyObject*)statement, NULL);
if (weakref == NULL)
goto error;
if (PyList_Append(self->statements, weakref) != 0) {
Py_DECREF(weakref);
goto error;
}
Py_DECREF(weakref);
return (PyObject*)statement;
error:
Py_DECREF(statement);
return NULL;
}
PyObject* pysqlite_connection_execute(pysqlite_Connection* self, PyObject* args)
{
PyObject* cursor = 0;
PyObject* result = 0;
PyObject* method = 0;
cursor = _PyObject_CallMethodId((PyObject*)self, &PyId_cursor, NULL);
if (!cursor) {
goto error;
}
method = PyObject_GetAttrString(cursor, "execute");
if (!method) {
Py_CLEAR(cursor);
goto error;
}
result = PyObject_CallObject(method, args);
if (!result) {
Py_CLEAR(cursor);
}
error:
Py_XDECREF(result);
Py_XDECREF(method);
return cursor;
}
PyObject* pysqlite_connection_executemany(pysqlite_Connection* self, PyObject* args)
{
PyObject* cursor = 0;
PyObject* result = 0;
PyObject* method = 0;
cursor = _PyObject_CallMethodId((PyObject*)self, &PyId_cursor, NULL);
if (!cursor) {
goto error;
}
method = PyObject_GetAttrString(cursor, "executemany");
if (!method) {
Py_CLEAR(cursor);
goto error;
}
result = PyObject_CallObject(method, args);
if (!result) {
Py_CLEAR(cursor);
}
error:
Py_XDECREF(result);
Py_XDECREF(method);
return cursor;
}
PyObject* pysqlite_connection_executescript(pysqlite_Connection* self, PyObject* args)
{
PyObject* cursor = 0;
PyObject* result = 0;
PyObject* method = 0;
cursor = _PyObject_CallMethodId((PyObject*)self, &PyId_cursor, NULL);
if (!cursor) {
goto error;
}
method = PyObject_GetAttrString(cursor, "executescript");
if (!method) {
Py_CLEAR(cursor);
goto error;
}
result = PyObject_CallObject(method, args);
if (!result) {
Py_CLEAR(cursor);
}
error:
Py_XDECREF(result);
Py_XDECREF(method);
return cursor;
}
/* ------------------------- COLLATION CODE ------------------------ */
static int
pysqlite_collation_callback(
void* context,
int text1_length, const void* text1_data,
int text2_length, const void* text2_data)
{
PyObject* callback = (PyObject*)context;
PyObject* string1 = 0;
PyObject* string2 = 0;
#ifdef WITH_THREAD
PyGILState_STATE gilstate;
#endif
PyObject* retval = NULL;
long longval;
int result = 0;
#ifdef WITH_THREAD
gilstate = PyGILState_Ensure();
#endif
if (PyErr_Occurred()) {
goto finally;
}
string1 = PyUnicode_FromStringAndSize((const char*)text1_data, text1_length);
string2 = PyUnicode_FromStringAndSize((const char*)text2_data, text2_length);
if (!string1 || !string2) {
goto finally; /* failed to allocate strings */
}
retval = PyObject_CallFunctionObjArgs(callback, string1, string2, NULL);
if (!retval) {
/* execution failed */
goto finally;
}
longval = PyLong_AsLongAndOverflow(retval, &result);
if (longval == -1 && PyErr_Occurred()) {
PyErr_Clear();
result = 0;
}
else if (!result) {
if (longval > 0)
result = 1;
else if (longval < 0)
result = -1;
}
finally:
Py_XDECREF(string1);
Py_XDECREF(string2);
Py_XDECREF(retval);
#ifdef WITH_THREAD
PyGILState_Release(gilstate);
#endif
return result;
}
static PyObject *
pysqlite_connection_interrupt(pysqlite_Connection* self, PyObject* args)
{
PyObject* retval = NULL;
if (!pysqlite_check_connection(self)) {
goto finally;
}
sqlite3_interrupt(self->db);
Py_INCREF(Py_None);
retval = Py_None;
finally:
return retval;
}
/* Function author: Paul Kippes <[email protected]>
* Class method of Connection to call the Python function _iterdump
* of the sqlite3 module.
*/
static PyObject *
pysqlite_connection_iterdump(pysqlite_Connection* self, PyObject* args)
{
PyObject* retval = NULL;
PyObject* module = NULL;
PyObject* module_dict;
PyObject* pyfn_iterdump;
if (!pysqlite_check_connection(self)) {
goto finally;
}
module = PyImport_ImportModule("sqlite3.dump");
if (!module) {
goto finally;
}
module_dict = PyModule_GetDict(module);
if (!module_dict) {
goto finally;
}
pyfn_iterdump = PyDict_GetItemString(module_dict, "_iterdump");
if (!pyfn_iterdump) {
PyErr_SetString(pysqlite_OperationalError, "Failed to obtain _iterdump() reference");
goto finally;
}
args = PyTuple_New(1);
if (!args) {
goto finally;
}
Py_INCREF(self);
PyTuple_SetItem(args, 0, (PyObject*)self);
retval = PyObject_CallObject(pyfn_iterdump, args);
finally:
Py_XDECREF(args);
Py_XDECREF(module);
return retval;
}
static PyObject *
pysqlite_connection_create_collation(pysqlite_Connection* self, PyObject* args)
{
PyObject* callable;
PyObject* uppercase_name = 0;
PyObject* name;
PyObject* retval;
Py_ssize_t i, len;
_Py_IDENTIFIER(upper);
char *uppercase_name_str;
int rc;
unsigned int kind;
void *data;
if (!pysqlite_check_thread(self) || !pysqlite_check_connection(self)) {
goto finally;
}
if (!PyArg_ParseTuple(args, "UO:create_collation(name, callback)",
&name, &callable)) {
goto finally;
}
uppercase_name = _PyObject_CallMethodIdObjArgs((PyObject *)&PyUnicode_Type,
&PyId_upper, name, NULL);
if (!uppercase_name) {
goto finally;
}
if (PyUnicode_READY(uppercase_name))
goto finally;
len = PyUnicode_GET_LENGTH(uppercase_name);
kind = PyUnicode_KIND(uppercase_name);
data = PyUnicode_DATA(uppercase_name);
for (i=0; i<len; i++) {
Py_UCS4 ch = PyUnicode_READ(kind, data, i);
if ((ch >= '0' && ch <= '9')
|| (ch >= 'A' && ch <= 'Z')
|| (ch == '_'))
{
continue;
} else {
PyErr_SetString(pysqlite_ProgrammingError, "invalid character in collation name");
goto finally;
}
}
uppercase_name_str = PyUnicode_AsUTF8(uppercase_name);
if (!uppercase_name_str)
goto finally;
if (callable != Py_None && !PyCallable_Check(callable)) {
PyErr_SetString(PyExc_TypeError, "parameter must be callable");
goto finally;
}
if (callable != Py_None) {
if (PyDict_SetItem(self->collations, uppercase_name, callable) == -1)
goto finally;
} else {
if (PyDict_DelItem(self->collations, uppercase_name) == -1)
goto finally;
}
rc = sqlite3_create_collation(self->db,
uppercase_name_str,
SQLITE_UTF8,
(callable != Py_None) ? callable : NULL,
(callable != Py_None) ? pysqlite_collation_callback : NULL);
if (rc != SQLITE_OK) {
PyDict_DelItem(self->collations, uppercase_name);
_pysqlite_seterror(self->db, NULL);
goto finally;
}
finally:
Py_XDECREF(uppercase_name);
if (PyErr_Occurred()) {
retval = NULL;
} else {
Py_INCREF(Py_None);
retval = Py_None;
}
return retval;
}
/* Called when the connection is used as a context manager. Returns itself as a
* convenience to the caller. */
static PyObject *
pysqlite_connection_enter(pysqlite_Connection* self, PyObject* args)
{
Py_INCREF(self);
return (PyObject*)self;
}
/** Called when the connection is used as a context manager. If there was any
* exception, a rollback takes place; otherwise we commit. */
static PyObject *
pysqlite_connection_exit(pysqlite_Connection* self, PyObject* args)
{
PyObject* exc_type, *exc_value, *exc_tb;
char* method_name;
PyObject* result;
if (!PyArg_ParseTuple(args, "OOO", &exc_type, &exc_value, &exc_tb)) {
return NULL;
}
if (exc_type == Py_None && exc_value == Py_None && exc_tb == Py_None) {
method_name = "commit";
} else {
method_name = "rollback";
}
result = PyObject_CallMethod((PyObject*)self, method_name, NULL);
if (!result) {
return NULL;
}
Py_DECREF(result);
Py_RETURN_FALSE;
}
static const char connection_doc[] =
PyDoc_STR("SQLite database connection object.");
static PyGetSetDef connection_getset[] = {
{"isolation_level", (getter)pysqlite_connection_get_isolation_level, (setter)pysqlite_connection_set_isolation_level},
{"total_changes", (getter)pysqlite_connection_get_total_changes, (setter)0},
{"in_transaction", (getter)pysqlite_connection_get_in_transaction, (setter)0},
{NULL}
};
static PyMethodDef connection_methods[] = {
{"cursor", (PyCFunction)pysqlite_connection_cursor, METH_VARARGS|METH_KEYWORDS,
PyDoc_STR("Return a cursor for the connection.")},
{"close", (PyCFunction)pysqlite_connection_close, METH_NOARGS,
PyDoc_STR("Closes the connection.")},
{"commit", (PyCFunction)pysqlite_connection_commit, METH_NOARGS,
PyDoc_STR("Commit the current transaction.")},
{"rollback", (PyCFunction)pysqlite_connection_rollback, METH_NOARGS,
PyDoc_STR("Roll back the current transaction.")},
{"create_function", (PyCFunction)pysqlite_connection_create_function, METH_VARARGS|METH_KEYWORDS,
PyDoc_STR("Creates a new function. Non-standard.")},
{"create_aggregate", (PyCFunction)pysqlite_connection_create_aggregate, METH_VARARGS|METH_KEYWORDS,
PyDoc_STR("Creates a new aggregate. Non-standard.")},
{"set_authorizer", (PyCFunction)pysqlite_connection_set_authorizer, METH_VARARGS|METH_KEYWORDS,
PyDoc_STR("Sets authorizer callback. Non-standard.")},
#ifdef HAVE_LOAD_EXTENSION
{"enable_load_extension", (PyCFunction)pysqlite_enable_load_extension, METH_VARARGS,
PyDoc_STR("Enable dynamic loading of SQLite extension modules. Non-standard.")},
{"load_extension", (PyCFunction)pysqlite_load_extension, METH_VARARGS,
PyDoc_STR("Load SQLite extension module. Non-standard.")},
#endif
{"set_progress_handler", (PyCFunction)pysqlite_connection_set_progress_handler, METH_VARARGS|METH_KEYWORDS,
PyDoc_STR("Sets progress handler callback. Non-standard.")},
{"set_trace_callback", (PyCFunction)pysqlite_connection_set_trace_callback, METH_VARARGS|METH_KEYWORDS,
PyDoc_STR("Sets a trace callback called for each SQL statement (passed as unicode). Non-standard.")},
{"execute", (PyCFunction)pysqlite_connection_execute, METH_VARARGS,
PyDoc_STR("Executes a SQL statement. Non-standard.")},
{"executemany", (PyCFunction)pysqlite_connection_executemany, METH_VARARGS,
PyDoc_STR("Repeatedly executes a SQL statement. Non-standard.")},
{"executescript", (PyCFunction)pysqlite_connection_executescript, METH_VARARGS,
PyDoc_STR("Executes a multiple SQL statements at once. Non-standard.")},
{"create_collation", (PyCFunction)pysqlite_connection_create_collation, METH_VARARGS,
PyDoc_STR("Creates a collation function. Non-standard.")},
{"interrupt", (PyCFunction)pysqlite_connection_interrupt, METH_NOARGS,
PyDoc_STR("Abort any pending database operation. Non-standard.")},
{"iterdump", (PyCFunction)pysqlite_connection_iterdump, METH_NOARGS,
PyDoc_STR("Returns iterator to the dump of the database in an SQL text format. Non-standard.")},
{"__enter__", (PyCFunction)pysqlite_connection_enter, METH_NOARGS,
PyDoc_STR("For context manager. Non-standard.")},
{"__exit__", (PyCFunction)pysqlite_connection_exit, METH_VARARGS,
PyDoc_STR("For context manager. Non-standard.")},
{NULL, NULL}
};
static struct PyMemberDef connection_members[] =
{
{"Warning", T_OBJECT, offsetof(pysqlite_Connection, Warning), READONLY},
{"Error", T_OBJECT, offsetof(pysqlite_Connection, Error), READONLY},
{"InterfaceError", T_OBJECT, offsetof(pysqlite_Connection, InterfaceError), READONLY},
{"DatabaseError", T_OBJECT, offsetof(pysqlite_Connection, DatabaseError), READONLY},
{"DataError", T_OBJECT, offsetof(pysqlite_Connection, DataError), READONLY},
{"OperationalError", T_OBJECT, offsetof(pysqlite_Connection, OperationalError), READONLY},
{"IntegrityError", T_OBJECT, offsetof(pysqlite_Connection, IntegrityError), READONLY},
{"InternalError", T_OBJECT, offsetof(pysqlite_Connection, InternalError), READONLY},
{"ProgrammingError", T_OBJECT, offsetof(pysqlite_Connection, ProgrammingError), READONLY},
{"NotSupportedError", T_OBJECT, offsetof(pysqlite_Connection, NotSupportedError), READONLY},
{"row_factory", T_OBJECT, offsetof(pysqlite_Connection, row_factory)},
{"text_factory", T_OBJECT, offsetof(pysqlite_Connection, text_factory)},
{NULL}
};
PyTypeObject pysqlite_ConnectionType = {
PyVarObject_HEAD_INIT(NULL, 0)
"sqlite3.Connection", /* tp_name */
sizeof(pysqlite_Connection), /* tp_basicsize */
0, /* tp_itemsize */
(destructor)pysqlite_connection_dealloc, /* tp_dealloc */
0, /* tp_print */
0, /* tp_getattr */
0, /* tp_setattr */
0, /* tp_reserved */
0, /* tp_repr */
0, /* tp_as_number */
0, /* tp_as_sequence */
0, /* tp_as_mapping */
0, /* tp_hash */
(ternaryfunc)pysqlite_connection_call, /* tp_call */
0, /* tp_str */
0, /* tp_getattro */
0, /* tp_setattro */
0, /* tp_as_buffer */
Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE, /* tp_flags */
connection_doc, /* tp_doc */
0, /* tp_traverse */
0, /* tp_clear */
0, /* tp_richcompare */
0, /* tp_weaklistoffset */
0, /* tp_iter */
0, /* tp_iternext */
connection_methods, /* tp_methods */
connection_members, /* tp_members */
connection_getset, /* tp_getset */
0, /* tp_base */
0, /* tp_dict */
0, /* tp_descr_get */
0, /* tp_descr_set */
0, /* tp_dictoffset */
(initproc)pysqlite_connection_init, /* tp_init */
0, /* tp_alloc */
0, /* tp_new */
0 /* tp_free */
};
extern int pysqlite_connection_setup_types(void)
{
pysqlite_ConnectionType.tp_new = PyType_GenericNew;
return PyType_Ready(&pysqlite_ConnectionType);
}
| 52,770 | 1,727 | jart/cosmopolitan | false |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.