1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
#![deny(missing_docs)]
#![forbid(missing_debug_implementations)]

//! Defines the types and helpers for binary/library communication.
//!
//! The general idea is that the user will run a driver program which calls
//! `game_init` to get a handle, and then gets lines from the user and passes
//! them to `game_process_line`, and prints the output. At some point the
//! driving program might try to exit cleanly, and if so it'll call `game_drop`.
//! Of course, the driving program might suddenly die at any moment without
//! `game_drop` ever being called, so I wouldn't rely on that happening.
//!
//! Note that all of the interchange types are fully compatible with the C ABI,
//! so you don't _have_ to use Rust if you don't want to. As long as you follow
//! the types you can write your DLL and/or driving program in any language you
//! like.
//!
//! To be loaded properly, your DLL should have one function of each function
//! type given here, named in snake_case without the "Fn" part at the end:
//!
//! * [`GameInitFn`](type.GameInitFn.html): `game_init`
//! * [`GameProcessLineFn`](type.GameProcessLineFn.html): `game_process_line`
//! * [`GameDropFn`](type.GameDropFn.html): `game_drop`
//!
//! # Building a game DLL with cargo
//!
//! First, be sure to mark your functions with `#[no_mangle]` and `pub`. You
//! must also have "cdylib" as one of your `crate-type` values for your crate's
//! library portion. If you want `cargo test` to work properly, you'll need
//! "rlib" as well. It'll look something like this:
//!
//! ```toml
//! [lib]
//! name = "vibha"
//! path = "src/lib.rs"
//! crate-type = ["rlib", "cdylib"]
//! ```
//!
//! You can easily ensure that your functions have the correct type at compile
//! time with a simple set of `const` declarations.
//!
//! A "complete" example might look something like this.
//!
//! ```rust
//! extern crate vibha;
//! use vibha::*;
//! use std::io::Write;
//! use std::os::raw::c_void;
//!
//! struct GameState {
//!   world_seed: u64,
//!   call_count: u64,
//! }
//!
//! #[no_mangle]
//! pub unsafe extern "C" fn game_init(world_seed: u64) -> *mut c_void {
//!   Box::into_raw(Box::new(GameState {
//!     world_seed,
//!     call_count: 0
//!   })) as *mut c_void
//! }
//!
//! #[no_mangle]
//! pub unsafe extern "C" fn game_process_line(handle: *mut c_void,
//!         line: *const u8, line_len: usize, mut buf: *mut u8, buf_len: usize) -> usize {
//!   if handle.is_null() || line.is_null() || buf.is_null() {
//!     return 0;
//!   }
//!   let user_line = ffi_recover_str(&line, line_len);
//!   let mut out_buffer = ffi_recover_out_buffer(&mut buf, buf_len);
//!   let game_state: &mut GameState =
//!     (handle as *mut GameState).as_mut().expect("game session was null!");
//!   // do something silly just so we can see an effect
//!   game_state.call_count += 1;
//!   if user_line.len() > 0 {
//!     write!(out_buffer, "{}: {}", game_state.call_count, user_line).ok();
//!   } else {
//!     write!(out_buffer, "{}: {}", game_state.call_count, game_state.world_seed).ok();
//!   }
//!   out_buffer.position() as usize
//! }
//!
//! #[no_mangle]
//! pub unsafe extern "C" fn game_drop(handle: *mut c_void) {
//!   Box::from_raw(handle as *mut GameState);
//! }
//!
//! #[allow(dead_code)]
//! const GAME_INIT_CONST: GameInitFn = game_init;
//! #[allow(dead_code)]
//! const GAME_PROCESS_LINE_CONST: GameProcessLineFn = game_process_line;
//! #[allow(dead_code)]
//! const GAME_DROP_CONST: GameDropFn = game_drop;
//! ```

use std::borrow::{Borrow, Cow};
use std::io::Cursor;
use std::os::raw::c_void;

/// Initializes a game session.
///
/// The argument passed is expected to be used as an RNG seed of some sort. If
/// your game has no randomization at all it can be ignored, but otherwise you
/// should use this seed in place of any other seed source.
///
/// Returns a pointer to the game data, which is then passed along to the other
/// two functions of the DLL. If the game somehow couldn't be initialized you
/// can return a null pointer instead.
///
/// Your game DLL should store all data for the game within the game data
/// structure. It should not use globals of any kind. This way the driving
/// program can run more than one session of the game at the same time (eg: a
/// single bot that runs a different session of the game for each player that
/// PMs it).
pub type GameInitFn = unsafe extern "C" fn(u64) -> *mut c_void;

/// Processes a single line of user input.
///
/// * The first argument is the pointer to the game data.
/// * The next two arguments are a pointer to the bytes and length of bytes for
///   the user's input line. Taken together these two values act like a rust
///   `&str`, just in an FFI usable form. The bytes are _probably_ valid utf-8,
///   but it's up to you how resilient you want to be about that.
///   [`ffi_recover_str`](fn.ffi_recover_str.html) can handle this for you.
/// * The final two arguments are a pointer to some bytes and a size for the
///   allocation. This can be converted into a `&mut [u8]` and then you can
///   write into it. You should obviously write valid utf-8 if at all possible,
///   but the driving program should not explode if you don't. You probably want
///   to use [`ffi_recover_out_buffer`](fn.ffi_recover_out_buffer.html).
///
/// The return value is the number of bytes written into the output buffer.
///
/// The output that goes back to the driving program will generally be displayed
/// as a "block" of text in a format appropriate to the user's interface (PC
/// terminal, phone app, IRC bot, etc). You do not need to place a newline at
/// the end. Text can be expected to be wrapped by the driver in a way
/// appropriate to the display, but you can also expect that a newline (`'\n'`)
/// in the middle of output will be respected if possible (eg: IRC flood
/// protection might limit the number of lines allowed to a channel within a
/// short period of time).
///
/// The input buffer can contain an `SOH` character (`'\x01'`) to switch to
/// "header mode", allowing the driving program to send special info to the game
/// about what capabilities it supports. The `STX` character (`'\x02'`) can be
/// used to switch the input back to "text mode". Every input line starts in
/// text mode, regardless of the mode that the last line ended with. Similarly,
/// the output buffer can use `SOH` and `STX` to swap output into header mode or
/// back to text mode. This can allow the game to specify special text
/// formatting such as applying color effects. All of this can be parsed out for
/// you by using [`mode_split_str`](fn.mode_split_str.html).
///
/// The exact details of any header mode information is unfortunately still up
/// in the air.
///
/// If either side does not care to process the special info that's fine,
/// however they MUST still at least process that the mode switch happened, and
/// then pass over header mode characters until the mode switches back to text
/// mode. Just call [`filter_text_only`](fn.filter_text_only.html) and pass in
/// your `mode_split_str` result and you'll get a plain old `String` with just
/// the text back.
pub type GameProcessLineFn = unsafe extern "C" fn(*mut c_void, *const u8, usize, *mut u8, usize) -> usize;

/// Frees up the game session data.
///
/// The argument given must be a game data pointer obtained from the
/// initialization function of this same DLL, or you'll have a very bad time.
pub type GameDropFn = unsafe extern "C" fn(*mut c_void);

/// Converts the const pointer and len for the user's input line into a rusty
/// form.
///
/// This accepts a reference to a const pointer so that the lifetime of the
/// `Cow` value can be properly tracked. This way you can't make the Cow
/// accidentally outlive the pointer it was built from.
///
/// ```rust
/// extern crate vibha;
/// use vibha::ffi_recover_str;
///
/// let static_str = "demo";
/// let ptr_ref = &static_str.as_ptr();
/// let len = static_str.len();
/// let recovered_value = unsafe { ffi_recover_str(ptr_ref, len) };
/// assert_eq!(static_str, recovered_value);
/// ```
pub unsafe fn ffi_recover_str<'a>(ptr_ref: &'a *const u8, len: usize) -> Cow<'a, str> {
  assert!(!ptr_ref.is_null());
  let slice = ::std::slice::from_raw_parts(*ptr_ref, len);
  String::from_utf8_lossy(slice)
}

