Upstream version 10.39.225.0
[platform/framework/web/crosswalk.git] / src / mojo / bindings / js / drain_data.h
1 // Copyright 2014 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 #ifndef MOJO_BINDINGS_JS_DRAIN_DATA_H_
6 #define MOJO_BINDINGS_JS_DRAIN_DATA_H_
7
8 #include "base/memory/scoped_vector.h"
9 #include "gin/runner.h"
10 #include "mojo/public/c/environment/async_waiter.h"
11 #include "mojo/public/cpp/system/core.h"
12 #include "v8/include/v8.h"
13
14 namespace mojo {
15 namespace js {
16
17 // This class is the implementation of the Mojo JavaScript core module's
18 // drainData() method. It is not intended to be used directly. The caller
19 // allocates a DrainData on the heap and returns GetPromise() to JS. The
20 // implementation deletes itself after reading as much data as possible
21 // and rejecting or resolving the Promise.
22
23 class DrainData {
24  public:
25   // Starts waiting for data on the specified data pipe consumer handle.
26   // See WaitForData(). The constructor does not block.
27   DrainData(v8::Isolate* isolate, mojo::Handle handle);
28
29   // Returns a Promise that will be settled when no more data can be read.
30   // Should be called just once on a newly allocated DrainData object.
31   v8::Handle<v8::Value> GetPromise();
32
33  private:
34   ~DrainData();
35
36   // Registers an "async waiter" that calls DataReady() via WaitCompleted().
37   void WaitForData();
38   static void WaitCompleted(void* self, MojoResult result) {
39     static_cast<DrainData*>(self)->DataReady(result);
40   }
41
42   // Use ReadData() to read whatever is availble now on handle_ and save
43   // it in data_buffers_.
44   void DataReady(MojoResult result);
45   MojoResult ReadData();
46
47   // When the remote data pipe handle is closed, or an error occurs, deliver
48   // all of the buffered data to the JS Promise and then delete this.
49   void DeliverData(MojoResult result);
50
51   typedef std::vector<char> DataBuffer;
52
53   v8::Isolate* isolate_;
54   ScopedDataPipeConsumerHandle handle_;
55   MojoAsyncWaitID wait_id_;
56   base::WeakPtr<gin::Runner> runner_;
57   v8::UniquePersistent<v8::Promise::Resolver> resolver_;
58   ScopedVector<DataBuffer> data_buffers_;
59 };
60
61 }  // namespace js
62 }  // namespace mojo
63
64 #endif  // MOJO_BINDINGS_JS_DRAIN_DATA_H_