1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* vim: set ts=2 et sw=2 tw=80: */
3 /* This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this file,
5 * You can obtain one at http://mozilla.org/MPL/2.0/. */
7 // Original author: ekr@rtfm.com
9 #ifndef transportlayer_h__
10 #define transportlayer_h__
14 #include "mozilla/DebugOnly.h"
15 #include "mozilla/RefPtr.h"
17 #include "nsIEventTarget.h"
19 #include "m_cpp_utils.h"
25 typedef int TransportResult
;
28 TE_WOULDBLOCK
= -1, TE_ERROR
= -2, TE_INTERNAL
= -3
31 #define TRANSPORT_LAYER_ID(name) \
32 virtual const std::string id() const { return name; } \
33 static std::string ID() { return name; }
35 // Abstract base class for network transport layers.
36 class TransportLayer
: public sigslot::has_slots
<> {
38 // The state of the transport flow
39 // We can't use "ERROR" because Windows has a macro named "ERROR"
40 enum State
{ TS_NONE
, TS_INIT
, TS_CONNECTING
, TS_OPEN
, TS_CLOSED
, TS_ERROR
};
42 // Is this a stream or datagram flow
48 virtual ~TransportLayer() {}
50 // Called to initialize
51 nsresult
Init(); // Called by Insert() to set up -- do not override
52 virtual nsresult
InitInternal() { return NS_OK
; } // Called by Init
54 // Called when inserted into a flow
55 virtual void Inserted(TransportFlow
*flow
, TransportLayer
*downward
);
58 TransportLayer
*downward() { return downward_
; }
60 // Dispatch a call onto our thread (or run on the same thread if
61 // thread is not set). This is always synchronous.
62 nsresult
RunOnThread(nsIRunnable
*event
);
65 State
state() const { return state_
; }
66 // Must be implemented by derived classes
67 virtual TransportResult
SendPacket(const unsigned char *data
, size_t len
) = 0;
70 const nsCOMPtr
<nsIEventTarget
> GetThread() const {
74 // Event definitions that one can register for
76 sigslot::signal2
<TransportLayer
*, State
> SignalStateChange
;
77 // Data received on the flow
78 sigslot::signal3
<TransportLayer
*, const unsigned char *, size_t>
81 // Return the layer id for this layer
82 virtual const std::string
id() const = 0;
85 const std::string
& flow_id() const {
90 virtual void WasInserted() {}
91 virtual void SetState(State state
, const char *file
, unsigned line
);
92 // Check if we are on the right thread
93 void CheckThread() const {
94 NS_ABORT_IF_FALSE(CheckThreadInt(), "Wrong thread");
99 TransportLayer
*downward_
; // The next layer in the stack
100 nsCOMPtr
<nsIEventTarget
> target_
;
103 DISALLOW_COPY_ASSIGN(TransportLayer
);
105 bool CheckThreadInt() const {
108 if (!target_
) // OK if no thread set.
111 NS_ENSURE_SUCCESS(target_
->IsOnCurrentThread(&on
), false);
112 NS_ENSURE_TRUE(on
, false);
118 #define LAYER_INFO "Flow[" << flow_id() << "(none)" << "]; Layer[" << id() << "]: "
119 #define TL_SET_STATE(x) SetState((x), __FILE__, __LINE__)