8ef626da982856c34c621a56bf494976c6102e80
[senf.git] / Scheduler / WriteHelper.ct
1 // $Id$
2 //
3 // Copyright (C) 2006 
4
5 // Definition of non-inline template functions
6
7 //#include "WriteHelper.ih"
8
9 // Custom includes
10 #include <errno.h>
11 #include "Utils/Exception.hh"
12 #include "Scheduler.hh"
13
14 #define prefix_
15 ///////////////////////////////ct.p////////////////////////////////////////
16
17 template <class Handle>
18 prefix_ satcom::lib::WriteHelper<Handle>::WriteHelper(Handle handle, std::string data,
19                                                       Callback callback)
20     : handle_(handle), data_(data), callback_(callback),
21       offset_(0), errno_(0)
22 {
23     satcom::lib::Scheduler::instance()
24         .add(handle_, boost::bind(&WriteHelper::dispatchProcess, ptr(this), _1, _2),
25              satcom::lib::Scheduler::EV_WRITE);
26 }
27
28 template <class Handle>
29 prefix_ std::string const & satcom::lib::WriteHelper<Handle>::data()
30     const
31 {
32     if (offset_ > 0) {
33         data_.erase(0,offset_);
34         offset_ = 0;
35     }
36     return data_;
37 }
38
39 template <class Handle>
40 prefix_ void satcom::lib::WriteHelper<Handle>::revoke()
41 {
42     ptr guard (this); // To ensure, 'this' is deleted only after this method terminates ...
43     satcom::lib::Scheduler::instance()
44         .remove(handle_, satcom::lib::Scheduler::EV_WRITE);
45 }
46
47 template <class Handle>
48 prefix_ void
49 satcom::lib::WriteHelper<Handle>::dispatchProcess(ptr helper, Handle handle,
50                                                   satcom::lib::Scheduler::EventId event)
51 {
52     // since we have a 'ptr' argument, the instance cannot be deleted
53     // before this method returns
54     return helper->process(handle,event);
55 }
56
57 template <class Handle>
58 prefix_ void satcom::lib::WriteHelper<Handle>::process(Handle handle,
59                                                        satcom::lib::Scheduler::EventId event)
60 {
61     try {
62         if (event != satcom::lib::Scheduler::EV_WRITE)
63             throw satcom::lib::SystemException(EPIPE);
64         offset_ += handle.write(data_.data()+offset_,data_.size()-offset_);
65         if (offset_ >= data_.size()) {
66             data_.erase();
67             done();
68         }
69     }
70     catch (satcom::lib::SystemException const & ex) {
71         errno_ = ex.err;
72         done();
73     }
74 }
75
76 template <class Handle>
77 prefix_ void satcom::lib::WriteHelper<Handle>::done()
78 {
79     revoke();
80     callback_(ptr(this));
81 }
82
83 ///////////////////////////////ct.e////////////////////////////////////////
84 #undef prefix_
85
86 \f
87 // Local Variables:
88 // mode: c++
89 // End: