[pypy-svn] r42977 - in pypy/branch/pypy-string-formatting/rlib: . test

fijal at codespeak.net fijal at codespeak.net
Wed May 9 22:51:58 CEST 2007


Author: fijal
Date: Wed May  9 22:51:57 2007
New Revision: 42977

Added:
   pypy/branch/pypy-string-formatting/rlib/rcharbuilder.py
   pypy/branch/pypy-string-formatting/rlib/test/test_rcharbuilder.py
Log:
A char builder, which allows for keeping list of chars or
repeated chars


Added: pypy/branch/pypy-string-formatting/rlib/rcharbuilder.py
==============================================================================
--- (empty file)
+++ pypy/branch/pypy-string-formatting/rlib/rcharbuilder.py	Wed May  9 22:51:57 2007
@@ -0,0 +1,55 @@
+
+""" RPython-level implementation of string builder,
+which can keep joined list of strings with additional
+optimizations (like 'x' * 123 or 'xxx' * 444)
+"""
+
+class AbstractElement:
+    pass
+
+class SingleChar(AbstractElement):
+    def __init__(self, c):
+        self.c = c
+
+    def flatten(self):
+        return self.c
+
+    def chars(self):
+        return [self.c]
+
+class MultipleChar(AbstractElement):
+    def __init__(self, c, count):
+        self.c = c
+        self.count = count
+
+    def flatten(self):
+        return self.c * self.count
+
+    def chars(self):
+        return [self.c] * self.count
+
+class rcharbuilder:
+    """ An implementation of special char-like builder, which
+    keeps list of substrings with additional informations.
+
+    Need to be char-like to keep eventual unicode characters :-(
+    """
+    def __init__(self):
+        self.l = []
+
+    def append_char(self, c):
+        self.l.append(SingleChar(c))
+
+    def append_multiple_char(self, c, count):
+        self.l.append(MultipleChar(c, count))
+
+    def flatten(self):
+        return "".join([i.flatten() for i in self.l])
+
+    def chars(self):
+        # XXX unicode literals in RPython anyone?
+        l = []
+        for i in self.l:
+            l += i.chars()
+        return l
+

Added: pypy/branch/pypy-string-formatting/rlib/test/test_rcharbuilder.py
==============================================================================
--- (empty file)
+++ pypy/branch/pypy-string-formatting/rlib/test/test_rcharbuilder.py	Wed May  9 22:51:57 2007
@@ -0,0 +1,18 @@
+
+from pypy.rlib.rcharbuilder import rcharbuilder
+
+class TestRStringBuilder:
+    def test_simple(self):
+        sb = rcharbuilder()
+        sb.append_char('x')
+        sb.append_char('y')
+        assert sb.flatten() == 'xy'
+        assert sb.chars() == ['x', 'y']
+
+    def test_multiple(self):
+        sb = rcharbuilder()
+        sb.append_char('x')
+        sb.append_multiple_char('z', 3)
+        sb.append_multiple_char('x', 4)
+        assert sb.flatten() == 'xzzzxxxx'
+        assert sb.chars() == ['x', 'z', 'z', 'z', 'x', 'x', 'x', 'x']



More information about the Pypy-commit mailing list