Commit 376e2b98 authored by Joris Vankerschaver's avatar Joris Vankerschaver

Add iterator support for file objects

parent bcc2509a
......@@ -12,6 +12,7 @@
// See the License for the specific language governing permissions and
// limitations under the License.
#include <cstdio>
#include <cstring>
#include <sstream>
......@@ -161,6 +162,22 @@ Box* fileNew(BoxedClass* cls, Box* s, Box* m) {
return open(s, m);
}
Box* fileIterNext(BoxedFile* s) {
return fileReadline1(s);
}
bool fileEof(BoxedFile* self) {
char ch = fgetc(self->f);
ungetc(ch, self->f);
return feof(self->f);
}
Box* fileIterHasNext(Box* s) {
assert(s->cls == file_cls);
BoxedFile* self = static_cast<BoxedFile*>(s);
return boxBool(!fileEof(self));
}
void setupFile() {
file_cls->giveAttr("__name__", boxStrConstant("file"));
......@@ -179,6 +196,10 @@ void setupFile() {
file_cls->giveAttr("__enter__", new BoxedFunction(boxRTFunction((void*)fileEnter, typeFromClass(file_cls), 1)));
file_cls->giveAttr("__exit__", new BoxedFunction(boxRTFunction((void*)fileExit, UNKNOWN, 4)));
file_cls->giveAttr("__iter__", file_cls->getattr("__enter__"));
file_cls->giveAttr("__hasnext__", new BoxedFunction(boxRTFunction((void*)fileIterHasNext, BOXED_BOOL, 1)));
file_cls->giveAttr("next", new BoxedFunction(boxRTFunction((void*)fileIterNext, STR, 1)));
file_cls->giveAttr("softspace",
new BoxedMemberDescriptor(BoxedMemberDescriptor::BYTE, offsetof(BoxedFile, softspace)));
......
......@@ -28,3 +28,14 @@ f = open("/dev/null", 'r')
print chop(str(f))
f.close()
print chop(str(f))
# Support for iteration protocol.
f = open('/dev/null')
print iter(f) is f
f.close()
with open('../README.md') as f:
lines = list(f)
print lines[:5]
print lines[-5:]
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment