<commit_before>/* Copyright (C)  2016 nokaa <nokaa@cock.li>
 * This software is licensed under the terms of the
 * GNU Affero General Public License. You should have
 * received a copy of this license with this software.
 * The license may also be found at https://gnu.org/licenses/agpl.txt
 */

mod command;
mod cursor;
mod insert;

use rustty::{self, Event, Color};
use editor;

/// `Term` represents our client application. This allows
/// us to work with the filesystem and the UI.
pub struct Term<'a> {
    /// Represents the location of the cursor in our UI
    cursor: cursor::Cursor,
    /// Contains file information; allows us to work with
    /// the filesystem
    editor: &'a mut editor::Editor<'a>,
    /// This is the UI itself
    term: rustty::Terminal,
    /// Represents the running status
    quit: bool,
    /// Represents the topmost line in our UI
    line: usize,
    /// Represents the total number of lines in the currently
    /// open file
    total_lines: usize,
}

impl<'a> Term<'a> {
    pub fn new(editor: &'a mut editor::Editor<'a>) -> Term<'a> {
        Term {
            cursor: cursor::Cursor::new(Color::Red),
            editor: editor,
            term: rustty::Terminal::new().unwrap(),
            quit: false,
            line: 0,
            total_lines: 0,
        }
    }

    /// Launches the terminal.
    pub fn run(&mut self) {
        self.editor.read_file(self.term.cols());
        let lines = self.editor.contents.len() as isize;
        self.set_total_lines(lines);

        self.term[self.cursor.current_pos()].set_bg(self.cursor.color);
        let current_line = self.current_line();
        self.print_file(current_line);
        self.prompt();
        self.term.swap_buffers().unwrap();

        while !self.quit {
            let evt = self.term.get_event(100).unwrap();
            if let Some(Event::Key(ch)) = evt {
                if self.editor.command_mode() {
                    command::handle(self, ch);
                } else {
                    insert::handle(self, ch);
                }

                if self.cursor.pos.x > self.term.cols() - 1 {
                    self.term[self.cursor.last_pos()].set_bg(Color::Default);
                    self.cursor.save_pos();
                    self.cursor.pos.x = 0;
                    self.cursor.pos.y += 1;
                }
                if self.cursor.pos.y >= self.term.rows() - 1 {
                    self.term[self.cursor.last_pos()].set_bg(Color::Default);
                    self.cursor.save_pos();
                    self.cursor.pos.x = 0;
                    self.cursor.pos.y = 0;
                }

                self.term[self.cursor.last_pos()].set_bg(Color::Default);
                self.term[self.cursor.current_pos()].set_bg(self.cursor.color);
                self.term.swap_buffers().unwrap();
            }
        }
    }

    /// Prints our prompt to the UI.
    pub fn prompt(&mut self) {
        let w = self.term.cols();
        let h = self.term.rows();

        for i in 0..w {
            self.term[(i, h - 2)].set_bg(Color::Red);
        }

        for (i, c) in self.editor.filename().chars().enumerate() {
            self.term[(i, h - 2)].set_ch(c);
        }
    }

    /// Prints our editor's contents to the UI.
    fn print_file(&mut self, start: usize) {
        let w = self.term.cols();
        let mut i = 0;
        let mut j = 0;
        for line in &self.editor.contents {
            if i < start {
                i += 1;
                continue;
            }

            for &b in line {
                if b == b'\n' {
                    continue;
                }
                self.term[(j, i - start)].set_ch(b as char);
                j += 1;
            }
            while j < w {
                self.term[(j, i - start)].set_ch(' ');
                j += 1;
            }

            i += 1;
            j = 0;
            if i - start == self.term.rows() - 2 {
                break;
            }
        }
    }

    pub fn move_cursor(&mut self, direction: cursor::Direction) {
        match direction {
            cursor::Direction::Up => {
                if self.cursor.pos.y != 0 {
                    self.cursor.save_pos();
                    self.cursor.pos.y -= 1;
                } else if self.current_line() != 0 {
                    let current_line = self.current_line();
                    self.set_current_line(current_line - 1);
                    self.redraw_file();
                }
            }
            cursor::Direction::Down => {
                if self.total_lines() <= self.term.rows() - 3 {
                    if self.cursor.pos.y != self.term.rows() - 3 &&
                       self.cursor.pos.y < self.total_lines() - 1
                    {
                        self.cursor.save_pos();
                        self.cursor.pos.y += 1;
                    }
                } else {
                    if self.cursor.pos.y != self.term.rows() - 3 {
                        self.cursor.save_pos();
                        self.cursor.pos.y += 1;
                    } else if self.cursor.pos.y + self.current_line() <
                              self.total_lines() - 1
                    {
                        let current_line = self.current_line();
                        self.set_current_line(current_line + 1);
                        self.redraw_file();
                    }
                }
            }
            cursor::Direction::Left => {
                if self.cursor.pos.x != 0 {
                    self.cursor.save_pos();
                    self.cursor.pos.x -= 1;
                }
            }
            cursor::Direction::Right => {
                let curr = self.cursor.pos.y + self.current_line();
                let len = self.editor.contents[curr].len() - 1;
                if self.editor.contents[curr][len] == b'\n' {
                    if self.cursor.pos.x != len - 1 {
                        self.cursor.save_pos();
                        self.cursor.pos.x += 1;
                    }
                } else if self.cursor.pos.x != len {
                    self.cursor.save_pos();
                    self.cursor.pos.x += 1;
                }
            }
        }
    }

    /// Changes the value of the `quit` attribute to `true`.
    pub fn quit(&mut self) {
        self.quit = true;
    }

    /// Returns the total lines in our file
    pub fn total_lines(&self) -> usize {
        self.total_lines
    }

    /// Allows us to modify the total number of lines
    /// in our file, e.g. if a new line is added.
    pub fn set_total_lines(&mut self, change: isize) {
        let new = self.total_lines as isize + change;
        self.total_lines = new as usize;
    }

    /// Gives the current line at the top of our UI
    pub fn current_line(&self) -> usize {
        self.line
    }

    /// Allows us to change what the topmost line in the UI is
    pub fn set_current_line(&mut self, line: usize) {
        self.line = line;
    }

    /// This function redraws the portion of our UI displaying
    /// file contents. E.g. this is called when the current line
    /// changes.
    pub fn redraw_file(&mut self) {
        let current_line = self.current_line();
        self.print_file(current_line);
    }
}
<commit_msg>Fix up/down movement not adhering to line length limit<commit_after>/* Copyright (C)  2016 nokaa <nokaa@cock.li>
 * This software is licensed under the terms of the
 * GNU Affero General Public License. You should have
 * received a copy of this license with this software.
 * The license may also be found at https://gnu.org/licenses/agpl.txt
 */

mod command;
mod cursor;
mod insert;

use rustty::{self, Event, Color};
use editor;

/// `Term` represents our client application. This allows
/// us to work with the filesystem and the UI.
pub struct Term<'a> {
    /// Represents the location of the cursor in our UI
    cursor: cursor::Cursor,
    /// Contains file information; allows us to work with
    /// the filesystem
    editor: &'a mut editor::Editor<'a>,
    /// This is the UI itself
    term: rustty::Terminal,
    /// Represents the running status
    quit: bool,
    /// Represents the topmost line in our UI
    line: usize,
    /// Represents the total number of lines in the currently
    /// open file
    total_lines: usize,
}

