1 /**
2  * This program is free software; you can redistribute it and/or modify
3  * it under the terms of the GNU General Public License as published by
4  * the Free Software Foundation; either version 2 of the License, or
5  * (at your option) any later version.
6  *
7  * net/socket_binder.h
8  * (c) 2007 Murat Deligonul
9  */
10 
11 #ifndef __NET_SOCKET_BINDER_H
12 #define __NET_SOCKET_BINDER_H
13 
14 #include "net/socket.h"
15 
16 namespace net {
17 
18 /**
19   * Essentially a 'glue' class that binds socket callback functions to
20   * member functions of another class.
21   */
22 template <class T,
23 	 	int (T::*on_readable_fn)(),
24 		int (T::*on_writeable_fn)(),
25 		void (T::*on_connect_fn)(),
26 		void (T::*on_disconnect_fn)(int),
27 		void (T::*on_connect_fail_fn)(int),
28 		void (T::*on_connecting_fn)()>
29 	class socket_binder : public socket {
30 private:
31 	T * owner;
32 
33 public:
34 	// Construct by accept()'ing from source
socket_binder(T * o,socket * source,size_t min,size_t max)35 	socket_binder(T * o, socket * source, size_t min, size_t max) :
36 		socket(source, min, max),
37 		owner(o) { }
38 	// Create from scratch
socket_binder(T * o,int family,int options,size_t min,size_t max)39 	socket_binder(T * o, int family, int options, size_t min, size_t max) :
40 		socket(family, options, min, max),
41 		owner(o) { }
42 
~socket_binder()43 	~socket_binder() { }
44 
45 	// Reassign owner
set_owner(T * o)46 	void set_owner(T * o) {
47 		owner = o;
48 	}
49 
50 public:
51 	/**
52 	  * Binding callback functions.
53 	  */
on_readable()54 	virtual int on_readable() {
55 		return (owner->*on_readable_fn)();
56 	}
on_writeable()57 	virtual int on_writeable() {
58 		return (owner->*on_writeable_fn)();
59 	}
on_disconnect(int e)60 	virtual void on_disconnect(int e) {
61 		(owner->*on_disconnect_fn)(e);
62 	}
on_connect()63 	virtual void on_connect() {
64 		(owner->*on_connect_fn)();
65 		socket::on_connect();
66 	}
on_connect_fail(int e)67 	virtual void on_connect_fail(int e) {
68 		(owner->*on_connect_fail_fn)(e);
69 	}
on_connecting()70 	virtual void on_connecting() {
71 		(owner->*on_connecting_fn)();
72 	}
73 
74 private:
75 	// non-copyable
76 	socket_binder(const socket_binder&);
77 	socket_binder& operator = (const socket_binder&);
78 };
79 
80 }	/* namespace net */
81 #endif	/* __NET_SOCKET_BINDER_H */
82