Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(173)

Side by Side Diff: pkg/barback/lib/src/internal_asset.dart

Issue 55983005: Serialize barback assets more efficiently. (Closed) Base URL: https://dart.googlecode.com/svn/branches/bleeding_edge/dart
Patch Set: Make serializeAsset and deserializeAsset into methods. Created 7 years, 1 month ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch | Annotate | Revision Log
OLDNEW
1 // Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file 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 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. 3 // BSD-style license that can be found in the LICENSE file.
4 4
5 library barback.asset; 5 library barback.internal_asset;
6 6
7 import 'dart:async'; 7 import 'dart:async';
8 import 'dart:convert'; 8 import 'dart:convert';
9 import 'dart:io'; 9 import 'dart:io';
10 10
11 import 'asset.dart';
11 import 'asset_id.dart'; 12 import 'asset_id.dart';
12 import 'file_pool.dart'; 13 import 'file_pool.dart';
14 import 'serialize.dart';
13 import 'stream_replayer.dart'; 15 import 'stream_replayer.dart';
14 import 'utils.dart'; 16 import 'utils.dart';
15 17
16 /// A blob of content. 18 /// Serialize an asset to a form that's safe to send across isolates.
17 /// 19 Map serializeAsset(Asset asset) {
18 /// Assets may come from the file system, or as the output of a [Transformer]. 20 var id = serializeId(asset.id);
19 /// They are identified by [AssetId]. 21 if (asset is BinaryAsset) {
20 abstract class Asset { 22 var contents = asset._contents.runtimeType == List ?
21 /// The ID for this asset. 23 asset._contents : asset._contents.toList();
22 final AssetId id; 24 // TODO(nweiz): Send a typed array if that works after issue 14703 is fixed.
25 return {
26 'type': 'binary',
27 'id': id,
28 // If [_contents] is a custom subclass of List, it won't be serializable,
29 // so we have to convert it to a built-in [List] first.
Bob Nystrom 2013/11/08 19:22:14 Move this comment up.
nweiz 2013/11/08 22:03:49 Done.
30 'contents': contents
31 };
32 } else if (asset is FileAsset) {
33 return {
34 'type': 'file',
35 'id': id,
36 'path': asset._path
37 };
38 } else if (asset is StringAsset) {
39 return {
40 'type': 'string',
41 'id': id,
42 'contents': asset._contents
43 };
44 } else {
45 // [asset] is probably a [StreamAsset], but it's possible that the user has
46 // created a custom subclass, in which case we just serialize the stream
47 // anyway.
48 return {
49 'type': 'stream',
50 'id': id,
51 'stream': serializeStream(asset.read())
52 };
53 }
54 }
23 55
24 Asset(this.id); 56 /// Deserialize an asset from the form returned by [serialize].
25 57 Asset deserializeAsset(Map asset) {
26 factory Asset.fromBytes(AssetId id, List<int> bytes) => 58 var id = deserializeId(asset['id']);
27 new _BinaryAsset(id, bytes); 59 switch (asset['type']) {
28 60 case 'binary': return new BinaryAsset(id, asset['contents']);
29 factory Asset.fromFile(AssetId id, File file) => 61 case 'file': return new FileAsset(id, asset['path']);
30 new _FileAsset(id, file); 62 case 'string': return new StringAsset(id, asset['contents']);
31 63 case 'stream':
32 factory Asset.fromString(AssetId id, String content) => 64 return new StreamAsset(id, deserializeStream(asset['stream']));
33 new _StringAsset(id, content); 65 default:
34 66 throw new FormatException('Unknown asset type "${asset['type']}".');
35 factory Asset.fromPath(AssetId id, String path) => 67 }
36 new _FileAsset(id, new File(path));
37
38 /// Creates an asset from a stream.
39 ///
40 /// This immediately starts draining [stream].
41 factory Asset.fromStream(AssetId id, Stream<List<int>> stream) =>
42 new _StreamAsset(id, stream);
43
44 /// Returns the contents of the asset as a string.
45 ///
46 /// If the asset was created from a [String] the original string is always
47 /// returned and [encoding] is ignored. Otherwise, the binary data of the
48 /// asset is decoded using [encoding], which defaults to [UTF8].
49 Future<String> readAsString({Encoding encoding});
50
51 /// Streams the binary contents of the asset.
52 ///
53 /// If the asset was created from a [String], this returns its UTF-8 encoding.
54 Stream<List<int>> read();
55 } 68 }
56 69
57 /// An asset whose data is stored in a list of bytes. 70 /// An asset whose data is stored in a list of bytes.
58 class _BinaryAsset extends Asset { 71 class BinaryAsset implements Asset {
72 final AssetId id;
73
59 final List<int> _contents; 74 final List<int> _contents;
60 75
61 _BinaryAsset(AssetId id, this._contents) 76 BinaryAsset(this.id, this._contents);
62 : super(id);
63 77
64 Future<String> readAsString({Encoding encoding}) { 78 Future<String> readAsString({Encoding encoding}) {
65 if (encoding == null) encoding = UTF8; 79 if (encoding == null) encoding = UTF8;
66 80
67 return new Future.value(encoding.decode(_contents)); 81 return new Future.value(encoding.decode(_contents));
68 } 82 }
69 83
70 Stream<List<int>> read() => new Future<List<int>>.value(_contents).asStream(); 84 Stream<List<int>> read() => new Future<List<int>>.value(_contents).asStream();
71 85
72 String toString() { 86 String toString() {
(...skipping 19 matching lines...) Expand all
92 buffer.write(byteToHex(_contents[i])); 106 buffer.write(byteToHex(_contents[i]));
93 } 107 }
94 } 108 }
95 109
96 buffer.write("]"); 110 buffer.write("]");
97 return buffer.toString(); 111 return buffer.toString();
98 } 112 }
99 } 113 }
100 114
101 /// An asset backed by a file on the local file system. 115 /// An asset backed by a file on the local file system.
102 class _FileAsset extends Asset { 116 class FileAsset implements Asset {
117 final AssetId id;
118
103 /// Use a [FilePool] to handle reads so we can try to cope with running out 119 /// Use a [FilePool] to handle reads so we can try to cope with running out
104 /// of file descriptors more gracefully. 120 /// of file descriptors more gracefully.
105 static final _pool = new FilePool(); 121 static final _pool = new FilePool();
106 122
107 final File _file; 123 final String _path;
108 _FileAsset(AssetId id, this._file) 124 FileAsset(this.id, this._path);
109 : super(id);
110 125
111 Future<String> readAsString({Encoding encoding}) { 126 Future<String> readAsString({Encoding encoding}) {
112 if (encoding == null) encoding = UTF8; 127 if (encoding == null) encoding = UTF8;
113 return _pool.readAsString(_file, encoding); 128 return _pool.readAsString(_path, encoding);
114 } 129 }
115 130
116 Stream<List<int>> read() => _pool.openRead(_file); 131 Stream<List<int>> read() => _pool.openRead(_path);
117 132
118 String toString() => 'File "${_file.path}"'; 133 String toString() => 'File "${_path}"';
119 } 134 }
120 135
121 /// An asset whose data is stored in a string. 136 /// An asset whose data is stored in a string.
122 class _StringAsset extends Asset { 137 class StringAsset implements Asset {
138 final AssetId id;
139
123 final String _contents; 140 final String _contents;
124 141
125 _StringAsset(AssetId id, this._contents) 142 StringAsset(this.id, this._contents);
126 : super(id);
127 143
128 Future<String> readAsString({Encoding encoding}) => 144 Future<String> readAsString({Encoding encoding}) =>
129 new Future.value(_contents); 145 new Future.value(_contents);
130 146
131 Stream<List<int>> read() => 147 Stream<List<int>> read() =>
132 new Future<List<int>>.value(UTF8.encode(_contents)).asStream(); 148 new Future<List<int>>.value(UTF8.encode(_contents)).asStream();
133 149
134 String toString() { 150 String toString() {
135 // Don't show the whole string if it's long. 151 // Don't show the whole string if it's long.
136 var contents = _contents; 152 var contents = _contents;
137 if (contents.length > 40) { 153 if (contents.length > 40) {
138 contents = contents.substring(0, 20) + " ... " + 154 contents = contents.substring(0, 20) + " ... " +
139 contents.substring(contents.length - 20); 155 contents.substring(contents.length - 20);
140 } 156 }
141 157
142 contents = _escape(contents); 158 contents = _escape(contents);
143 return 'String "$contents"'; 159 return 'String "$contents"';
144 } 160 }
145 161
146 String _escape(String string) { 162 String _escape(String string) {
147 return string 163 return string
148 .replaceAll("\"", r'\"') 164 .replaceAll("\"", r'\"')
149 .replaceAll("\n", r"\n") 165 .replaceAll("\n", r"\n")
150 .replaceAll("\r", r"\r") 166 .replaceAll("\r", r"\r")
151 .replaceAll("\t", r"\t"); 167 .replaceAll("\t", r"\t");
152 } 168 }
153 } 169 }
154 170
155 /// An asset whose data is available from a stream. 171 /// An asset whose data is available from a stream.
156 class _StreamAsset extends Asset { 172 class StreamAsset implements Asset {
173 final AssetId id;
174
157 /// A stream replayer that records and replays the contents of the input 175 /// A stream replayer that records and replays the contents of the input
158 /// stream. 176 /// stream.
159 final StreamReplayer<List<int>> _replayer; 177 final StreamReplayer<List<int>> _replayer;
160 178
161 _StreamAsset(AssetId id, Stream<List<int>> stream) 179 StreamAsset(this.id, Stream<List<int>> stream)
162 : _replayer = new StreamReplayer(stream), 180 : _replayer = new StreamReplayer(stream);
163 super(id);
164 181
165 Future<String> readAsString({Encoding encoding}) { 182 Future<String> readAsString({Encoding encoding}) {
166 if (encoding == null) encoding = UTF8; 183 if (encoding == null) encoding = UTF8;
167 return _replayer.getReplay().toList() 184 return _replayer.getReplay().toList()
168 .then((chunks) => encoding.decode(flatten(chunks))); 185 .then((chunks) => encoding.decode(flatten(chunks)));
169 } 186 }
170 187
171 Stream<List<int>> read() => _replayer.getReplay(); 188 Stream<List<int>> read() => _replayer.getReplay();
172 189
173 String toString() => "Stream"; 190 String toString() => "Stream";
174 } 191 }
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698