Skip to content

Commit 2eb41f2

Browse files
committed
Implemented SourceFile.write()
1 parent eda6dc5 commit 2eb41f2

File tree

2 files changed

+25
-6
lines changed

2 files changed

+25
-6
lines changed

src/core/modules/filesystem/filesystem.cpp

Lines changed: 24 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -83,7 +83,7 @@ void SourceFile::Save(const char* file_path)
8383
BOOST_RAISE_EXCEPTION(PyExc_IOError, "Failed to open file: %s", file_path)
8484

8585
int size = Size();
86-
void* buffer = new char[size];
86+
void* buffer = new char[size+1];
8787
int bytesRead = filesystem->Read(buffer, size, m_handle);
8888

8989
filesystem->Write(buffer, bytesRead, handle);
@@ -134,12 +134,31 @@ PyObject* SourceFile::ConsumeBuffer(void* buffer, int bytesRead)
134134
return result;
135135
}
136136

137-
int SourceFile::Write(object data)
137+
int SourceFile::Write(PyObject* data)
138138
{
139139
CheckClosed();
140-
// TODO
141-
BOOST_RAISE_EXCEPTION(PyExc_NotImplementedError, "Not implemented yet.")
142-
return 0;
140+
141+
char* input = NULL;
142+
int size = 0;
143+
144+
if (IsBinaryMode()) {
145+
if (!PyBytes_Check(data)) {
146+
BOOST_RAISE_EXCEPTION(PyExc_TypeError, "a bytes-like object is required, not '%s'", data->ob_type->tp_name)
147+
}
148+
149+
input = PyBytes_AsString(data);
150+
size = PyBytes_Size(data);
151+
}
152+
else {
153+
if (!PyUnicode_Check(data)) {
154+
BOOST_RAISE_EXCEPTION(PyExc_TypeError, "write() argument must be str, not %s", data->ob_type->tp_name)
155+
}
156+
157+
size = PyUnicode_GetLength(data);
158+
input = (char *) PyUnicode_DATA(data);
159+
}
160+
161+
return filesystem->Write((void *) input, size, m_handle);
143162
}
144163

145164
void SourceFile::Writelines(list lines)

src/core/modules/filesystem/filesystem.h

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,7 @@ class SourceFile
4545

4646
// File-like methods
4747
PyObject* Read(int size=-1);
48-
int Write(object data);
48+
int Write(PyObject* data);
4949
void Close();
5050
void Seek(int pos, int seekType=FILESYSTEM_SEEK_HEAD);
5151
unsigned int Tell();

0 commit comments

Comments
 (0)