/* Copyright 2010, 2011, 2012 Tony Garnock-Jones <tonygarnockjones@gmail.com>.
 *
 * This file is part of Hop.
 *
 * Hop is free software: you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Hop is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
 * or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public
 * License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Hop.  If not, see <http://www.gnu.org/licenses/>.
 */
#ifndef cmsg_harness_h
#define cmsg_harness_h

typedef void (*process_main_t)(void *);

typedef enum process_state_t_ {
  PROCESS_DEAD = 0,
  PROCESS_RUNNING,
  PROCESS_WAITING
} process_state_t;

typedef struct Process {
  process_state_t state;
  int wait_flags;
  void *stack_base;
  ucontext_t context;
  struct Process *link;
} Process;

typedef struct IOHandle {
  Process *waiters;
  int fd;
  struct bufferevent *io;
  int eof;
  unsigned short error_direction;
  unsigned short error_kind;
  int error_errno;
} IOHandle;

extern IOHandle *stdin_h;
extern IOHandle *stdout_h;
extern IOHandle *stderr_h;

extern Process *current_process;

extern void yield(void);
extern Process *spawn(process_main_t f, void *arg);
extern int nap(long millis); /* 1 for timeout expired; 0 for resumed early */

extern void suspend(void);
extern int resume(Process *p);

extern IOHandle *new_iohandle(int fd);
extern void delete_iohandle(IOHandle *h);
extern void iohandle_clear_error(IOHandle *h);
extern cmsg_bytes_t iohandle_readwait(IOHandle *h, size_t at_least);
extern void iohandle_drain(IOHandle *h, size_t count);
extern void iohandle_write(IOHandle *h, cmsg_bytes_t buf);
extern int iohandle_flush(IOHandle *h);
extern void iohandle_settimeout(IOHandle *h, int timeout_read, int timeout_write);

extern void boot_harness(void);
extern void interrupt_harness(void);

#endif
