Merge Network code with webserver etc
[clinton/Smoothieware.git] / src / libs / Network / uip / CallbackStream.cpp
1 #include "CallbackStream.h"
2 #include "Kernel.h"
3
4 #define DEBUG_PRINTF std::printf
5
6 CallbackStream::CallbackStream(cb_t cb, void *u)
7 {
8 DEBUG_PRINTF("Callbackstream ctor: %p\n", this);
9 callback= cb;
10 user= u;
11 closed= false;
12 use_count= 0;
13 }
14
15 CallbackStream::~CallbackStream()
16 {
17 DEBUG_PRINTF("Callbackstream dtor: %p\n", this);
18 }
19
20 int CallbackStream::puts(const char *s)
21 {
22 if(closed) return 0;
23
24 if(s == NULL) return (*callback)(NULL, user);
25
26 int len = strlen(s);
27 int n;
28 do {
29 // call this streams result callback
30 n= (*callback)(s, user);
31
32 // if closed just pretend we sent it
33 if(n == -1) {
34 closed= true;
35 return len;
36
37 }else if(n == 0) {
38 // if output queue is full
39 // call idle until we can output more
40 THEKERNEL->call_event(ON_IDLE);
41 }
42 } while(n == 0);
43
44 return len;
45 }
46
47 void CallbackStream::mark_closed()
48 {
49 closed= true;
50 if(use_count <= 0) delete this;
51 }
52 void CallbackStream::dec()
53 {
54 use_count--;
55 if(closed && use_count <= 0) delete this;
56 }
57
58 extern "C" void *new_callback_stream(cb_t cb, void *u)
59 {
60 return new CallbackStream(cb, u);
61 }
62
63 extern "C" void delete_callback_stream(void *p)
64 {
65 // we don't delete it in case it is still on the command queue
66 ((CallbackStream*)p)->mark_closed();
67 }