1# -*- test-case-name: foolscap.test.test_banana -*- 2 3import decimal 4import six 5from twisted.internet.defer import Deferred 6from foolscap.tokens import BananaError, STRING, VOCAB 7from foolscap.slicer import BaseSlicer, LeafUnslicer 8from foolscap.constraint import Any 9 10class DecimalSlicer(BaseSlicer): 11 opentype = ("decimal",) 12 slices = decimal.Decimal 13 def sliceBody(self, streamable, banana): 14 yield six.ensure_binary(str(self.obj)) 15 16class DecimalUnslicer(LeafUnslicer): 17 opentype = ("decimal",) 18 value = None 19 constraint = None 20 21 def setConstraint(self, constraint): 22 if isinstance(constraint, Any): 23 return 24 assert False, "DecimalUnslicer does not currently accept a constraint" 25 26 def checkToken(self, typebyte, size): 27 if typebyte not in (STRING, VOCAB): 28 raise BananaError("DecimalUnslicer only accepts strings") 29 #if self.constraint: 30 # self.constraint.checkToken(typebyte, size) 31 32 def receiveChild(self, obj, ready_deferred=None): 33 assert not isinstance(obj, Deferred) 34 assert ready_deferred is None 35 if self.value != None: 36 raise BananaError("already received a string") 37 self.value = decimal.Decimal(six.ensure_str(obj)) 38 39 def receiveClose(self): 40 return self.value, None 41 def describe(self): 42 return "<unicode>" 43