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
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
//! # Monotron API
//!
//! This crate contains the Userspace to Kernel API for the Monotron.
//!
//! It is pulled in by the Kernel (github.com/thejpster/monotron) and the
//! various user-space example applications
//! (github.com/thejpster/monotron-apps).
//!
//! The API in here is modelled after both the UNIX/POSIX API and the MS-DOS
//! API. We use function pointers rather than `SWI` calls (software
//! interrupts), provided in a structure. This structure is designed to be
//! extensible.
//!
//! A C header file version of this API can be generated with `cbindgen`.
//!
//! All types in this file must be `#[repr(C)]`.
#![cfg_attr(not(test), no_std)]
#![deny(missing_docs)]

/// The set of Error codes the API can report.
#[repr(C)]
#[derive(Debug, Clone, Copy)]
pub enum Error {
    /// The given filename was not found
    FileNotFound,
    /// The given file handle was not valid
    BadFileHandle,
    /// Error reading or writing
    IOError,
    /// You can't do that operation on that sort of file
    NotSupported,
    /// An unknown error occured
    Unknown = 0xFFFF,
}

/// Describes a handle to some resource.
#[repr(C)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Handle(pub u16);

/// Describes a string of fixed length, which must not be free'd by the
/// recipient. The given length must not include any null terminators that may
/// be present. The string must be valid UTF-8 (or 7-bit ASCII, which is a
/// valid subset of UTF-8).
#[repr(C)]
#[derive(Debug, Clone, Eq)]
pub struct BorrowedString {
    /// The start of the string
    pub ptr: *const u8,
    /// The length of the string in bytes
    pub length: usize,
}

impl BorrowedString {
    /// Create a new API-compatible borrowed string, from a static string slice.
    pub fn new(value: &'static str) -> BorrowedString {
        BorrowedString {
            ptr: value.as_ptr(),
            length: value.len(),
        }
    }
}

impl core::cmp::PartialEq for BorrowedString {
    fn eq(&self, rhs: &BorrowedString) -> bool {
        if self.length == rhs.length {
            let left = unsafe { core::slice::from_raw_parts(self.ptr, self.length) };
            let right = unsafe { core::slice::from_raw_parts(rhs.ptr, rhs.length) };
            left == right
        } else {
            false
        }
    }
}

/// Describes the result of a function which may return a `Handle` if
/// everything was Ok, or return an `Error` if something went wrong.
///
/// This is not a standard Rust `Result` because they are not `#[repr(C)]`.
#[repr(C)]
#[derive(Debug)]
pub enum HandleResult {
    /// Success - a handle is returned
    Ok(Handle),
    /// Failure - an error is returned
    Error(Error),
}

/// Describes the result of a function which may return nothing if everything
/// was Ok, or return an `Error` if something went wrong.
///
/// This is not a standard Rust `Result` because they are not `#[repr(C)]`.
#[repr(C)]
#[derive(Debug)]
pub enum EmptyResult {
    /// Success - nothing is returned
    Ok,
    /// Failure - an error is returned
    Error(Error),
}

/// Describes the result of a function which may return a numeric count of
/// bytes read/written if everything was Ok, or return an `Error` if something
/// went wrong.
///
/// This is not a standard Rust `Result` because they are not `#[repr(C)]`.
#[repr(C)]
#[derive(Debug)]
pub enum SizeResult {
    /// Success - a size in bytes is returned
    Ok(usize),
    /// Failure - an error is returned
    Error(Error),
}

/// Describes the sort of files you will find in the system-wide virtual
/// filesystem. Some exist on disk, and some do not.
#[repr(C)]
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub enum FileType {
    /// A regular file
    File,
    /// A directory contains other files and directories
    Directory,
    /// A device you can read/write a block (e.g. 512 bytes) at a time
    BlockDevice,
    /// A device you can read/write one or more bytes at a time
    CharDevice,
}

