refactor formatting, add %% format
@@ -4,7 +4,9 @@ from rpython.rlib.unroll import unrolling_iterable
FORMAT_CHARS = unrolling_iterable([
- "s", "d", "f"
+ ((c, c) if type(c) is str else c) for c in [
+ "s", "d", "f", ("%", "percent")
+ ]
])
@@ -34,28 +36,34 @@ class StringFormatter(object):
width = width * 10 + (ord(self.fmt[i]) - ord("0"))
i += 1
format_char = self.fmt[i]
- w_item = self.items_w[self.item_index]
- self.item_index += 1
i += 1
- for c in FORMAT_CHARS:
+ for c, postfix in FORMAT_CHARS:
if c == format_char:
- w_res = getattr(self, "fmt_" + c)(space, w_item, width)
+ w_res = getattr(self, "fmt_" + postfix)(space, width)
result_w.append(w_res)
break
else:
raise NotImplementedError(format_char)
return result_w
+ def _next_item(self):
+ w_item = self.items_w[self.item_index]
+ self.item_index += 1
+ return w_item
+
def _fmt_num(self, space, num, width):
return space.newstr_fromstr((width - len(num)) * "0" + num)
- def fmt_s(self, space, w_item, width):
- return space.send(w_item, "to_s")
+ def fmt_s(self, space, width):
+ return space.send(self._next_item(), "to_s")
- def fmt_d(self, space, w_item, width):
- num = space.int_w(w_item)
+ def fmt_d(self, space, width):
+ num = space.int_w(self._next_item())
return self._fmt_num(space, str(num), width)
- def fmt_f(self, space, w_item, width):
- num = space.float_w(w_item)
+ def fmt_f(self, space, width):
+ num = space.float_w(self._next_item())
return self._fmt_num(space, formatd(num, "f", 6), width)
+
+ def fmt_percent(self, space, width):
+ return space.newstr_fromstr("%")
