Lichen

Annotated lib/__builtins__/file.py

986:9ee9c9e18fa6
14 months ago Paul Boddie Introduced a dedicated method for statement nodes.
paul@6 1
#!/usr/bin/env python
paul@6 2
paul@6 3
"""
paul@6 4
File objects.
paul@6 5
paul@529 6
Copyright (C) 2015, 2016, 2017 Paul Boddie <paul@boddie.org.uk>
paul@6 7
paul@6 8
This program is free software; you can redistribute it and/or modify it under
paul@6 9
the terms of the GNU General Public License as published by the Free Software
paul@6 10
Foundation; either version 3 of the License, or (at your option) any later
paul@6 11
version.
paul@6 12
paul@6 13
This program is distributed in the hope that it will be useful, but WITHOUT
paul@6 14
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
paul@6 15
FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
paul@6 16
details.
paul@6 17
paul@6 18
You should have received a copy of the GNU General Public License along with
paul@6 19
this program.  If not, see <http://www.gnu.org/licenses/>.
paul@6 20
"""
paul@6 21
paul@529 22
from __builtins__.stream import filestream
paul@529 23
from native import fopen, fread
paul@347 24
paul@347 25
class file(filestream):
paul@173 26
paul@173 27
    "A file abstraction."
paul@173 28
paul@392 29
    def __init__(self, filename, mode="r", encoding=None, bufsize=1024):
paul@347 30
paul@392 31
        """
paul@392 32
        Open the file with the given 'filename' using the given access 'mode',
paul@392 33
        any specified 'encoding', and the given 'bufsize'.
paul@392 34
        """
paul@347 35
paul@392 36
        get_using(filestream.__init__, self)(encoding, bufsize)
paul@356 37
        self.__data__ = fopen(filename, mode)
paul@436 38
        self.buffered = ""
paul@436 39
paul@436 40
    def _get_data(self):
paul@436 41
paul@436 42
        "Get data from the file."
paul@436 43
paul@436 44
        if self.buffered:
paul@436 45
            s = self.buffered
paul@436 46
            self.buffered = ""
paul@436 47
        else:
paul@436 48
            s = fread(self.__data__, self.bufsize)
paul@436 49
paul@436 50
        return s
paul@436 51
paul@436 52
    def _read_data(self, l):
paul@436 53
paul@436 54
        "Read data into 'l'."
paul@436 55
paul@436 56
        s = self._get_data()
paul@436 57
        l.append(s)
paul@436 58
paul@436 59
    def _read_until_newline(self, l):
paul@436 60
paul@436 61
        "Read data into 'l', returning whether a newline has been read."
paul@436 62
paul@436 63
        s = self._get_data()
paul@436 64
paul@436 65
        # NOTE: Only POSIX newlines are supported currently.
paul@436 66
paul@436 67
        i = s.find("\n")
paul@436 68
paul@436 69
        if i != -1:
paul@436 70
            l.append(s[:i+1])
paul@436 71
            self.buffered = s[i+1:]
paul@436 72
            return True
paul@436 73
paul@436 74
        l.append(s)
paul@436 75
        return False
paul@347 76
paul@6 77
# vim: tabstop=4 expandtab shiftwidth=4