/// Converts the pointer and len for the output buffer into a rusty form.
///
/// This accepts a mutable reference to a mut pointer so that the lifetime of
/// the `Cursor` will be correct. It can't accidentally outlive the pointer it
/// was based on. You also can't accidentally make two buffers to the same
/// block of data.
///
/// ```rust
/// extern crate vibha;
/// use vibha::ffi_recover_out_buffer;
/// use std::io::Write;
///
/// const BUFFER_SIZE: usize = 20;
/// let mut vec: Vec<u8> = Vec::with_capacity(BUFFER_SIZE);
/// unsafe { vec.set_len(BUFFER_SIZE) };
/// {
///   let len = vec.len();
///   let ptr_ref_mut = &mut unsafe { vec.as_mut_ptr() };
///   let mut cursor = unsafe { ffi_recover_out_buffer(ptr_ref_mut, len) };
///   write!(cursor, "a");
/// }
/// assert_eq!(vec[0], 'a' as u8);
/// ```
pub unsafe fn ffi_recover_out_buffer<'a>(ptr_ref_mut: &'a mut *mut u8, len: usize) -> Cursor<&'a mut [u8]> {
  assert!(!ptr_ref_mut.is_null());
  let slice_mut = ::std::slice::from_raw_parts_mut(*ptr_ref_mut, len);
  Cursor::new(slice_mut)
}

/// Wraps a string slice with a "mode" tag.
///
/// If you `Display` a modal slice, a Text will prefix itself with `'\x02'` to
/// ensure that it's in text mode. Similarly, a Header will start with `'\x01'`
/// and end with `'\x02'`. This way you're always in text mode by default, and
/// writes that don't use `ModalSlice` can assume that things are always in text
/// mode.
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone, Copy)]
pub enum ModalSlice<'a> {
  /// A slice of textual data.
  Text(&'a str),

  /// A slice of header data.
  Header(&'a str),
}

impl<'a> ::std::fmt::Display for ModalSlice<'a> {
  fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
    match self {
      &ModalSlice::Header(s) => write!(f, "\x01{}\x02", s),
      &ModalSlice::Text(s) => write!(f, "\x02{}", s),
    }
  }
}

/// Breaks up a `&str` in the special way demanded by the
/// [`GameProcessLineFn`](type.GameProcessLineFn.html) docs.
///
/// ```rust
/// extern crate vibha;
/// use vibha::*;
///
/// // plain string
/// assert_eq!(mode_split_str(""), vec![]);
/// assert_eq!(mode_split_str("foo"), vec![ModalSlice::Text("foo")]);
///
/// // header then text
/// assert_eq!(mode_split_str("\x01header\x02foo"),
///   vec![ModalSlice::Header("header"),
///        ModalSlice::Text("foo")]);
///
/// // empty slices are pruned for you
/// assert_eq!(mode_split_str("\x01\x02foo"), vec![ModalSlice::Text("foo")]);
///
/// // you can "switch" to the same mode you're already "in"
/// assert_eq!(mode_split_str("\x01A\x01B\x02foo"),
///   vec![ModalSlice::Header("A"),
///        ModalSlice::Header("B"),
///        ModalSlice::Text("foo")]);
/// ```
pub fn mode_split_str(line: &str) -> Vec<ModalSlice> {
  let mut output = Vec::new();
  let mut char_iter = line.bytes().enumerate();
  let mut this_slice_start = 0;
  let mut text_mode = true;
  while let Some((index, byte)) = char_iter.next() {
    if byte == 1 || byte == 2 {
      if index - this_slice_start > 0 {
        output.push(if text_mode {
          ModalSlice::Text(&line[this_slice_start..index])
        } else {
          ModalSlice::Header(&line[this_slice_start..index])
        });
      }
      this_slice_start = index + 1;
      text_mode = match byte {
        1 => false,
        2 => true,
        _ => unreachable!(),
      };
    } else {
      continue;
    }
  }
  // do the last slice
  if this_slice_start != line.len() {
    output.push(if text_mode {
      ModalSlice::Text(&line[this_slice_start..line.len()])
    } else {
      ModalSlice::Header(&line[this_slice_start..line.len()])
    });
  }
  // return
  output
}

