summaryrefslogtreecommitdiffstats
path: root/blimp/net/stream_packet_writer.h
blob: a13711b84009ea85e57c9207a927e0a474acd842 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#ifndef BLIMP_NET_STREAM_PACKET_WRITER_H_
#define BLIMP_NET_STREAM_PACKET_WRITER_H_

#include <string>

#include "base/macros.h"
#include "base/memory/ref_counted.h"
#include "base/threading/thread_checker.h"
#include "blimp/net/blimp_net_export.h"
#include "blimp/net/packet_writer.h"
#include "net/base/completion_callback.h"
#include "net/base/net_errors.h"

namespace net {
class DrainableIOBuffer;
class StreamSocket;
}  // namespace net

namespace blimp {

// Writes opaque length-prefixed packets to a StreamSocket.
// The header segment is 32-bit, encoded in network byte order.
// The body segment length is specified in the header (should be capped at
//     kMaxPacketPayloadSizeBytes).
class BLIMP_NET_EXPORT StreamPacketWriter : public PacketWriter {
 public:
  // |socket|: The socket to write packets to. The caller must ensure |socket|
  // is valid while the reader is in-use (see ReadPacket below).
  explicit StreamPacketWriter(net::StreamSocket* socket);

  ~StreamPacketWriter() override;

  // PacketWriter implementation.
  void WritePacket(const scoped_refptr<net::DrainableIOBuffer>& data,
                   const net::CompletionCallback& callback) override;

 private:
  enum class WriteState {
    IDLE,
    HEADER,
    PAYLOAD,
  };

  friend std::ostream& operator<<(std::ostream& out, const WriteState state);

  // State machine implementation.
  // |result| - the result value of the most recent network operation.
  // See comments for WritePacket() for documentation on return values.
  int DoWriteLoop(int result);

  int DoWriteHeader(int result);

  int DoWritePayload(int result);

  // Callback function to be invoked on asynchronous write completion.
  // Invokes |callback_| on packet write completion or on error.
  void OnWriteComplete(int result);

  WriteState write_state_;

  net::StreamSocket* socket_;

  scoped_refptr<net::DrainableIOBuffer> payload_buffer_;
  scoped_refptr<net::DrainableIOBuffer> header_buffer_;
  net::CompletionCallback callback_;

  base::WeakPtrFactory<StreamPacketWriter> weak_factory_;

  DISALLOW_COPY_AND_ASSIGN(StreamPacketWriter);
};

}  // namespace blimp

#endif  // BLIMP_NET_STREAM_PACKET_WRITER_H_