/// Describes an instant in time. The system only supports local time and has
/// no concept of time zones.
#[repr(C)]
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Timestamp {
    /// The Gregorian calendar year, minus 1970 (so 10 is 1980, and 30 is the year 2000)
    pub year_from_1970: u8,
    /// The month of the year, where January is 1 and December is 12
    pub month: u8,
    /// The day of the month where 1 is the first of the month, through to 28,
    /// 29, 30 or 31 (as appropriate)
    pub days: u8,
    /// The hour in the day, from 0 to 23
    pub hours: u8,
    /// The minutes past the hour, from 0 to 59
    pub minutes: u8,
    /// The seconds past the minute, from 0 to 59. Note that some filesystems
    /// only have 2-second precision on their timestamps.
    pub seconds: u8,
}

/// Represents the seven days of the week
#[repr(C)]
#[derive(Debug, Eq, PartialEq, Ord, PartialOrd)]
pub enum DayOfWeek {
    /// First day of the week
    Monday,
    /// Comes after Monday
    Tuesday,
    /// Middle of the week
    Wednesday,
    /// Between Wednesday and Friday
    Thursday,
    /// Almost the weekend
    Friday,
    /// First day of the weekend
    Saturday,
    /// Last day of the week
    Sunday,
}

impl DayOfWeek {
    /// Returns the UK English word for the day of the week
    pub fn day_str(&self) -> &'static str {
        match self {
            DayOfWeek::Monday => "Monday",
            DayOfWeek::Tuesday => "Tuesday",
            DayOfWeek::Wednesday => "Wednesday",
            DayOfWeek::Thursday => "Thursday",
            DayOfWeek::Friday => "Friday",
            DayOfWeek::Saturday => "Saturday",
            DayOfWeek::Sunday => "Sunday",
        }
    }
}

impl Timestamp {
    /// Returns the day of the week for the given timestamp.
    pub fn day_of_week(&self) -> DayOfWeek {
        let zellers_month = ((i32::from(self.month) + 9) % 12) + 1;
        let k = i32::from(self.days);
        let year = if zellers_month >= 11 {
            i32::from(self.year_from_1970) + 1969
        } else {
            i32::from(self.year_from_1970) + 1970
        };
        let d = year % 100;
        let c = year / 100;
        let f = k + (((13 * zellers_month) - 1) / 5) + d + (d / 4) + (c / 4) - (2 * c);
        let day_of_week = f % 7;
        match day_of_week {
            0 => DayOfWeek::Sunday,
            1 => DayOfWeek::Monday,
            2 => DayOfWeek::Tuesday,
            3 => DayOfWeek::Wednesday,
            4 => DayOfWeek::Thursday,
            5 => DayOfWeek::Friday,
            _ => DayOfWeek::Saturday,
        }
    }

    /// Move this timestamp forward by a number of days and seconds.
    pub fn increment(&mut self, days: u32, seconds: u32) {
        let new_seconds = seconds + u32::from(self.seconds);
        self.seconds = (new_seconds % 60) as u8;
        let new_minutes = (new_seconds / 60) + u32::from(self.minutes);
        self.minutes = (new_minutes % 60) as u8;
        let new_hours = (new_minutes / 60) + u32::from(self.hours);
        self.hours = (new_hours % 24) as u8;
        let mut new_days = (new_hours / 24) + u32::from(self.days) + days;
        while new_days > u32::from(self.days_in_month()) {
            new_days -= u32::from(self.days_in_month());
            self.month += 1;
            if self.month > 12 {
                self.month = 1;
                self.year_from_1970 += 1;
            }
        }
        self.days = new_days as u8;
    }

    /// Returns true if this is a leap year, false otherwise.
    pub fn is_leap_year(&self) -> bool {
        let year = u32::from(self.year_from_1970) + 1970;
        (year == 2000) || (((year % 4) == 0) && ((year % 100) != 0))
    }

    /// Returns the number of days in the current month
    pub fn days_in_month(&self) -> u8 {
        match self.month {
            1 => 31,
            2 if self.is_leap_year() => 29,
            2 => 28,
            3 => 31,
            4 => 30,
            5 => 31,
            6 => 30,
            7 => 31,
            8 => 31,
            9 => 30,
            10 => 31,
            11 => 30,
            12 => 31,
            _ => panic!("Bad timestamp {:?}", self),
        }
    }

    /// Returns the current month as a UK English string (e.g. "August").
    pub fn month_str(&self) -> &'static str {
        match self.month {
            1 => "January",
            2 => "February",
            3 => "March",
            4 => "April",
            5 => "May",
            6 => "June",
            7 => "July",
            8 => "August",
            9 => "September",
            10 => "October",
            11 => "November",
            12 => "December",
            _ => "Unknown",
        }
    }
}

impl core::fmt::Display for Timestamp {
    fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
        write!(
            f,
            "{year:04}-{month:02}-{days:02}T{hours:02}:{minutes:02}:{seconds:02}",
            year = u16::from(self.year_from_1970) + 1970u16,
            month = self.month,
            days = self.days,
            hours = self.hours,
            minutes = self.minutes,
            seconds = self.seconds,
        )
    }
}

/// Describes a file as it exists on disk.
#[repr(C)]
#[derive(Debug, Clone)]
pub struct DirEntry {
    /// The file of the file this entry represents
    pub file_type: FileType,
    /// The name of the file (not including its full path)
    pub name: [u8; 11],
    /// The sie of the file in bytes
    pub size: u32,
    /// When this file was last modified
    pub mtime: Timestamp,
    /// When this file was created
    pub ctime: Timestamp,
    /// The various mode bits set on this file
    pub mode: FileMode,
}

/// A bitfield indicating if a file is:
///
/// * read-only
/// * a volume label
/// * a system file
/// * in need of archiving
#[repr(C)]
#[derive(Debug, Clone, Copy)]
pub struct FileMode(u8);

/// Is the read-only bit set in this FileMode bit-field?
#[no_mangle]
pub extern "C" fn monotron_filemode_is_readonly(flags: FileMode) -> bool {
    (flags.0 & FileMode::READ_ONLY) != 0
}

/// Is the volume label bit set in this FileMode bit-field?
#[no_mangle]
pub extern "C" fn monotron_filemode_is_volume(flags: FileMode) -> bool {
    (flags.0 & FileMode::VOLUME) != 0
}

/// Is the system bit set in this FileMode bit-field?
#[no_mangle]
pub extern "C" fn monotron_filemode_is_system(flags: FileMode) -> bool {
    (flags.0 & FileMode::SYSTEM) != 0
}

/// Is the archive bit set in this FileMode bit-field?
#[no_mangle]
pub extern "C" fn monotron_filemode_is_archive(flags: FileMode) -> bool {
    (flags.0 & FileMode::ARCHIVE) != 0
}

impl FileMode {
    const READ_ONLY: u8 = 1;
    const VOLUME: u8 = 2;
    const SYSTEM: u8 = 4;
    const ARCHIVE: u8 = 8;
}

/// Represents how far to move the current read/write pointer through a file.
/// You can specify the position as relative to the start of the file,
/// relative to the end of the file, or relative to the current pointer
/// position.
#[repr(C)]
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Offset {
    /// Set the pointer to this many bytes from the start of the file
    FromStart(u32),
    /// Set the pointer to this many bytes from the current position (+ve is forwards, -ve is backwards)
    FromCurrent(i32),
    /// Set the pointer to this many bytes back from the end of the file
    FromEnd(u32),
}

/// The ways in which we can open a file.
///
/// TODO: Replace all these booleans with a u8 flag-set
#[repr(C)]
pub enum OpenMode {
    /// Open file in read-only mode. No writes allowed. One file can be opened in read-only mode multiple times.
    ReadOnly {
        /// Set to true if read/write requests on this handle should be non-blocking
        non_blocking: bool,
    },
    /// Open a file for writing, but not reading.
    WriteOnly {
        /// If true, the write pointer will default to the end of the file
        append: bool,
        /// If true, the file will be created if it doesn't exist. If false, the file must exist. See also the `exclusive` flag.
        create: bool,
        /// If true AND the create flag is true, the open will fail if the file already exists.
        exclusive: bool,
        /// If true, the file contents will be deleted on open, giving a zero byte file.
        truncate: bool,
        /// Set to true if read/write requests on this handle should be non-blocking
        non_blocking: bool,
    },
    /// Open a file for reading and writing.
    ReadWrite {
        /// If true, the write pointer will default to the end of the file
        append: bool,
        /// If true, the file will be created if it doesn't exist. If false, the file must exist. See also the `exclusive` flag.
        create: bool,
        /// If true AND the create flag is true, the open will fail if the file already exists.
        exclusive: bool,
        /// If true, the file contents will be deleted on open, giving a zero byte file.
        truncate: bool,
        /// Set to true if read/write requests on this handle should be non-blocking
        non_blocking: bool,
    },
}

/// Create a new Read Only open mode object, for passing to the `open` syscall.
#[no_mangle]
pub extern "C" fn monotron_openmode_readonly(non_blocking: bool) -> OpenMode {
    OpenMode::ReadOnly { non_blocking }
}

/// Create a new Write Only open mode object, for passing to the `open` syscall.
#[no_mangle]
pub extern "C" fn monotron_openmode_writeonly(
    append: bool,
    create: bool,
    exclusive: bool,
    truncate: bool,
    non_blocking: bool,
) -> OpenMode {
    OpenMode::WriteOnly {
        append,
        create,
        exclusive,
        truncate,
        non_blocking,
    }
}

/// Create a new Read Write open mode object, for passing to the `open` syscall.
#[no_mangle]
pub extern "C" fn monotron_openmode_readwrite(
    append: bool,
    create: bool,
    exclusive: bool,
    truncate: bool,
    non_blocking: bool,
) -> OpenMode {
    OpenMode::ReadWrite {
        append,
        create,
        exclusive,
        truncate,
        non_blocking,
    }
}

/// Standard Output
pub static STDOUT: Handle = Handle(0);

/// Standard Error
pub static STDERR: Handle = Handle(1);

/// Standard Input
pub static STDIN: Handle = Handle(2);

/// This structure contains all the function pointers the application can use
/// to access OS functions.
#[repr(C)]
pub struct Api {
    /// Old function for writing a single 8-bit character to the screen.
    pub putchar: extern "C" fn(ch: u8) -> i32,

    /// Old function for writing a null-terminated 8-bit string to the screen.
    pub puts: extern "C" fn(string: *const u8) -> i32,

    /// Old function for reading one byte from stdin, blocking.
    pub readc: extern "C" fn() -> i32,

    /// Old function for checking if readc() would block.
    pub kbhit: extern "C" fn() -> i32,

    /// Old function for moving the cursor on screen. To be replaced with ANSI
    /// escape codes.
    pub move_cursor: extern "C" fn(row: u8, col: u8),

    /// Old function for playing a note.
    pub play: extern "C" fn(frequency: u32, channel: u8, volume: u8, waveform: u8) -> i32,

    /// Old function for changing the on-screen font.
    pub change_font: extern "C" fn(font_id: u32, font_data: *const u8),

    /// Old function for reading the Joystick status.
    pub get_joystick: extern "C" fn() -> u8,

    /// Old function for turning the cursor on/off.
    pub set_cursor_visible: extern "C" fn(enabled: u8),

    /// Old function for reading the contents of the screen.
    pub read_char_at: extern "C" fn(row: u8, col: u8) -> u16,

    /// Wait for next vertical blanking interval.
    pub wfvbi: extern "C" fn(),

    /// Open/create a device/file. Returns a file handle, or an error.
    pub open: extern "C" fn(filename: BorrowedString, mode: OpenMode) -> HandleResult,

    /// Close a previously opened handle.
    pub close: extern "C" fn(handle: Handle) -> EmptyResult,

    /// Read from a file handle into the given buffer. Returns an error, or
    /// the number of bytes read (which may be less than `buffer_len`).
    pub read: extern "C" fn(handle: Handle, buffer: *mut u8, buffer_len: usize) -> SizeResult,

    /// Write the contents of the given buffer to a file handle. Returns an
    /// error, or the number of bytes written (which may be less than
    /// `buffer_len`).
    pub write: extern "C" fn(handle: Handle, buffer: *const u8, buffer_len: usize) -> SizeResult,

    /// Write to the handle and the read from the handle. Useful when doing an
    /// I2C read of a specific address. It is an error if the complete
    /// `out_buffer` could not be written.
    pub write_then_read: extern "C" fn(
        handle: Handle,
        out_buffer: *const u8,
        out_buffer_len: usize,
        in_buffer: *mut u8,
        in_buffer_len: usize,
    ) -> SizeResult,

    /// Move the read/write pointer in a file.
    pub seek: extern "C" fn(handle: Handle, offset: Offset) -> EmptyResult,

    /// Open a directory. Returns a file handle, or an error.
    pub opendir: extern "C" fn(filename: BorrowedString) -> HandleResult,

    /// Read directory entry into given buffer.
    pub readdir: extern "C" fn(handle: Handle, dir_entry: &mut DirEntry) -> EmptyResult,

    /// Get information about a file by path
    pub stat: extern "C" fn(filename: BorrowedString, stat_entry: &mut DirEntry) -> EmptyResult,

    /// Get the current time
    pub gettime: extern "C" fn() -> Timestamp,

    /// Old function for writing a UTF-8 string to the screen.
    pub puts_utf8: extern "C" fn(string: *const u8, length: usize),

    /// Maps an actual line on the screen to be drawn as if it was somewhere else on the screen.
    ///
    /// So if you ran this, the image would look completely normal:
    ///
    /// ```rust
    /// for x in 0..576 {
    ///     map_line(x, x);
    /// }
    /// ```
    ///
    /// But if you did this, the screen would be upside down.
    ///
    /// ```rust
    /// for x in 0..576 {
    ///     map_line(x, 576 - x);
    /// }
    /// ```
    ///
    /// And if you did this, the top 32 scanlines on the screen would repeat
    /// all the way down.
    ///
    /// ```rust
    /// for x in 0..576 {
    ///     map_line(x, x % 32);
    /// }
    /// ```
    pub map_line: extern "C" fn(actual_scanline: u16, drawn_scanline: u16),
    /// Get the current cursor position
    pub get_cursor: extern "C" fn(row: *mut u8, col: *mut u8),
}

#[cfg(test)]
mod test {
    use super::*;

    #[test]
    fn day_of_week() {
        let samples = [
            (
                Timestamp {
                    year_from_1970: 49,
                    month: 7,
                    day: 16,
                    hours: 0,
                    minutes: 0,
                    seconds: 0,
                },
                DayOfWeek::Tuesday,
            ),
            (
                Timestamp {
                    year_from_1970: 49,
                    month: 7,
                    day: 17,
                    hours: 0,
                    minutes: 0,
                    seconds: 0,
                },
                DayOfWeek::Wednesday,
            ),
            (
                Timestamp {
                    year_from_1970: 49,
                    month: 7,
                    day: 18,
                    hours: 0,
                    minutes: 0,
                    seconds: 0,
                },
                DayOfWeek::Thursday,
            ),
        ];
        for (timestamp, day) in samples.iter() {
            assert_eq!(timestamp.day_of_week(), *day);
        }
    }
}