| OLD | NEW |
| (Empty) |
| 1 # Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file | |
| 2 # for details. All rights reserved. Use of this source code is governed by a | |
| 3 # BSD-style license that can be found in the LICENSE file. | |
| 4 | |
| 5 ''' | |
| 6 This Encoder shares a lot in common with protobufs. It uses variable length | |
| 7 ints and size-encoded strings and binary values. Other than being hugely | |
| 8 stripped down, the major conceptual difference is that this encoding | |
| 9 is UTF8 "safe". This means that it generates a form that should be passed | |
| 10 on the wire as UTF8 and then can be very efficiently decoded by JS in the | |
| 11 browser which natively handles these kinds of strings. To stay efficient in | |
| 12 this range, all numeric data is encoded in only 7 bits. | |
| 13 ''' | |
| 14 | |
| 15 import base64 | |
| 16 | |
| 17 class Encoder: | |
| 18 def __init__(self): | |
| 19 self.data = [] | |
| 20 | |
| 21 def writeInt(self, value): | |
| 22 '''Uses a 7-bit per byte encoding to stay UTF-8 "safe".''' | |
| 23 bits = value & 0x3f | |
| 24 value >>= 6 | |
| 25 while value: | |
| 26 self.data.append(chr(0x40|bits)) | |
| 27 bits = value & 0x3f | |
| 28 value >>= 6 | |
| 29 self.data.append(chr(bits)) | |
| 30 | |
| 31 def writeBool(self, b): | |
| 32 self.data.append(('F', 'T')[b]) | |
| 33 | |
| 34 def writeString(self, s): | |
| 35 if not s: s = '' | |
| 36 self.writeInt(len(s)) | |
| 37 self.data.append(s) | |
| 38 | |
| 39 def writeBinary(self, s): | |
| 40 '''Encode binary data using base64. This is less efficient than a 7-bit | |
| 41 encoding would be; however, it can be decoded much faster on most | |
| 42 browsers due to native support for the format.''' | |
| 43 v = base64.b64encode(s) | |
| 44 self.writeInt(len(v)) | |
| 45 self.data.append(v) | |
| 46 | |
| 47 def writeList(self, l): | |
| 48 self.writeInt(len(l)) | |
| 49 for i in l: | |
| 50 i.encode(self) | |
| 51 | |
| 52 def writeRaw(self, s): | |
| 53 self.data.append(s) | |
| 54 | |
| 55 def finish(self): | |
| 56 d = ''.join(self.data) | |
| 57 return _encVarInt(len(d)) + d | |
| 58 | |
| 59 def getRaw(self): | |
| 60 return ''.join(self.data) | |
| OLD | NEW |