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
use super::consts::*;
use super::slab::*;
use super::slab_def::*;

use super::slab_kind::*;

#[derive(Debug)]
pub struct Row {
    /// Slabs containing the actual data
    pub slabs: [Slab; WIDTH_MAX],
}

impl Row {
    /// Create a new row, with a given slab def.
    ///
    /// # Examples
    ///
    /// ```
    /// use babalcore::*;
    ///
    /// let _row = Row::new(SlabDef::Floor);
    /// ```
    pub fn new(def: SlabDef) -> Row {
        Row {
            slabs: [Slab::new(def); WIDTH_MAX],
        }
    }

    /// Get a row content, at a given time.
    ///
    /// # Examples
    ///
    /// ```
    /// use babalcore::*;
    ///
    /// let row = Row::new(SlabDef::Floor);
    /// assert_eq!(SlabKind::Floor, row.slab_kind(5, 123));
    /// ```
    pub fn slab_kind(&self, col: isize, now_msec: i64) -> SlabKind {
        if col < 0 || col >= WIDTH_MAX as isize {
            return SlabKind::Void;
        }
        self.slabs[col as usize].slab_kind(now_msec)
    }

    /// Set a row content.
    ///
    /// # Examples
    ///
    /// ```
    /// use babalcore::*;
    ///
    /// let mut row = Row::default();
    /// assert_eq!(SlabKind::Void, row.slab_kind(3, 0));
    /// row.set(3, SlabDef::Floor);
    /// assert_eq!(SlabKind::Floor, row.slab_kind(3, 0));
    /// assert_eq!(SlabKind::Void, row.slab_kind(2, 0));
    /// ```
    pub fn set(&mut self, col: isize, def: SlabDef) {
        if col < 0 || col >= WIDTH_MAX as isize {
            return;
        }
        self.slabs[col as usize].set(def)
    }

    pub fn get(&self, col: isize) -> SlabDef {
        if col < 0 || col >= WIDTH_MAX as isize {
            SlabDef::Void
        } else {
            self.slabs[col as usize].get()
        }
    }
}

impl std::fmt::Display for Row {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let str_list: Vec<String> = self
            .slabs
            .iter()
            .map(|x| format!("{}", x).to_string())
            .collect();
        write!(f, "{}", str_list.join(""))
    }
}

impl std::default::Default for Row {
    fn default() -> Self {
        Row {
            slabs: [Slab::new(SlabDef::Void); WIDTH_MAX],
        }
    }
}

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

    #[test]
    fn test_fmt() {
        assert_eq!(
            "                                ",
            format!("{}", Row::new(SlabDef::Void))
        );
        assert_eq!(
            "################################",
            format!("{}", Row::new(SlabDef::Floor))
        );
    }
}