OLD | NEW |
(Empty) | |
| 1 // Copyright (c) 2013, 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 import "package:expect/expect.dart"; |
| 6 import 'dart:convert'; |
| 7 |
| 8 final TESTS = [ |
| 9 [ 5, '5' ], |
| 10 [ -42, '-42' ], |
| 11 [ 3.14, '3.14' ], |
| 12 [ true, 'true' ], |
| 13 [ false, 'false' ], |
| 14 [ null, 'null' ], |
| 15 [ 'quote"or\'', '"quote\\"or\'"' ], |
| 16 [ '', '""' ], |
| 17 [ [], "[]" ], |
| 18 [ [3, -4.5, true, "hi", false], '[3,-4.5,true,"hi",false]' ], |
| 19 [ [null], "[null]" ], |
| 20 [ [[null]], "[[null]]" ], |
| 21 [ [[3]], "[[3]]" ], |
| 22 [ {}, "{}" ], |
| 23 [ { "x": 3, "y": 4.5, "z": "hi", "u": true, "v": false }, |
| 24 '{"x":3,"y":4.5,"z":"hi","u":true,"v":false}' ], |
| 25 [ { "x": null }, '{"x":null}' ], |
| 26 [ { "x": {} }, '{"x":{}}' ], |
| 27 // Note that -0.0 won't be treated the same in JS. The Json spec seems to |
| 28 // allow it, though. |
| 29 // TODO(rnystrom): Changed to "0". See above comment. |
| 30 [ { "hi there": 499, "'":-0.0 }, '{"hi there":499,"\'":0}' ], |
| 31 [ r'\foo', r'"\\foo"' ], |
| 32 ]; |
| 33 |
| 34 class MyStringConversionSink extends StringConversionSinkBase { |
| 35 var buffer = new StringBuffer(); |
| 36 var callback; |
| 37 |
| 38 MyStringConversionSink(this.callback); |
| 39 |
| 40 addSlice(str, start, end, bool isLast) { |
| 41 buffer.write(str.substring(start, end)); |
| 42 if (isLast) close(); |
| 43 } |
| 44 |
| 45 close() { |
| 46 callback(buffer.toString()); |
| 47 } |
| 48 } |
| 49 |
| 50 String encode(Object o) { |
| 51 var result; |
| 52 var encoder = new JsonEncoder(); |
| 53 ChunkedConversionSink stringSink = |
| 54 new MyStringConversionSink((x) => result = x); |
| 55 var objectSink = new JsonEncoder().startChunkedConversion(stringSink); |
| 56 objectSink.add(o); |
| 57 objectSink.close(); |
| 58 return result; |
| 59 } |
| 60 |
| 61 String encode2(Object o) { |
| 62 var result; |
| 63 var encoder = new JsonEncoder(); |
| 64 ChunkedConversionSink stringSink = |
| 65 new StringConversionSink.withCallback((x) => result = x); |
| 66 var objectSink = encoder.startChunkedConversion(stringSink); |
| 67 objectSink.add(o); |
| 68 objectSink.close(); |
| 69 return result; |
| 70 } |
| 71 |
| 72 main() { |
| 73 for (var test in TESTS) { |
| 74 var o = test[0]; |
| 75 var expected = test[1]; |
| 76 Expect.equals(expected, encode(o)); |
| 77 Expect.equals(expected, encode2(o)); |
| 78 } |
| 79 } |
OLD | NEW |