impl<'a> Term<'a> {
    pub fn new(editor: &'a mut editor::Editor<'a>) -> Term<'a> {
        Term {
            cursor: cursor::Cursor::new(Color::Red),
            editor: editor,
            term: rustty::Terminal::new().unwrap(),
            quit: false,
            line: 0,
            total_lines: 0,
        }
    }

    /// Launches the terminal.
    pub fn run(&mut self) {
        self.editor.read_file(self.term.cols());
        let lines = self.editor.contents.len() as isize;
        self.set_total_lines(lines);

        self.term[self.cursor.current_pos()].set_bg(self.cursor.color);
        let current_line = self.current_line();
        self.print_file(current_line);
        self.prompt();
        self.term.swap_buffers().unwrap();

        while !self.quit {
            let evt = self.term.get_event(100).unwrap();
            if let Some(Event::Key(ch)) = evt {
                if self.editor.command_mode() {
                    command::handle(self, ch);
                } else {
                    insert::handle(self, ch);
                }

                if self.cursor.pos.x > self.term.cols() - 1 {
                    self.term[self.cursor.last_pos()].set_bg(Color::Default);
                    self.cursor.save_pos();
                    self.cursor.pos.x = 0;
                    self.cursor.pos.y += 1;
                }
                if self.cursor.pos.y >= self.term.rows() - 1 {
                    self.term[self.cursor.last_pos()].set_bg(Color::Default);
                    self.cursor.save_pos();
                    self.cursor.pos.x = 0;
                    self.cursor.pos.y = 0;
                }

                self.term[self.cursor.last_pos()].set_bg(Color::Default);
                self.term[self.cursor.current_pos()].set_bg(self.cursor.color);
                self.term.swap_buffers().unwrap();
            }
        }
    }

    /// Prints our prompt to the UI.
    pub fn prompt(&mut self) {
        let w = self.term.cols();
        let h = self.term.rows();

        for i in 0..w {
            self.term[(i, h - 2)].set_bg(Color::Red);
        }

        for (i, c) in self.editor.filename().chars().enumerate() {
            self.term[(i, h - 2)].set_ch(c);
        }
    }

    /// Prints our editor's contents to the UI.
    fn print_file(&mut self, start: usize) {
        let w = self.term.cols();
        let mut i = 0;
        let mut j = 0;
        for line in &self.editor.contents {
            if i < start {
                i += 1;
                continue;
            }

            for &b in line {
                if b == b'\n' {
                    continue;
                }
                self.term[(j, i - start)].set_ch(b as char);
                j += 1;
            }
            while j < w {
                self.term[(j, i - start)].set_ch(' ');
                j += 1;
            }

            i += 1;
            j = 0;
            if i - start == self.term.rows() - 2 {
                break;
            }
        }
    }

    pub fn move_cursor(&mut self, direction: cursor::Direction) {
        match direction {
            cursor::Direction::Up => {
                if self.cursor.pos.y != 0 {
                    self.cursor.save_pos();
                    self.cursor.pos.y -= 1;
                } else if self.current_line() != 0 {
                    let current_line = self.current_line();
                    self.set_current_line(current_line - 1);
                    self.redraw_file();
                }
                let curr = self.cursor.pos.y + self.current_line();
                let len = self.editor.contents[curr].len() - 1;
                if self.cursor.pos.x > len {
                    if self.editor.contents[curr][len] == b'\n' && len > 0{
                        self.cursor.pos.x = len - 1;
                    } else {
                        self.cursor.pos.x = len;
                    }
                }
            }
            cursor::Direction::Down => {
                if self.total_lines() <= self.term.rows() - 3 {
                    if self.cursor.pos.y != self.term.rows() - 3 &&
                       self.cursor.pos.y < self.total_lines() - 1
                    {
                        self.cursor.save_pos();
                        self.cursor.pos.y += 1;
                    }
                } else {
                    if self.cursor.pos.y != self.term.rows() - 3 {
                        self.cursor.save_pos();
                        self.cursor.pos.y += 1;
                    } else if self.cursor.pos.y + self.current_line() <
                              self.total_lines() - 1
                    {
                        let current_line = self.current_line();
                        self.set_current_line(current_line + 1);
                        self.redraw_file();
                    }
                }
                let curr = self.cursor.pos.y + self.current_line();
                let len = self.editor.contents[curr].len() - 1;
                if self.cursor.pos.x > len {
                    if self.editor.contents[curr][len] == b'\n' && len > 0{
                        self.cursor.pos.x = len - 1;
                    } else {
                        self.cursor.pos.x = len;
                    }
                }
            }
            cursor::Direction::Left => {
                if self.cursor.pos.x != 0 {
                    self.cursor.save_pos();
                    self.cursor.pos.x -= 1;
                }
            }
            cursor::Direction::Right => {
                let curr = self.cursor.pos.y + self.current_line();
                let len = self.editor.contents[curr].len() - 1;
                if self.editor.contents[curr][len] == b'\n' {
                    if self.cursor.pos.x != len - 1 {
                        self.cursor.save_pos();
                        self.cursor.pos.x += 1;
                    }
                } else if self.cursor.pos.x != len {
                    self.cursor.save_pos();
                    self.cursor.pos.x += 1;
                }
            }
        }
    }

    /// Changes the value of the `quit` attribute to `true`.
    pub fn quit(&mut self) {
        self.quit = true;
    }

    /// Returns the total lines in our file
    pub fn total_lines(&self) -> usize {
        self.total_lines
    }

    /// Allows us to modify the total number of lines
    /// in our file, e.g. if a new line is added.
    pub fn set_total_lines(&mut self, change: isize) {
        let new = self.total_lines as isize + change;
        self.total_lines = new as usize;
    }

    /// Gives the current line at the top of our UI
    pub fn current_line(&self) -> usize {
        self.line
    }

    /// Allows us to change what the topmost line in the UI is
    pub fn set_current_line(&mut self, line: usize) {
        self.line = line;
    }

    /// This function redraws the portion of our UI displaying
    /// file contents. E.g. this is called when the current line
    /// changes.
    pub fn redraw_file(&mut self) {
        let current_line = self.current_line();
        self.print_file(current_line);
    }
}
<|endoftext|>


<commit_before>use cargo_metadata::{Message::CompilerArtifact, MetadataCommand};
use std::env;
use std::ffi::OsStr;
use std::mem;
use std::path::PathBuf;
use std::process::Command;

pub struct BuildInfo {
    cargo_target_dir: PathBuf,
}

impl BuildInfo {
    pub fn new() -> Self {
        let data = MetadataCommand::new().exec().unwrap();
        Self {
            cargo_target_dir: data.target_directory,
        }
    }

    pub fn host_lib(&self) -> PathBuf {
        if let Some(path) = option_env!("HOST_LIBS") {
            PathBuf::from(path)
        } else {
            self.cargo_target_dir.join(env!("PROFILE"))
        }
    }

    pub fn target_lib(&self) -> PathBuf {
        if let Some(path) = option_env!("TARGET_LIBS") {
            path.into()
        } else {
            let mut dir = self.cargo_target_dir.clone();
            if let Some(target) = env::var_os("CARGO_BUILD_TARGET") {
                dir.push(target);
            }
            dir.push(env!("PROFILE"));
            dir
        }
    }

    pub fn clippy_driver_path(&self) -> PathBuf {
        if let Some(path) = option_env!("CLIPPY_DRIVER_PATH") {
            PathBuf::from(path)
        } else {
            self.target_lib().join("clippy-driver")
        }
    }

    // When we'll want to use `extern crate ..` for a dependency that is used
    // both by the crate and the compiler itself, we can't simply pass -L flags
    // as we'll get a duplicate matching versions. Instead, disambiguate with
    // `--extern dep=path`.
    // See https://github.com/rust-lang/rust-clippy/issues/4015.
    pub fn third_party_crates() -> Vec<(&'static str, PathBuf)> {
        const THIRD_PARTY_CRATES: [&str; 3] = ["serde", "regex", "clippy_lints"];
        let cargo = env::var_os("CARGO");
        let cargo = cargo.as_deref().unwrap_or_else(|| OsStr::new("cargo"));
        let output = Command::new(cargo)
            .arg("build")
            .arg("--test=compile-test")
            .arg("--message-format=json")
            .output()
            .unwrap();

        let mut crates = Vec::with_capacity(THIRD_PARTY_CRATES.len());
        for message in cargo_metadata::parse_messages(output.stdout.as_slice()) {
            if let CompilerArtifact(mut artifact) = message.unwrap() {
                if let Some(&krate) = THIRD_PARTY_CRATES.iter().find(|&&krate| krate == artifact.target.name) {
                    crates.push((krate, mem::take(&mut artifact.filenames[0])));
                }
            }
        }
        crates
    }
}
<commit_msg>Add `serde_derive` to the need-to-be-disambiguated-crates list<commit_after>use cargo_metadata::{Message::CompilerArtifact, MetadataCommand};
use std::env;
use std::ffi::OsStr;
use std::mem;
use std::path::PathBuf;
use std::process::Command;

pub struct BuildInfo {
    cargo_target_dir: PathBuf,
}

impl BuildInfo {
    pub fn new() -> Self {
        let data = MetadataCommand::new().exec().unwrap();
        Self {
            cargo_target_dir: data.target_directory,
        }
    }

    pub fn host_lib(&self) -> PathBuf {
        if let Some(path) = option_env!("HOST_LIBS") {
            PathBuf::from(path)
        } else {
            self.cargo_target_dir.join(env!("PROFILE"))
        }
    }

    pub fn target_lib(&self) -> PathBuf {
        if let Some(path) = option_env!("TARGET_LIBS") {
            path.into()
        } else {
            let mut dir = self.cargo_target_dir.clone();
            if let Some(target) = env::var_os("CARGO_BUILD_TARGET") {
                dir.push(target);
            }
            dir.push(env!("PROFILE"));
            dir
        }
    }

    pub fn clippy_driver_path(&self) -> PathBuf {
        if let Some(path) = option_env!("CLIPPY_DRIVER_PATH") {
            PathBuf::from(path)
        } else {
            self.target_lib().join("clippy-driver")
        }
    }

    // When we'll want to use `extern crate ..` for a dependency that is used
    // both by the crate and the compiler itself, we can't simply pass -L flags
    // as we'll get a duplicate matching versions. Instead, disambiguate with
    // `--extern dep=path`.
    // See https://github.com/rust-lang/rust-clippy/issues/4015.
    pub fn third_party_crates() -> Vec<(&'static str, PathBuf)> {
        const THIRD_PARTY_CRATES: [&str; 4] = ["serde", "serde_derive", "regex", "clippy_lints"];
        let cargo = env::var_os("CARGO");
        let cargo = cargo.as_deref().unwrap_or_else(|| OsStr::new("cargo"));
        let output = Command::new(cargo)
            .arg("build")
            .arg("--test=compile-test")
            .arg("--message-format=json")
            .output()
            .unwrap();

        let mut crates = Vec::with_capacity(THIRD_PARTY_CRATES.len());
        for message in cargo_metadata::parse_messages(output.stdout.as_slice()) {
            if let CompilerArtifact(mut artifact) = message.unwrap() {
                if let Some(&krate) = THIRD_PARTY_CRATES.iter().find(|&&krate| krate == artifact.target.name) {
                    crates.push((krate, mem::take(&mut artifact.filenames[0])));
                }
            }
        }
        crates
    }
}
<|endoftext|>


<commit_before>//! Modules specific to the TI LM4F120H5QR Cortex-M4F microcontroller

// ****************************************************************************
//
// Imports
//
// ****************************************************************************

pub mod gpio;
pub mod pll;
pub mod registers;
pub mod uart;
pub mod timer;
pub mod systick;

extern "C" {
    fn _stack_top();
}

use board::launchpad as board;

pub use cpu::cortex_m4f::fpu as fpu;

// ****************************************************************************
//
// Public Types
//
// ****************************************************************************

// None

// ****************************************************************************
//
// Private Types
//
// ****************************************************************************

// None

// ****************************************************************************
//
// Public Data
//
// ****************************************************************************

#[link_section=".nvic_table"]
#[no_mangle]
pub static ISR_VECTORS: [Option<unsafe extern "C" fn()>; 155] = [// Stack pointer
                                                                 Some(_stack_top),
                                                                 // Reset
                                                                 Some(::common::startup::startup),
                                                                 // NMI
                                                                 Some(isr_nmi),
                                                                 // Hard Fault
                                                                 Some(isr_hardfault),
                                                                 // CM3 Memory Management Fault
                                                                 Some(isr_mmfault),
                                                                 // CM3 Bus Fault
                                                                 Some(isr_busfault),
                                                                 // CM3 Usage Fault
                                                                 Some(isr_usagefault),
                                                                 // Reserved - Used as NXP Checksum
                                                                 None,
                                                                 // Reserved
                                                                 None,
                                                                 // Reserved
                                                                 None,
                                                                 // Reserved
                                                                 None,
                                                                 // SVCall
                                                                 Some(isr_svcall),
                                                                 // Reserved for debug
                                                                 Some(isr_debugmon),
                                                                 // Reserved
                                                                 None,
                                                                 // PendSV
                                                                 Some(isr_pendsv),
                                                                 // SysTick
                                                                 Some(isr_systick),
                                                                 // GPIO Port A                      16
                                                                 Some(isr_empty_def),
                                                                 // GPIO Port B                      17
                                                                 Some(isr_empty_def),
                                                                 // GPIO Port C                      18
                                                                 Some(isr_empty_def),
                                                                 // GPIO Port D                      19
                                                                 Some(isr_empty_def),
                                                                 // GPIO Port E                      20
                                                                 Some(isr_empty_def),
                                                                 // UART 0                           21
                                                                 Some(uart::uart0_isr),
                                                                 // UART 1                           22
                                                                 Some(isr_empty_def),
                                                                 // SSI 0                            23
                                                                 Some(isr_empty_def),
                                                                 // I2C 0                            24
                                                                 Some(isr_empty_def),
                                                                 // Reserved                         25
                                                                 None,
                                                                 // Reserved                         26
                                                                 None,
                                                                 // Reserved                         27
                                                                 None,
                                                                 // Reserved                         28
                                                                 None,
                                                                 // Reserved                         29
                                                                 None,
                                                                 // ADC 0 Seq 0                      30
                                                                 Some(isr_empty_def),
                                                                 // ADC 0 Seq 1                      31
                                                                 Some(isr_empty_def),
                                                                 // ADC 0 Seq 2                      32
                                                                 Some(isr_empty_def),
                                                                 // ADC 0 Seq 3                      33
                                                                 Some(isr_empty_def),
                                                                 // WDT 0 and 1                      34
                                                                 Some(isr_empty_def),
                                                                 // 16/32 bit timer 0 A              35
                                                                 Some(isr_empty_def),
                                                                 // 16/32 bit timer 0 B              36
                                                                 Some(isr_empty_def),
                                                                 // 16/32 bit timer 1 A              37
                                                                 Some(isr_empty_def),
                                                                 // 16/32 bit timer 1 B              38
                                                                 Some(isr_empty_def),
                                                                 // 16/32 bit timer 2 A              39
                                                                 Some(isr_empty_def),
                                                                 // 16/32 bit timer 2 B              40
                                                                 Some(isr_empty_def),
                                                                 // Analog comparator 0              41
                                                                 Some(isr_empty_def),
                                                                 // Analog comparator 1              42
                                                                 Some(isr_empty_def),
                                                                 // Reserved                         43
                                                                 None,
                                                                 // System control                   44
                                                                 Some(isr_empty_def),
                                                                 // Flash + EEPROM control           45
                                                                 Some(isr_empty_def),
                                                                 // GPIO Port F                      46
                                                                 Some(isr_empty_def),
                                                                 // Reserved                         47
                                                                 None,
                                                                 // Reserved                         48
                                                                 None,
                                                                 // UART 2                           49
                                                                 Some(isr_empty_def),
                                                                 // SSI 1                            50
                                                                 Some(isr_empty_def),
                                                                 // 16/32 bit timer 3 A              51
                                                                 Some(isr_empty_def),
                                                                 // 16/32 bit timer 3 B              52
                                                                 Some(isr_empty_def),
                                                                 // I2C 1                            53
                                                                 Some(isr_empty_def),
                                                                 // Reserved                         54
                                                                 None,
                                                                 // CAN 0                            55
                                                                 Some(isr_empty_def),
                                                                 // Reserved                         56
                                                                 None,
                                                                 // Reserved                         57
                                                                 None,
                                                                 // Reserved                         58
                                                                 None,
                                                                 // Hibernation module               59
                                                                 Some(isr_empty_def),
                                                                 // USB                              60
                                                                 Some(isr_empty_def),
                                                                 // Reserved                         61
                                                                 None,
                                                                 // UDMA SW                          62
                                                                 Some(isr_empty_def),
                                                                 // UDMA Error                       63
                                                                 Some(isr_empty_def),
                                                                 // ADC 1 Seq 0                      64
                                                                 Some(isr_empty_def),
                                                                 // ADC 1 Seq 1                      65
                                                                 Some(isr_empty_def),
                                                                 // ADC 1 Seq 2                      66
                                                                 Some(isr_empty_def),
                                                                 // ADC 1 Seq 3                      67
                                                                 Some(isr_empty_def),
                                                                 // Reserved                         68
                                                                 None,
                                                                 // Reserved                         69
                                                                 None,
                                                                 // Reserved                         70
                                                                 None,
                                                                 // Reserved                         71
                                                                 None,
                                                                 // Reserved                         72
                                                                 None,
                                                                 // SSI 2                            73
                                                                 Some(isr_empty_def),
                                                                 // SSI 2                            74
                                                                 Some(isr_empty_def),
                                                                 // UART 3                           75
                                                                 Some(isr_empty_def),
                                                                 // UART 4                           76
                                                                 Some(isr_empty_def),
                                                                 // UART 5                           77
                                                                 Some(isr_empty_def),
                                                                 // UART 6                           78
                                                                 Some(isr_empty_def),
                                                                 // UART 7                           79
                                                                 Some(isr_empty_def),
                                                                 // Reserved                         80
                                                                 None,
                                                                 // Reserved                         81
                                                                 None,
                                                                 // Reserved                         82
                                                                 None,
                                                                 // Reserved                         83
                                                                 None,
                                                                 // I2C 2                            84
                                                                 Some(isr_empty_def),
                                                                 // I2C 4                            85
                                                                 Some(isr_empty_def),
                                                                 // 16/32 bit timer 4 A              86
                                                                 Some(isr_empty_def),
                                                                 // 16/32 bit timer 4 B              87
                                                                 Some(isr_empty_def),
                                                                 // Reserved                         88
                                                                 None,
                                                                 // Reserved                         89
                                                                 None,
                                                                 // Reserved                         90
                                                                 None,
                                                                 // Reserved                         91
                                                                 None,
                                                                 // Reserved                         92
                                                                 None,
                                                                 // Reserved                         93
                                                                 None,
                                                                 // Reserved                         94
                                                                 None,
                                                                 // Reserved                         95
                                                                 None,
                                                                 // Reserved                         96
                                                                 None,
                                                                 // Reserved                         97
                                                                 None,
                                                                 // Reserved                         98
                                                                 None,
                                                                 // Reserved                         99
                                                                 None,
                                                                 // Reserved                         100
                                                                 None,
                                                                 // Reserved                         101
                                                                 None,
                                                                 // Reserved                         102
                                                                 None,
                                                                 // Reserved                         103
                                                                 None,
                                                                 // Reserved                         104
                                                                 None,
                                                                 // Reserved                         105
                                                                 None,
                                                                 // Reserved                         106
                                                                 None,
                                                                 // Reserved                         107
                                                                 None,
                                                                 // 16/32 bit timer 5 A              108
                                                                 Some(isr_empty_def),
                                                                 // 16/32 bit timer 5 B              109
                                                                 Some(isr_empty_def),
                                                                 // 32/64 bit timer 0 A              110
                                                                 Some(isr_empty_def),
                                                                 // 32/64 bit timer 0 B              111
                                                                 Some(isr_empty_def),
                                                                 // 32/64 bit timer 1 A              112
                                                                 Some(isr_empty_def),
                                                                 // 32/64 bit timer 1 B              113
                                                                 Some(isr_empty_def),
                                                                 // 32/64 bit timer 2 A              114
                                                                 Some(isr_empty_def),
                                                                 // 32/64 bit timer 2 B              115
                                                                 Some(isr_empty_def),
                                                                 // 32/64 bit timer 3 A              116
                                                                 Some(isr_empty_def),
                                                                 // 32/64 bit timer 3 B              117
                                                                 Some(isr_empty_def),
                                                                 // 32/64 bit timer 4 A              118
                                                                 Some(isr_empty_def),
                                                                 // 32/64 bit timer 4 B              119
                                                                 Some(isr_empty_def),
                                                                 // 32/64 bit timer 5 A              120
                                                                 Some(isr_empty_def),
                                                                 // 32/64 bit timer 5 B              121
                                                                 Some(isr_empty_def),
                                                                 // System Exception                 122
                                                                 Some(isr_empty_def),
                                                                 // Reserved                         123
                                                                 None,
                                                                 // Reserved                         124
                                                                 None,
                                                                 // Reserved                         125
                                                                 None,
                                                                 // Reserved                         126
                                                                 None,
                                                                 // Reserved                         127
                                                                 None,
                                                                 // Reserved                         128
                                                                 None,
                                                                 // Reserved                         129
                                                                 None,
                                                                 // Reserved                         130
                                                                 None,
                                                                 // Reserved                         131
                                                                 None,
                                                                 // Reserved                         132
                                                                 None,
                                                                 // Reserved                         133
                                                                 None,
                                                                 // Reserved                         134
                                                                 None,
                                                                 // Reserved                         135
                                                                 None,
                                                                 // Reserved                         136
                                                                 None,
                                                                 // Reserved                         137
                                                                 None,
                                                                 // Reserved                         138
                                                                 None,
                                                                 // Reserved                         139
                                                                 None,
                                                                 // Reserved                         140
                                                                 None,
                                                                 // Reserved                         141
                                                                 None,
                                                                 // Reserved                         142
                                                                 None,
                                                                 // Reserved                         143
                                                                 None,
                                                                 // Reserved                         144
                                                                 None,
                                                                 // Reserved                         145
                                                                 None,
                                                                 // Reserved                         146
                                                                 None,
                                                                 // Reserved                         147
                                                                 None,
                                                                 // Reserved                         148
                                                                 None,
                                                                 // Reserved                         149
                                                                 None,
                                                                 // Reserved                         150
                                                                 None,
                                                                 // Reserved                         151
                                                                 None,
                                                                 // Reserved                         152
                                                                 None,
                                                                 // Reserved                         153
                                                                 None,
                                                                 // Reserved                         154
                                                                 None];

// ****************************************************************************
//
// Public Functions
//
// ****************************************************************************

/// Busy-waits for the given period.
///
/// Currently this function spins with a empirical number
/// of NOPS per millisecond. It should really use a timer.
///
/// * `ms` - The period to wait, in milliseconds
pub fn delay(ms: i32) {
    for _ in 0..ms * 250 {
        unsafe {
            asm!("NOP");
        }
    }
}

// ****************************************************************************
//
// Private Functions
//
// ****************************************************************************

