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

Unified Diff: lib/src/body.dart

Issue 1327453002: Share a body across all versions of a message. (Closed) Base URL: git@github.com:dart-lang/shelf@master
Patch Set: Code review changes Created 5 years, 4 months 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 side-by-side diff with in-line comments
Download patch
« no previous file with comments | « CHANGELOG.md ('k') | lib/src/message.dart » ('j') | no next file with comments »
Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
Index: lib/src/body.dart
diff --git a/lib/src/body.dart b/lib/src/body.dart
new file mode 100644
index 0000000000000000000000000000000000000000..5d39be578433fe9345feb9ef8b3c20c89413c486
--- /dev/null
+++ b/lib/src/body.dart
@@ -0,0 +1,60 @@
+// Copyright (c) 2015, the Dart project authors. Please see the AUTHORS file
+// for details. All rights reserved. Use of this source code is governed by a
+// BSD-style license that can be found in the LICENSE file.
+
+library shelf.body;
+
+import 'dart:async';
+import 'dart:convert';
+
+/// The body of a request or response.
+///
+/// This tracks whether the body has been read. It's separate from [Message]
+/// because the message may be changed with [Message.change], but each instance
+/// should share a notion of whether the body was read.
+class Body {
+ /// The contents of the message body.
+ ///
+ /// This will be `null` after [read] is called.
+ Stream<List<int>> _stream;
+
+ Body._(this._stream);
+
+ /// Converts [body] to a byte stream and wraps it in a [Body].
+ ///
+ /// [body] may be either a [Body], a [String], a [Stream<List<int>>], or
+ /// `null`. If it's a [String], [encoding] will be used to convert it to a
+ /// [Stream<List<int>>].
+ factory Body(body, [Encoding encoding]) {
+ if (encoding == null) encoding = UTF8;
+
+ if (body is Body) return body;
+
+ var stream;
+ if (body == null) {
+ stream = new Stream.fromIterable([]);
+ } else if (body is String) {
+ stream = new Stream.fromIterable([encoding.encode(body)]);
+ } else if (body is Stream) {
+ stream = body;
+ } else {
+ throw new ArgumentError('Response body "$body" must be a String or a '
+ 'Stream.');
+ }
+
+ return new Body._(stream);
+ }
+
+ /// Returns a [Stream] representing the body.
+ ///
+ /// Can only be called once.
+ Stream<List<int>> read() {
+ if (_stream == null) {
+ throw new StateError("The 'read' method can only be called once on a "
+ "shelf.Request/shelf.Response object.");
+ }
+ var stream = _stream;
+ _stream = null;
+ return stream;
+ }
+}
« no previous file with comments | « CHANGELOG.md ('k') | lib/src/message.dart » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698