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