/// A Non Maskable Interrupt (NMI) can be signalled by a peripheral or
/// triggered by software. This is the highest priority exception other than
/// reset. It is permanently enabled and has a fixed priority of -2. NMIs
/// cannot be:
/// * masked or prevented from activation by any other exception
/// * preempted by any exception other than Reset.
#[no_mangle]
pub unsafe extern "C" fn isr_nmi() {
    // Do nothing
}

/// A HardFault is an exception that occurs because of an error during
/// exception processing, or because an exception cannot be managed by any
/// other exception mechanism. HardFaults have a fixed priority of -1, meaning
/// they have higher priority than any exception with configurable priority.
#[no_mangle]
pub unsafe extern "C" fn isr_hardfault() {

     // Todo see https://community.arm.com/servlet/JiveServlet/previewBody/7835-102-2-12371/Developing%20a%20Generic%20Hard%20Fault%20handler%20for%20ARM.pdf
     // Use ITM to emit serial chars and then bkpt into debugger
     bkpt!();
     board::panic();
}

/// A MemManage fault is an exception that occurs because of a memory
/// protection related fault. The the fixed memory protection constraints
/// determines this fault, for both instruction and data memory transactions.
/// This fault is always used to abort instruction accesses to Execute Never
/// (XN) memory regions.
#[no_mangle]
pub unsafe extern "C" fn isr_mmfault() {
    board::panic();
}

/// A BusFault is an exception that occurs because of a memory related fault
/// for an instruction or data memory transaction. This might be from an error
/// detected on a bus in the memory system.
#[no_mangle]
pub unsafe extern "C" fn isr_busfault() {
    board::panic();
}

/// A UsageFault is an exception that occurs because of a fault related to instruction execution. This includes:
/// * an undefined instruction
/// * an illegal unaligned access
/// * invalid state on instruction execution
/// * an error on exception return.
/// The following can cause a UsageFault when the core is configured to report them:
/// * an unaligned address on word and halfword memory access
/// * division by zero.
#[no_mangle]
pub unsafe extern "C" fn isr_usagefault() {
    board::panic();
}

/// A supervisor call (SVC) is an exception that is triggered by the SVC
/// instruction. In an OS environment, applications can use SVC instructions
/// to access OS kernel functions and device drivers.
#[no_mangle]
pub unsafe extern "C" fn isr_svcall() {
    // Nothing
}

/// Debug monitor interrupt handler.
#[no_mangle]
pub unsafe extern "C" fn isr_debugmon() {
    // Nothing
}

/// PendSV is an interrupt-driven request for system-level service. In an OS
/// environment, use PendSV for context switching when no other exception is
/// active.
#[no_mangle]
pub unsafe extern "C" fn isr_pendsv() {
    // Nothing
}

/// A SysTick exception is an exception the system timer generates when it
/// reaches zero. Software can also generate a SysTick exception. In an OS
/// environment, the processor can use this exception as system tick.
#[no_mangle]
pub unsafe extern "C" fn isr_systick() {
    systick::isr();
}

/// A place-holder ISR used when we have nothing better to use.
#[no_mangle]
pub unsafe extern "C" fn isr_empty_def() {
    board::panic();
}

// ****************************************************************************
//
// End Of File
//
// ****************************************************************************
<commit_msg>Moving towards one board per crate. Set target automatically. Rename crate from primer to launchpad.<commit_after>//! Modules specific to the TI LM4F120H5QR Cortex-M4F microcontroller

// ****************************************************************************
//
// Imports
//
// ****************************************************************************

pub mod gpio;
pub mod pll;
pub mod registers;
pub mod uart;
pub mod timer;
pub mod systick;

extern "C" {
    fn _stack_top();
}

use board;

pub use cpu::cortex_m4f::fpu as fpu;

// ****************************************************************************
//
// Public Types
//
// ****************************************************************************

// None

// ****************************************************************************
//
// Private Types
//
// ****************************************************************************

// None

// ****************************************************************************
//
// Public Data
//
// ****************************************************************************

#[link_section=".nvic_table"]
#[no_mangle]
pub static ISR_VECTORS: [Option<unsafe extern "C" fn()>; 155] = [// Stack pointer
                                                                 Some(_stack_top),
                                                                 // Reset
                                                                 Some(::common::startup::startup),
                                                                 // NMI
                                                                 Some(isr_nmi),
                                                                 // Hard Fault
                                                                 Some(isr_hardfault),
                                                                 // CM3 Memory Management Fault
                                                                 Some(isr_mmfault),
                                                                 // CM3 Bus Fault
                                                                 Some(isr_busfault),
                                                                 // CM3 Usage Fault
                                                                 Some(isr_usagefault),
                                                                 // Reserved - Used as NXP Checksum
                                                                 None,
                                                                 // Reserved
                                                                 None,
                                                                 // Reserved
                                                                 None,
                                                                 // Reserved
                                                                 None,
                                                                 // SVCall
                                                                 Some(isr_svcall),
                                                                 // Reserved for debug
                                                                 Some(isr_debugmon),
                                                                 // Reserved
                                                                 None,
                                                                 // PendSV
                                                                 Some(isr_pendsv),
                                                                 // SysTick
                                                                 Some(isr_systick),
                                                                 // GPIO Port A                      16
                                                                 Some(isr_empty_def),
                                                                 // GPIO Port B                      17
                                                                 Some(isr_empty_def),
                                                                 // GPIO Port C                      18
                                                                 Some(isr_empty_def),
                                                                 // GPIO Port D                      19
                                                                 Some(isr_empty_def),
                                                                 // GPIO Port E                      20
                                                                 Some(isr_empty_def),
                                                                 // UART 0                           21
                                                                 Some(uart::uart0_isr),
                                                                 // UART 1                           22
                                                                 Some(isr_empty_def),
                                                                 // SSI 0                            23
                                                                 Some(isr_empty_def),
                                                                 // I2C 0                            24
                                                                 Some(isr_empty_def),
                                                                 // Reserved                         25
                                                                 None,
                                                                 // Reserved                         26
                                                                 None,
                                                                 // Reserved                         27
                                                                 None,
                                                                 // Reserved                         28
                                                                 None,
                                                                 // Reserved                         29
                                                                 None,
                                                                 // ADC 0 Seq 0                      30
                                                                 Some(isr_empty_def),
                                                                 // ADC 0 Seq 1                      31
                                                                 Some(isr_empty_def),
                                                                 // ADC 0 Seq 2                      32
                                                                 Some(isr_empty_def),
                                                                 // ADC 0 Seq 3                      33
                                                                 Some(isr_empty_def),
                                                                 // WDT 0 and 1                      34
                                                                 Some(isr_empty_def),
                                                                 // 16/32 bit timer 0 A              35
                                                                 Some(isr_empty_def),
                                                                 // 16/32 bit timer 0 B              36
                                                                 Some(isr_empty_def),
                                                                 // 16/32 bit timer 1 A              37
                                                                 Some(isr_empty_def),
                                                                 // 16/32 bit timer 1 B              38
                                                                 Some(isr_empty_def),
                                                                 // 16/32 bit timer 2 A              39
                                                                 Some(isr_empty_def),
                                                                 // 16/32 bit timer 2 B              40
                                                                 Some(isr_empty_def),
                                                                 // Analog comparator 0              41
                                                                 Some(isr_empty_def),
                                                                 // Analog comparator 1              42
                                                                 Some(isr_empty_def),
                                                                 // Reserved                         43
                                                                 None,
                                                                 // System control                   44
                                                                 Some(isr_empty_def),
                                                                 // Flash + EEPROM control           45
                                                                 Some(isr_empty_def),
                                                                 // GPIO Port F                      46
                                                                 Some(isr_empty_def),
                                                                 // Reserved                         47
                                                                 None,
                                                                 // Reserved                         48
                                                                 None,
                                                                 // UART 2                           49
                                                                 Some(isr_empty_def),
                                                                 // SSI 1                            50
                                                                 Some(isr_empty_def),
                                                                 // 16/32 bit timer 3 A              51
                                                                 Some(isr_empty_def),
                                                                 // 16/32 bit timer 3 B              52
                                                                 Some(isr_empty_def),
                                                                 // I2C 1                            53
                                                                 Some(isr_empty_def),
                                                                 // Reserved                         54
                                                                 None,
                                                                 // CAN 0                            55
                                                                 Some(isr_empty_def),
                                                                 // Reserved                         56
                                                                 None,
                                                                 // Reserved                         57
                                                                 None,
                                                                 // Reserved                         58
                                                                 None,
                                                                 // Hibernation module               59
                                                                 Some(isr_empty_def),
                                                                 // USB                              60
                                                                 Some(isr_empty_def),
                                                                 // Reserved                         61
                                                                 None,
                                                                 // UDMA SW                          62
                                                                 Some(isr_empty_def),
                                                                 // UDMA Error                       63
                                                                 Some(isr_empty_def),
                                                                 // ADC 1 Seq 0                      64
                                                                 Some(isr_empty_def),
                                                                 // ADC 1 Seq 1                      65
                                                                 Some(isr_empty_def),
                                                                 // ADC 1 Seq 2                      66
                                                                 Some(isr_empty_def),
                                                                 // ADC 1 Seq 3                      67
                                                                 Some(isr_empty_def),
                                                                 // Reserved                         68
                                                                 None,
                                                                 // Reserved                         69
                                                                 None,
                                                                 // Reserved                         70
                                                                 None,
                                                                 // Reserved                         71
                                                                 None,
                                                                 // Reserved                         72
                                                                 None,
                                                                 // SSI 2                            73
                                                                 Some(isr_empty_def),
                                                                 // SSI 2                            74
                                                                 Some(isr_empty_def),
                                                                 // UART 3                           75
                                                                 Some(isr_empty_def),
                                                                 // UART 4                           76
                                                                 Some(isr_empty_def),
                                                                 // UART 5                           77
                                                                 Some(isr_empty_def),
                                                                 // UART 6                           78
                                                                 Some(isr_empty_def),
                                                                 // UART 7                           79
                                                                 Some(isr_empty_def),
                                                                 // Reserved                         80
                                                                 None,
                                                                 // Reserved                         81
                                                                 None,
                                                                 // Reserved                         82
                                                                 None,
                                                                 // Reserved                         83
                                                                 None,
                                                                 // I2C 2                            84
                                                                 Some(isr_empty_def),
                                                                 // I2C 4                            85
                                                                 Some(isr_empty_def),
                                                                 // 16/32 bit timer 4 A              86
                                                                 Some(isr_empty_def),
                                                                 // 16/32 bit timer 4 B              87
                                                                 Some(isr_empty_def),
                                                                 // Reserved                         88
                                                                 None,
                                                                 // Reserved                         89
                                                                 None,
                                                                 // Reserved                         90
                                                                 None,
                                                                 // Reserved                         91
                                                                 None,
                                                                 // Reserved                         92
                                                                 None,
                                                                 // Reserved                         93
                                                                 None,
                                                                 // Reserved                         94
                                                                 None,
                                                                 // Reserved                         95
                                                                 None,
                                                                 // Reserved                         96
                                                                 None,
                                                                 // Reserved                         97
                                                                 None,
                                                                 // Reserved                         98
                                                                 None,
                                                                 // Reserved                         99
                                                                 None,
                                                                 // Reserved                         100
                                                                 None,
                                                                 // Reserved                         101
                                                                 None,
                                                                 // Reserved                         102
                                                                 None,
                                                                 // Reserved                         103
                                                                 None,
                                                                 // Reserved                         104
                                                                 None,
                                                                 // Reserved                         105
                                                                 None,
                                                                 // Reserved                         106
                                                                 None,
                                                                 // Reserved                         107
                                                                 None,
                                                                 // 16/32 bit timer 5 A              108
                                                                 Some(isr_empty_def),
                                                                 // 16/32 bit timer 5 B              109
                                                                 Some(isr_empty_def),
                                                                 // 32/64 bit timer 0 A              110
                                                                 Some(isr_empty_def),
                                                                 // 32/64 bit timer 0 B              111
                                                                 Some(isr_empty_def),
                                                                 // 32/64 bit timer 1 A              112
                                                                 Some(isr_empty_def),
                                                                 // 32/64 bit timer 1 B              113
                                                                 Some(isr_empty_def),
                                                                 // 32/64 bit timer 2 A              114
                                                                 Some(isr_empty_def),
                                                                 // 32/64 bit timer 2 B              115
                                                                 Some(isr_empty_def),
                                                                 // 32/64 bit timer 3 A              116
                                                                 Some(isr_empty_def),
                                                                 // 32/64 bit timer 3 B              117
                                                                 Some(isr_empty_def),
                                                                 // 32/64 bit timer 4 A              118
                                                                 Some(isr_empty_def),
                                                                 // 32/64 bit timer 4 B              119
                                                                 Some(isr_empty_def),
                                                                 // 32/64 bit timer 5 A              120
                                                                 Some(isr_empty_def),
                                                                 // 32/64 bit timer 5 B              121
                                                                 Some(isr_empty_def),
                                                                 // System Exception                 122
                                                                 Some(isr_empty_def),
                                                                 // Reserved                         123
                                                                 None,
                                                                 // Reserved                         124
                                                                 None,
                                                                 // Reserved                         125
                                                                 None,
                                                                 // Reserved                         126
                                                                 None,
                                                                 // Reserved                         127
                                                                 None,
                                                                 // Reserved                         128
                                                                 None,
                                                                 // Reserved                         129
                                                                 None,
                                                                 // Reserved                         130
                                                                 None,
                                                                 // Reserved                         131
                                                                 None,
                                                                 // Reserved                         132
                                                                 None,
                                                                 // Reserved                         133
                                                                 None,
                                                                 // Reserved                         134
                                                                 None,
                                                                 // Reserved                         135
                                                                 None,
                                                                 // Reserved                         136
                                                                 None,
                                                                 // Reserved                         137
                                                                 None,
                                                                 // Reserved                         138
                                                                 None,
                                                                 // Reserved                         139
                                                                 None,
                                                                 // Reserved                         140
                                                                 None,
                                                                 // Reserved                         141
                                                                 None,
                                                                 // Reserved                         142
                                                                 None,
                                                                 // Reserved                         143
                                                                 None,
                                                                 // Reserved                         144
                                                                 None,
                                                                 // Reserved                         145
                                                                 None,
                                                                 // Reserved                         146
                                                                 None,
                                                                 // Reserved                         147
                                                                 None,
                                                                 // Reserved                         148
                                                                 None,
                                                                 // Reserved                         149
                                                                 None,
                                                                 // Reserved                         150
                                                                 None,
                                                                 // Reserved                         151
                                                                 None,
                                                                 // Reserved                         152
                                                                 None,
                                                                 // Reserved                         153
                                                                 None,
                                                                 // Reserved                         154
                                                                 None];

// ****************************************************************************
//
// Public Functions
//
// ****************************************************************************

/// Busy-waits for the given period.
///
/// Currently this function spins with a empirical number
/// of NOPS per millisecond. It should really use a timer.
///
/// * `ms` - The period to wait, in milliseconds
pub fn delay(ms: i32) {
    for _ in 0..ms * 250 {
        unsafe {
            asm!("NOP");
        }
    }
}

// ****************************************************************************
//
// Private Functions
//
// ****************************************************************************

/// A Non Maskable Interrupt (NMI) can be signalled by a peripheral or
/// triggered by software. This is the highest priority exception other than
/// reset. It is permanently enabled and has a fixed priority of -2. NMIs
/// cannot be:
/// * masked or prevented from activation by any other exception
/// * preempted by any exception other than Reset.
#[no_mangle]
pub unsafe extern "C" fn isr_nmi() {
    // Do nothing
}

/// A HardFault is an exception that occurs because of an error during
/// exception processing, or because an exception cannot be managed by any
/// other exception mechanism. HardFaults have a fixed priority of -1, meaning
/// they have higher priority than any exception with configurable priority.
#[no_mangle]
pub unsafe extern "C" fn isr_hardfault() {

     // Todo see https://community.arm.com/servlet/JiveServlet/previewBody/7835-102-2-12371/Developing%20a%20Generic%20Hard%20Fault%20handler%20for%20ARM.pdf
     // Use ITM to emit serial chars and then bkpt into debugger
     bkpt!();
     board::panic();
}

/// A MemManage fault is an exception that occurs because of a memory
/// protection related fault. The the fixed memory protection constraints
/// determines this fault, for both instruction and data memory transactions.
/// This fault is always used to abort instruction accesses to Execute Never
/// (XN) memory regions.
#[no_mangle]
pub unsafe extern "C" fn isr_mmfault() {
    board::panic();
}

/// A BusFault is an exception that occurs because of a memory related fault
/// for an instruction or data memory transaction. This might be from an error
/// detected on a bus in the memory system.
#[no_mangle]
pub unsafe extern "C" fn isr_busfault() {
    board::panic();
}

/// A UsageFault is an exception that occurs because of a fault related to instruction execution. This includes:
/// * an undefined instruction
/// * an illegal unaligned access
/// * invalid state on instruction execution
/// * an error on exception return.
/// The following can cause a UsageFault when the core is configured to report them:
/// * an unaligned address on word and halfword memory access
/// * division by zero.
#[no_mangle]
pub unsafe extern "C" fn isr_usagefault() {
    board::panic();
}

/// A supervisor call (SVC) is an exception that is triggered by the SVC
/// instruction. In an OS environment, applications can use SVC instructions
/// to access OS kernel functions and device drivers.
#[no_mangle]
pub unsafe extern "C" fn isr_svcall() {
    // Nothing
}

/// Debug monitor interrupt handler.
#[no_mangle]
pub unsafe extern "C" fn isr_debugmon() {
    // Nothing
}

/// PendSV is an interrupt-driven request for system-level service. In an OS
/// environment, use PendSV for context switching when no other exception is
/// active.
#[no_mangle]
pub unsafe extern "C" fn isr_pendsv() {
    // Nothing
}

/// A SysTick exception is an exception the system timer generates when it
/// reaches zero. Software can also generate a SysTick exception. In an OS
/// environment, the processor can use this exception as system tick.
#[no_mangle]
pub unsafe extern "C" fn isr_systick() {
    systick::isr();
}

/// A place-holder ISR used when we have nothing better to use.
#[no_mangle]
pub unsafe extern "C" fn isr_empty_def() {
    board::panic();
}

// ****************************************************************************
//
// End Of File
//
// ****************************************************************************
<|endoftext|>


<commit_before>// Copyright 2018 The Grin Developers
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//! Base types that the block chain pipeline requires.

use crate::core::core::hash::{Hash, Hashed, ZERO_HASH};
use crate::core::core::{Block, BlockHeader};
use crate::core::pow::Difficulty;
use crate::core::ser;

bitflags! {
/// Options for block validation
	pub struct Options: u32 {
		/// No flags
		const NONE = 0b00000000;
		/// Runs without checking the Proof of Work, mostly to make testing easier.
		const SKIP_POW = 0b00000001;
		/// Adds block while in syncing mode.
		const SYNC = 0b00000010;
		/// Block validation on a block we mined ourselves
		const MINE = 0b00000100;
	}
}

/// A helper to hold the roots of the txhashset in order to keep them
/// readable.
#[derive(Debug)]
pub struct TxHashSetRoots {
	/// Header root
	pub header_root: Hash,
	/// Output root
	pub output_root: Hash,
	/// Range Proof root
	pub rproof_root: Hash,
	/// Kernel root
	pub kernel_root: Hash,
}

/// The tip of a fork. A handle to the fork ancestry from its leaf in the
/// blockchain tree. References the max height and the latest and previous
/// blocks
/// for convenience and the total difficulty.
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
pub struct Tip {
	/// Height of the tip (max height of the fork)
	pub height: u64,
	/// Last block pushed to the fork
	pub last_block_h: Hash,
	/// Previous block
	pub prev_block_h: Hash,
	/// Total difficulty accumulated on that fork
	pub total_difficulty: Difficulty,
}

impl Tip {
	/// TODO - why do we have Tip when we could just use a block header?
	/// Creates a new tip based on header.
	pub fn from_header(header: &BlockHeader) -> Tip {
		Tip {
			height: header.height,
			last_block_h: header.hash(),
			prev_block_h: header.prev_hash,
			total_difficulty: header.total_difficulty(),
		}
	}
}

impl Default for Tip {
	fn default() -> Self {
		Tip {
			height: 0,
			last_block_h: ZERO_HASH,
			prev_block_h: ZERO_HASH,
			total_difficulty: Difficulty::min(),
		}
	}
}

/// Serialization of a tip, required to save to datastore.
impl ser::Writeable for Tip {
	fn write<W: ser::Writer>(&self, writer: &mut W) -> Result<(), ser::Error> {
		writer.write_u64(self.height)?;
		writer.write_fixed_bytes(&self.last_block_h)?;
		writer.write_fixed_bytes(&self.prev_block_h)?;
		self.total_difficulty.write(writer)
	}
}

impl ser::Readable for Tip {
	fn read(reader: &mut dyn ser::Reader) -> Result<Tip, ser::Error> {
		let height = reader.read_u64()?;
		let last = Hash::read(reader)?;
		let prev = Hash::read(reader)?;
		let diff = Difficulty::read(reader)?;
		Ok(Tip {
			height: height,
			last_block_h: last,
			prev_block_h: prev,
			total_difficulty: diff,
		})
	}
}

/// Bridge between the chain pipeline and the rest of the system. Handles
/// downstream processing of valid blocks by the rest of the system, most
/// importantly the broadcasting of blocks to our peers.
pub trait ChainAdapter {
	/// The blockchain pipeline has accepted this block as valid and added
	/// it to our chain.
	fn block_accepted(&self, block: &Block, status: BlockStatus, opts: Options);
}

/// Inform the caller of the current status of a txhashset write operation,
/// as it can take quite a while to process. Each function is called in the
/// order defined below and can be used to provide some feedback to the
/// caller. Functions taking arguments can be called repeatedly to update
/// those values as the processing progresses.
pub trait TxHashsetWriteStatus {
	/// First setup of the txhashset
	fn on_setup(&self);
	/// Starting validation
	fn on_validation(&self, kernels: u64, kernel_total: u64, rproofs: u64, rproof_total: u64);
	/// Starting to save the txhashset and related data
	fn on_save(&self);
	/// Done writing a new txhashset
	fn on_done(&self);
}

/// Do-nothing implementation of TxHashsetWriteStatus
pub struct NoStatus;

impl TxHashsetWriteStatus for NoStatus {
	fn on_setup(&self) {}
	fn on_validation(&self, _ks: u64, _kts: u64, _rs: u64, _rt: u64) {}
	fn on_save(&self) {}
	fn on_done(&self) {}
}

/// Dummy adapter used as a placeholder for real implementations
pub struct NoopAdapter {}

impl ChainAdapter for NoopAdapter {
	fn block_accepted(&self, _b: &Block, _status: BlockStatus, _opts: Options) {}
}

