473,386 Members | 1,712 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,386 software developers and data experts.

String buffer

Yet another useful code snippet!

This StringBuffer class is a FIFO for character data.

Example:
B = StringBuffer('Hello W')
B.append('orld!')
print B.read(5) # 'Hello'
print B.read() # 'World!'

The append method appends a string to the end of the string buffer.
The read(n) method reads and removes n characters from the beginning
of the buffer. If n is omitted, it reads the entire buffer. To view
the first n characters of the string buffer, use peek:

print B.peek(5) # View first 5 characters

Or cast as a string to get the entire contents:

print str(B) # View entire buffer

The append and read methods are O(k), where k is the number of
characters appended or read.

# -------------------------------------------------------
# StringBuffer: A FIFO for string data.
# -------------------------------------------------------

class Deque:
"""A double-ended queue."""
def __init__(self):
self.a = []
self.b = []
def push_last(self, obj):
self.b.append(obj)
def push_first(self, obj):
self.a.append(obj)
def partition(self):
if len(self) > 1:
self.a.reverse()
all = self.a + self.b
n = len(all) / 2
self.a = all[:n]
self.b = all[n:]
self.a.reverse()
def pop_last(self):
if not self.b: self.partition()
try: return self.b.pop()
except: return self.a.pop()
def pop_first(self):
if not self.a: self.partition()
try: return self.a.pop()
except: return self.b.pop()
def __len__(self):
return len(self.b) + len(self.a)

class StringBuffer(Deque):
"""A FIFO for characters. Strings can be efficiently
appended to the end, and read from the beginning.

Example:
B = StringBuffer('Hello W')
B.append('orld!')
print B.read(5) # 'Hello'
print B.read() # 'World!'
"""
def __init__(self, s=''):
Deque.__init__(self)
self.length = 0
self.append(s)
def append(self, s):
n = 128
for block in [s[i:i+n] for i in range(0,len(s),n)]:
self.push_last(block)
self.length += len(s)
def prepend(self, s):
n = 128
blocks = [s[i:i+n] for i in range(0,len(s),n)]
blocks.reverse()
for block in blocks:
self.push_first(block)
self.length += len(s)
def read(self, n=None):
if n == None or n > len(self): n = len(self)
destlen = len(self) - n
ans = []
while len(self) > destlen:
ans += [self.pop_first()]
self.length -= len(ans[-1])
ans = ''.join(ans)
self.prepend(ans[n:])
ans = ans[:n]
return ans
def peek(self, n=None):
ans = self.read(n)
self.prepend(ans)
return ans
def __len__(self): return self.length
def __str__(self): return self.peek()
def __repr__(self): return 'StringBuffer(' + str(self) + ')'
- Connelly Barnes
Jul 18 '05 #1
0 2594

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

17
by: Axel | last post by:
Hiho, here my Newbie question (Win32 GUI): I'm reading a file in binary mode to a char* named buffer. I used malloc(filesize) to make the needed space avaiable. The filedata in the buffer...
51
by: Alan | last post by:
hi all, I want to define a constant length string, say 4 then in a function at some time, I want to set the string to a constant value, say a below is my code but it fails what is the correct...
9
by: rsine | last post by:
I have developed a program that sends a command through the serial port to our business system and then reads from the buffer looking for a number. Everything worked great on my WinXP system, but...
1
by: mdefoor | last post by:
I've written the following sample to split a string into chunks. Is this the right approach or is there perhaps a better way to accomplish getting chunks of a string? #include <stdio.h>...
6
by: Erik | last post by:
Hello, For many years ago I implemented my own string buffer class, which works fine except assignments - it copies the char* buffer instead of the pointer. Therefore in function calls I pass...
9
by: Michael D. Ober | last post by:
OK, I can't figure out a way to optimize the following VB 2005 code using StringBuilders: Public Const RecSize as Integer = 105 Private buffer As String Public Sub New() init End Sub...
3
by: Jim Langston | last post by:
Is it possible to initialize a std::string with a character array, not neccessarily null terminated? I.E. Given something like this: char buffer; buffer = 0x01; buffer = 0x00; buffer = 'A';...
3
by: Benny the Guard | last post by:
I have a comma delimited file to parse up. So I figured I will go line by line and parse them up. Now efficiency is the top priority here. So I figure I can use the old-school C approach or use...
14
by: Aman JIANG | last post by:
hi i need a fast way to do lots of conversion that between string and numerical value(integer, float, double...), and boost::lexical_cast is useless, because it runs for a long time, (about 60...
17
by: let_the_best_man_win | last post by:
How do I print a pointer address into a string buffer and then read it back on a 64 bit machine ? Compulsion is to use string (char * buffer) only. printing with %d does not capture the full...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.