Debian Codegraph @

Modules/_testcapi/file.c

raw
1 // clinic/file.c.h uses internal pycore_modsupport.h API
2 #define PYTESTCAPI_NEED_INTERNAL_API
3
4 #include "parts.h"
5 #include "util.h"
6 #include "clinic/file.c.h"
7
8
9 /*[clinic input]
10 module _testcapi
11 [clinic start generated code]*/
12 /*[clinic end generated code: output=da39a3ee5e6b4b0d input=6361033e795369fc]*/
13
14
15 /*[clinic input]
16 _testcapi.pyfile_newstdprinter
17
18 fd: int
19 /
20
21 [clinic start generated code]*/
22
23 static PyObject *
24 _testcapi_pyfile_newstdprinter_impl(PyObject *module, int fd)
25 /*[clinic end generated code: output=8a2d1c57b6892db3 input=442f1824142262ea]*/
26 {
27 return PyFile_NewStdPrinter(fd);
28 }
29
30
31 /*[clinic input]
32 _testcapi.py_fopen
33
34 path: object
35 mode: str(zeroes=True, accept={robuffer, str, NoneType})
36 /
37
38 Call Py_fopen(), fread(256) and Py_fclose(). Return read bytes.
39 [clinic start generated code]*/
40
41 static PyObject *
42 _testcapi_py_fopen_impl(PyObject *module, PyObject *path, const char *mode,
43 Py_ssize_t mode_length)
44 /*[clinic end generated code: output=69840d0cfd8b7fbb input=f3a579dd7eb60926]*/
45 {
46 NULLABLE(path);
47 FILE *fp = Py_fopen(path, mode);
48 if (fp == NULL) {
49 return NULL;
50 }
51
52 char buffer[256];
53 size_t size = fread(buffer, 1, Py_ARRAY_LENGTH(buffer), fp);
54 Py_fclose(fp);
55
56 return PyBytes_FromStringAndSize(buffer, size);
57 }
58
59
60 /*[clinic input]
61 _testcapi.py_universalnewlinefgets
62
63 file: object
64 size: int
65 /
66
67 Read a line from a file using Py_UniversalNewlineFgets.
68 [clinic start generated code]*/
69
70 static PyObject *
71 _testcapi_py_universalnewlinefgets_impl(PyObject *module, PyObject *file,
72 int size)
73 /*[clinic end generated code: output=2ce1bc76c9dc871c input=02c236049d18569a]*/
74 {
75 FILE *fp = Py_fopen(file, "rb");
76 if (fp == NULL) {
77 return NULL;
78 }
79
80 char *buf = (char *)PyMem_Malloc(size);
81 if (buf == NULL) {
82 Py_fclose(fp);
83 return PyErr_NoMemory();
84 }
85
86 char *result = Py_UniversalNewlineFgets(buf, size, fp, NULL);
87 if (result == NULL) {
88 PyMem_Free(buf);
89 Py_fclose(fp);
90 Py_RETURN_NONE;
91 }
92
93 PyObject *line = PyBytes_FromString(result);
94 PyMem_Free(buf);
95 Py_fclose(fp);
96
97 return line;
98 }
99
100 static PyMethodDef test_methods[] = {
101 _TESTCAPI_PYFILE_NEWSTDPRINTER_METHODDEF
102 _TESTCAPI_PY_FOPEN_METHODDEF
103 _TESTCAPI_PY_UNIVERSALNEWLINEFGETS_METHODDEF
104 {NULL},
105 };
106
107 int
108 _PyTestCapi_Init_File(PyObject *m)
109 {
110 return PyModule_AddFunctions(m, test_methods);
111 }