/// Filters the results of `mode_split_str` into just the textual part.
///
/// ```rust
/// extern crate vibha;
/// use vibha::*;
///
/// assert_eq!(filter_text_only(mode_split_str("\x01A\x01B\x02foo")), "foo");
/// ```
pub fn filter_text_only<'a, V: Borrow<Vec<ModalSlice<'a>>>>(vec_borrow: V) -> String {
  let vec_ref = vec_borrow.borrow();
  let mut output = String::new();
  for modal in vec_ref {
    match modal {
      &ModalSlice::Header(_) => {}
      &ModalSlice::Text(s) => output.push_str(s),
    }
  }
  output
}

/// Requests the game to display its introduction.
///
/// When the driver wants the game to give its introduction, but naturally
/// doesn't have user input to send yet, it will send this instead. Note that
/// the driver also might begin sending actual player commands without having
/// sent this first.
pub const INTRO_HEADER: ModalSlice<'static> = ModalSlice::Header("INTRO");

/// Signals that the driver supports ANSI color outputs.
///
/// The game can define when color changes should happen within the display by
/// placing the appropriate header values into the output buffer. There's a
/// complete set for both `FOREGROUND_` and `BACKGROUND_` values.
pub const ANSI_COLOR_AVAILABLE_HEADER: ModalSlice<'static> = ModalSlice::Header("ANSI_COLOR_AVAILABLE");

/// Makes the foreground black until the end of this output
pub const FOREGROUND_BLACK: ModalSlice<'static> = ModalSlice::Header("k");
/// Makes the foreground red until the end of this output
pub const FOREGROUND_RED: ModalSlice<'static> = ModalSlice::Header("r");
/// Makes the foreground green until the end of this output
pub const FOREGROUND_GREEN: ModalSlice<'static> = ModalSlice::Header("g");
/// Makes the foreground yellow until the end of this output
pub const FOREGROUND_YELLOW: ModalSlice<'static> = ModalSlice::Header("y");
/// Makes the foreground blue until the end of this output
pub const FOREGROUND_BLUE: ModalSlice<'static> = ModalSlice::Header("b");
/// Makes the foreground magenta until the end of this output
pub const FOREGROUND_MAGENTA: ModalSlice<'static> = ModalSlice::Header("m");
/// Makes the foreground cyan until the end of this output
pub const FOREGROUND_CYAN: ModalSlice<'static> = ModalSlice::Header("c");
/// Makes the foreground white until the end of this output
pub const FOREGROUND_WHITE: ModalSlice<'static> = ModalSlice::Header("w");

/// Makes the background black until the end of this output
pub const BACKGROUND_BLACK: ModalSlice<'static> = ModalSlice::Header("K");
/// Makes the background red until the end of this output
pub const BACKGROUND_RED: ModalSlice<'static> = ModalSlice::Header("R");
/// Makes the background green until the end of this output
pub const BACKGROUND_GREEN: ModalSlice<'static> = ModalSlice::Header("G");
/// Makes the background yellow until the end of this output
pub const BACKGROUND_YELLOW: ModalSlice<'static> = ModalSlice::Header("Y");
/// Makes the background blue until the end of this output
pub const BACKGROUND_BLUE: ModalSlice<'static> = ModalSlice::Header("B");
/// Makes the background magenta until the end of this output
pub const BACKGROUND_MAGENTA: ModalSlice<'static> = ModalSlice::Header("M");
/// Makes the background cyan until the end of this output
pub const BACKGROUND_CYAN: ModalSlice<'static> = ModalSlice::Header("C");
/// Makes the background white until the end of this output
pub const BACKGROUND_WHITE: ModalSlice<'static> = ModalSlice::Header("W");

/// Allows you to specify a protocol version.
///
/// Place this into your line or out buffer by "displaying" an appropriate
/// version value.
///
/// ```rust
/// extern crate vibha;
/// use vibha::*;
/// use std::io::Write;
///
/// let mut vec: Vec<u8> = vec![];
/// write!(vec, "{}", VibhaVersion(1));
/// assert_eq!(unsafe { std::str::from_utf8_unchecked(&vec) }, "\x01VibhaVersion=1\x02");
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct VibhaVersion(pub u64);

impl ::std::fmt::Display for VibhaVersion {
  fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
    write!(f, "\x01{}{}\x02", VIBHA_VERSION_PREFIX, self.0)
  }
}

/// The prefix for the formatted vibha version header.
pub const VIBHA_VERSION_PREFIX: &'static str = "VibhaVersion=";