1 #!/usr/bin/env python 2 3 """ 4 Buffer object. 5 6 Copyright (C) 2015, 2016 Paul Boddie <paul@boddie.org.uk> 7 8 This program is free software; you can redistribute it and/or modify it under 9 the terms of the GNU General Public License as published by the Free Software 10 Foundation; either version 3 of the License, or (at your option) any later 11 version. 12 13 This program is distributed in the hope that it will be useful, but WITHOUT 14 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS 15 FOR A PARTICULAR PURPOSE. See the GNU General Public License for more 16 details. 17 18 You should have received a copy of the GNU General Public License along with 19 this program. If not, see <http://www.gnu.org/licenses/>. 20 """ 21 22 from native import _list_init, _list_append, _list_concat, _buffer_str 23 24 class buffer(object): 25 26 "A buffer, used to build strings." 27 28 def __init__(self, args=None, size=0): 29 30 "Initialise a buffer from the given 'args' or the given 'size'." 31 32 if args is not None: 33 n = len(args) 34 elif isinstance(size, int): 35 n = size 36 else: 37 raise TypeError(size) 38 39 self.__data__ = _list_init(n) 40 41 # Append all arguments in string form to the buffer. 42 43 if args: 44 for arg in args: 45 _list_append(self, str(arg)) 46 47 def append(self, s): 48 49 "Append 's' to the buffer." 50 51 if isinstance(s, buffer): 52 _list_concat(self, s) 53 elif isinstance(s, string): 54 _list_append(self, s) 55 else: 56 raise TypeError(s) 57 58 def __str__(self): 59 60 "Return a string representation." 61 62 return _buffer_str(self) 63 64 # vim: tabstop=4 expandtab shiftwidth=4