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