/// Status of an accepted block.
#[derive(Debug, Clone, PartialEq)]
pub enum BlockStatus {
	/// Block is the "next" block, updating the chain head.
	Next,
	/// Block does not update the chain head and is a fork.
	Fork,
	/// Block updates the chain head via a (potentially disruptive) "reorg".
	/// Previous block was not our previous chain head.
	Reorg,
}
<commit_msg>add hash() to tip for safety (#2145)<commit_after>// Copyright 2018 The Grin Developers
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//! Base types that the block chain pipeline requires.

use crate::core::core::hash::{Hash, Hashed, ZERO_HASH};
use crate::core::core::{Block, BlockHeader};
use crate::core::pow::Difficulty;
use crate::core::ser;

bitflags! {
/// Options for block validation
	pub struct Options: u32 {
		/// No flags
		const NONE = 0b00000000;
		/// Runs without checking the Proof of Work, mostly to make testing easier.
		const SKIP_POW = 0b00000001;
		/// Adds block while in syncing mode.
		const SYNC = 0b00000010;
		/// Block validation on a block we mined ourselves
		const MINE = 0b00000100;
	}
}

/// A helper to hold the roots of the txhashset in order to keep them
/// readable.
#[derive(Debug)]
pub struct TxHashSetRoots {
	/// Header root
	pub header_root: Hash,
	/// Output root
	pub output_root: Hash,
	/// Range Proof root
	pub rproof_root: Hash,
	/// Kernel root
	pub kernel_root: Hash,
}

/// The tip of a fork. A handle to the fork ancestry from its leaf in the
/// blockchain tree. References the max height and the latest and previous
/// blocks
/// for convenience and the total difficulty.
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
pub struct Tip {
	/// Height of the tip (max height of the fork)
	pub height: u64,
	/// Last block pushed to the fork
	pub last_block_h: Hash,
	/// Previous block
	pub prev_block_h: Hash,
	/// Total difficulty accumulated on that fork
	pub total_difficulty: Difficulty,
}

impl Tip {
	/// Creates a new tip based on provided header.
	pub fn from_header(header: &BlockHeader) -> Tip {
		Tip {
			height: header.height,
			last_block_h: header.hash(),
			prev_block_h: header.prev_hash,
			total_difficulty: header.total_difficulty(),
		}
	}

	/// *Really* easy to accidentally call hash() on a tip (thinking its a header).
	/// So lets make hash() do the right thing here.
	pub fn hash(&self) -> Hash {
		self.last_block_h
	}
}

impl Default for Tip {
	fn default() -> Self {
		Tip {
			height: 0,
			last_block_h: ZERO_HASH,
			prev_block_h: ZERO_HASH,
			total_difficulty: Difficulty::min(),
		}
	}
}

/// Serialization of a tip, required to save to datastore.
impl ser::Writeable for Tip {
	fn write<W: ser::Writer>(&self, writer: &mut W) -> Result<(), ser::Error> {
		writer.write_u64(self.height)?;
		writer.write_fixed_bytes(&self.last_block_h)?;
		writer.write_fixed_bytes(&self.prev_block_h)?;
		self.total_difficulty.write(writer)
	}
}

impl ser::Readable for Tip {
	fn read(reader: &mut dyn ser::Reader) -> Result<Tip, ser::Error> {
		let height = reader.read_u64()?;
		let last = Hash::read(reader)?;
		let prev = Hash::read(reader)?;
		let diff = Difficulty::read(reader)?;
		Ok(Tip {
			height: height,
			last_block_h: last,
			prev_block_h: prev,
			total_difficulty: diff,
		})
	}
}

/// Bridge between the chain pipeline and the rest of the system. Handles
/// downstream processing of valid blocks by the rest of the system, most
/// importantly the broadcasting of blocks to our peers.
pub trait ChainAdapter {
	/// The blockchain pipeline has accepted this block as valid and added
	/// it to our chain.
	fn block_accepted(&self, block: &Block, status: BlockStatus, opts: Options);
}

/// Inform the caller of the current status of a txhashset write operation,
/// as it can take quite a while to process. Each function is called in the
/// order defined below and can be used to provide some feedback to the
/// caller. Functions taking arguments can be called repeatedly to update
/// those values as the processing progresses.
pub trait TxHashsetWriteStatus {
	/// First setup of the txhashset
	fn on_setup(&self);
	/// Starting validation
	fn on_validation(&self, kernels: u64, kernel_total: u64, rproofs: u64, rproof_total: u64);
	/// Starting to save the txhashset and related data
	fn on_save(&self);
	/// Done writing a new txhashset
	fn on_done(&self);
}

/// Do-nothing implementation of TxHashsetWriteStatus
pub struct NoStatus;

impl TxHashsetWriteStatus for NoStatus {
	fn on_setup(&self) {}
	fn on_validation(&self, _ks: u64, _kts: u64, _rs: u64, _rt: u64) {}
	fn on_save(&self) {}
	fn on_done(&self) {}
}

/// Dummy adapter used as a placeholder for real implementations
pub struct NoopAdapter {}

impl ChainAdapter for NoopAdapter {
	fn block_accepted(&self, _b: &Block, _status: BlockStatus, _opts: Options) {}
}

/// Status of an accepted block.
#[derive(Debug, Clone, PartialEq)]
pub enum BlockStatus {
	/// Block is the "next" block, updating the chain head.
	Next,
	/// Block does not update the chain head and is a fork.
	Fork,
	/// Block updates the chain head via a (potentially disruptive) "reorg".
	/// Previous block was not our previous chain head.
	Reorg,
}
<|endoftext|>


<commit_before>use proc_macro2::{Delimiter, Group, Ident, Punct, Spacing, Span, TokenStream, TokenTree};
use std::iter::FromIterator;
use syn::{Expr, Type};

#[test]
fn parse_interpolated_leading_component() {
    // mimics the token stream corresponding to `$mod::rest`
    let tokens = TokenStream::from_iter(vec![
        TokenTree::Group(Group::new(
            Delimiter::None,
            TokenStream::from_iter(vec![TokenTree::Ident(Ident::new(
                "first",
                Span::call_site(),
            ))]),
        )),
        TokenTree::Punct(Punct::new(':', Spacing::Joint)),
        TokenTree::Punct(Punct::new(':', Spacing::Alone)),
        TokenTree::Ident(Ident::new("rest", Span::call_site())),
    ]);

    match syn::parse2::<Expr>(tokens.clone()) {
        Ok(Expr::Path(_)) => {}
        expr => panic!("incorrect expr: {:?}", expr),
    }

    match syn::parse2::<Type>(tokens) {
        Ok(Type::Path(_)) => {}
        expr => panic!("incorrect expr: {:?}", expr),
    }
}
<commit_msg>Fix bad copy/paste in test_path<commit_after>use proc_macro2::{Delimiter, Group, Ident, Punct, Spacing, Span, TokenStream, TokenTree};
use std::iter::FromIterator;
use syn::{Expr, Type};

#[test]
fn parse_interpolated_leading_component() {
    // mimics the token stream corresponding to `$mod::rest`
    let tokens = TokenStream::from_iter(vec![
        TokenTree::Group(Group::new(
            Delimiter::None,
            TokenStream::from_iter(vec![TokenTree::Ident(Ident::new(
                "first",
                Span::call_site(),
            ))]),
        )),
        TokenTree::Punct(Punct::new(':', Spacing::Joint)),
        TokenTree::Punct(Punct::new(':', Spacing::Alone)),
        TokenTree::Ident(Ident::new("rest", Span::call_site())),
    ]);

    match syn::parse2::<Expr>(tokens.clone()) {
        Ok(Expr::Path(_)) => {}
        expr => panic!("incorrect expr: {:?}", expr),
    }

    match syn::parse2::<Type>(tokens) {
        Ok(Type::Path(_)) => {}
        ty => panic!("incorrect ty: {:?}", ty),
    }
}
<|endoftext|>