<commit_before>use crate::alloc::Allocator;
use core::iter::TrustedLen;
use core::ptr::{self};
use core::slice::{self};

use super::{IntoIter, SetLenOnDrop, Vec};

// Specialization trait used for Vec::extend
pub(super) trait SpecExtend<T, I> {
    fn spec_extend(&mut self, iter: I);
}

impl<T, I, A: Allocator> SpecExtend<T, I> for Vec<T, A>
where
    I: Iterator<Item = T>,
{
    default fn spec_extend(&mut self, iter: I) {
        self.extend_desugared(iter)
    }
}

impl<T, I, A: Allocator> SpecExtend<T, I> for Vec<T, A>
where
    I: TrustedLen<Item = T>,
{
    default fn spec_extend(&mut self, iterator: I) {
        // This is the case for a TrustedLen iterator.
        let (low, high) = iterator.size_hint();
        if let Some(high_value) = high {
            debug_assert_eq!(
                low,
                high_value,
                "TrustedLen iterator's size hint is not exact: {:?}",
                (low, high)
            );
        }
        if let Some(additional) = high {
            self.reserve(additional);
            unsafe {
                let mut ptr = self.as_mut_ptr().add(self.len());
                let mut local_len = SetLenOnDrop::new(&mut self.len);
                iterator.for_each(move |element| {
                    ptr::write(ptr, element);
                    ptr = ptr.offset(1);
                    // NB can't overflow since we would have had to alloc the address space
                    local_len.increment_len(1);
                });
            }
        } else {
            // Per TrustedLen contract a `None` upper bound means that the iterator length
            // truly exceeds usize::MAX, which would eventually lead to a capacity overflow anyway.
            // Since the other branch already panics eagerly (via `reserve()`) we do the same here.
            // This avoids additional codegen for a fallback code path which would eventually
            // panic anyway.
            panic!("capacity overflow");
        }
    }
}

impl<T, A: Allocator> SpecExtend<T, IntoIter<T>> for Vec<T, A> {
    fn spec_extend(&mut self, mut iterator: IntoIter<T>) {
        unsafe {
            self.append_elements(iterator.as_slice() as _);
        }
        iterator.ptr = iterator.end;
    }
}

impl<'a, T: 'a, I, A: Allocator + 'a> SpecExtend<&'a T, I> for Vec<T, A>
where
    I: Iterator<Item = &'a T>,
    T: Clone,
{
    default fn spec_extend(&mut self, iterator: I) {
        self.spec_extend(iterator.cloned())
    }
}

impl<'a, T: 'a, A: Allocator + 'a> SpecExtend<&'a T, slice::Iter<'a, T>> for Vec<T, A>
where
    T: Copy,
{
    fn spec_extend(&mut self, iterator: slice::Iter<'a, T>) {
        let slice = iterator.as_slice();
        unsafe { self.append_elements(slice) };
    }
}
<commit_msg>Auto merge of #84209 - pickfire:patch-3, r=jyn514<commit_after>use crate::alloc::Allocator;
use core::iter::TrustedLen;
use core::ptr::{self};
use core::slice::{self};

use super::{IntoIter, SetLenOnDrop, Vec};

// Specialization trait used for Vec::extend
pub(super) trait SpecExtend<T, I> {
    fn spec_extend(&mut self, iter: I);
}

impl<T, I, A: Allocator> SpecExtend<T, I> for Vec<T, A>
where
    I: Iterator<Item = T>,
{
    default fn spec_extend(&mut self, iter: I) {
        self.extend_desugared(iter)
    }
}

impl<T, I, A: Allocator> SpecExtend<T, I> for Vec<T, A>
where
    I: TrustedLen<Item = T>,
{
    default fn spec_extend(&mut self, iterator: I) {
        // This is the case for a TrustedLen iterator.
        let (low, high) = iterator.size_hint();
        if let Some(additional) = high {
            debug_assert_eq!(
                low,
                additional,
                "TrustedLen iterator's size hint is not exact: {:?}",
                (low, high)
            );
            self.reserve(additional);
            unsafe {
                let mut ptr = self.as_mut_ptr().add(self.len());
                let mut local_len = SetLenOnDrop::new(&mut self.len);
                iterator.for_each(move |element| {
                    ptr::write(ptr, element);
                    ptr = ptr.offset(1);
                    // NB can't overflow since we would have had to alloc the address space
                    local_len.increment_len(1);
                });
            }
        } else {
            // Per TrustedLen contract a `None` upper bound means that the iterator length
            // truly exceeds usize::MAX, which would eventually lead to a capacity overflow anyway.
            // Since the other branch already panics eagerly (via `reserve()`) we do the same here.
            // This avoids additional codegen for a fallback code path which would eventually
            // panic anyway.
            panic!("capacity overflow");
        }
    }
}

impl<T, A: Allocator> SpecExtend<T, IntoIter<T>> for Vec<T, A> {
    fn spec_extend(&mut self, mut iterator: IntoIter<T>) {
        unsafe {
            self.append_elements(iterator.as_slice() as _);
        }
        iterator.ptr = iterator.end;
    }
}

impl<'a, T: 'a, I, A: Allocator + 'a> SpecExtend<&'a T, I> for Vec<T, A>
where
    I: Iterator<Item = &'a T>,
    T: Clone,
{
    default fn spec_extend(&mut self, iterator: I) {
        self.spec_extend(iterator.cloned())
    }
}

impl<'a, T: 'a, A: Allocator + 'a> SpecExtend<&'a T, slice::Iter<'a, T>> for Vec<T, A>
where
    T: Copy,
{
    fn spec_extend(&mut self, iterator: slice::Iter<'a, T>) {
        let slice = iterator.as_slice();
        unsafe { self.append_elements(slice) };
    }
}
<|endoftext|>


<commit_before>use crate::{direction::Direction, ship::Ship, space::Space};
use std::cmp;

pub struct Player {
    is_cpu: bool,
    spaces: Vec<Space>,
    ships: Vec<Ship>,
    grid_size: [u8; 2],
    grid_cursor: [u8; 2],
}

impl Player {
    pub fn new(grid_size: [u8; 2], ship_count: usize, is_cpu: bool) -> Player {
        Player {
            is_cpu: is_cpu,
            spaces: Space::all_grid_spaces(&grid_size),
            ships: Vec::with_capacity(ship_count),
            grid_size: grid_size,
            grid_cursor: [0, 0],
        }
    }

    /// Selects a space.
    ///
    /// # Errors
    ///
    /// Returns an error if the space at `pos` was already checked.
    pub fn select_space(&mut self, pos: &[u8; 2]) -> Result<(), &'static str> {
        let space_index = self.space_index(pos);
        let ship_hit = self.ships.iter().position(|s| s.pos().contains(pos));
        self.spaces[space_index].set_checked(ship_hit.is_some())?;

        Ok(())
    }

    /// Sets the ship at the given position as sunk if all spaces it occupies
    /// have been checked, and returns whether the ship was sunk.
    ///
    /// # Errors
    ///
    /// Returns an error if no ship is at the given position, or if the ship
    /// state is not active.
    pub fn sink_ship_if_all_hit(&mut self, pos: &[u8; 2]) -> Result<bool, &'static str> {
        if let Some(index) = self.ships.iter().position(|s| s.pos().contains(pos)) {
            let sunk = self.ships[index]
                .pos()
                .iter()
                .all(|p| self.space(p).is_hit());

            if sunk {
                self.ships[index].set_sunk()?;
            }

            Ok(sunk)
        } else {
            Err("no ship at the given position")
        }
    }

    /// Returns whether all of the player's ships have been sunk.
    pub fn all_ships_sunk(&self) -> bool {
        self.ships.iter().all(|ship| ship.is_sunk())
    }

    /// Returns suggestions for the best spaces to check based on the player's hit spaces and ships.
    ///
    /// This is intended for use in cases where the active player is computer-controlled, to
    /// determine the space they check.  However, it could also be used to suggest a space that a
    /// human player could check.
    pub fn suggested_checks(&self) -> Vec<[u8; 2]> {
        let mut select = vec![];
        let directions = Direction::all();
        let hit_spaces = self
            .spaces
            .iter()
            .filter(|s| s.is_hit() && self.ship(s.pos()).unwrap().is_active())
            .collect::<Vec<&Space>>();

        // Check for a line of hit spaces.
        for space in &hit_spaces {
            for direction in &directions {
                let unchecked = self.find_unchecked_space(space.pos(), *direction, true);

                if let Some(pos) = unchecked {
                    if !select.contains(&pos) {
                        select.push(pos);
                    }
                }
            }
        }

        // If a hit space was found, but no hit spaces next to it, look for unchecked spaces next
        // to it.
        if hit_spaces.len() > 0 && select.is_empty() {
            for direction in &directions {
                let unchecked = self.find_unchecked_space(hit_spaces[0].pos(), *direction, false);

                if let Some(pos) = unchecked {
                    select.push(pos);
                }
            }
        }

        // If no candidates have been found yet, just add any unchecked space.
        // TODO: smarter checking for spaces that remaining ships could realistically occupy.
        if select.is_empty() {
            select = self
                .spaces
                .iter()
                .filter(|space| space.is_unchecked())
                .map(|space| *space.pos())
                .collect::<Vec<[u8; 2]>>();
        }

        select
    }

    pub fn add_ship(
        &mut self,
        head: [u8; 2],
        direction: Direction,
        length: u8,
        placement: bool,
    ) -> Result<(), &'static str> {
        if self.ships.len() == self.ships.capacity() {
            Err("tried to add ship to a player with all ships already added")
        } else {
            let pos = self
                .get_ship_position(head, direction, length)
                .ok_or("tried to place a ship partially out of bounds")?;

            if !placement && !self.valid_ship_position(&pos) {
                Err("tried to place a ship in an invalid position")
            } else {
                let mut ship = Ship::new(pos)?;

                if !placement {
                    ship.set_active()?;
                }

                self.ships.push(ship);

                Ok(())
            }
        }
    }

    /// Moves the player's placement ship in the given direction.
    ///
    /// # Errors
    ///
    /// Returns an error if the player does not have a placement ship, or if the ship could not be
    /// moved in `direction` without going out of bounds.
    pub fn move_placement_ship(&mut self, direction: Direction) -> Result<(), &'static str> {
        let index = self.ships.len() - 1;
        let old_head = self.ships[index].pos()[0];
        let new_head = self
            .movement(&old_head, direction)
            .ok_or("movement not possible without going out of bounds")?;
        let ship_pos = self
            .get_ship_position(
                new_head,
                self.ships[index].dir(),
                self.ships[index].len() as u8,
            )
            .ok_or("movement not possible without going out of bounds")?;

        self.ships[index].set_pos(ship_pos)?;

        Ok(())
    }

    pub fn place_placement_ship(&mut self) -> Result<(), &'static str> {
        let index = self.ships.len() - 1;

        // Ensure the ship doesn't overlap with another ship.
        if !self.valid_ship_position(&self.ships[index].pos()) {
            Err("placement ship overlaps with another ship")
        } else {
            self.ships[index].set_active()?;

            Ok(())
        }
    }

    /// Rotates the player's placement ship during the ship placement game state.
    ///
    /// # Errors
    ///
    /// Returns an error if the player does not have a placement ship.
    pub fn rotate_placement_ship(&mut self) -> Result<(), &'static str> {
        let index = self.ships.len() - 1;
        let ship_len = self.ships[index].len() as u8;
        let dir = self.ships[index].dir().rotated();

        // If the current ship position would cause the rotation to position the ship partially out
        // of bounds, adjust the position such that the ship will be entirely within bounds.
        let old_head = self.ships[index].pos()[0];
        let new_head = match dir {
            Direction::North => [
                old_head[0],
                cmp::min(old_head[1], self.grid_size[1] - ship_len),
            ],
            Direction::East => [cmp::max(old_head[0], ship_len - 1), old_head[1]],
            Direction::South => [old_head[0], cmp::max(old_head[1], ship_len - 1)],
            Direction::West => [
                cmp::min(old_head[0], self.grid_size[0] - ship_len),
                old_head[1],
            ],
        };

        // get_ship_position() should always return Some(ship_pos) in this situation.
        let ship_pos = self.get_ship_position(new_head, dir, ship_len).unwrap();
        self.ships[index].set_pos(ship_pos)?;

        Ok(())
    }

    /// Returns a ship position, given its head position, direction and length.
    ///
    /// `direction` refers to the direction the ship is facing, not the
    /// direction in which positions are generated.
    /// Returns `None` if the resulting ship position would not be contained
    /// within the grid.
    pub fn get_ship_position(
        &self,
        head: [u8; 2],
        direction: Direction,
        length: u8,
    ) -> Option<Vec<[u8; 2]>> {
        let valid = match direction {
            Direction::North => head[1] + length <= self.grid_size[1],
            Direction::East => head[0] >= length - 1,
            Direction::South => head[1] >= length - 1,
            Direction::West => head[0] + length <= self.grid_size[0],
        };

        if valid {
            let mut ship = Vec::with_capacity(length as usize);

            for pos in 0..length {
                let pos_u8 = pos as u8;

                ship.push(match direction {
                    Direction::North => [head[0], head[1] + pos_u8],
                    Direction::East => [head[0] - pos_u8, head[1]],
                    Direction::South => [head[0], head[1] - pos_u8],
                    Direction::West => [head[0] + pos_u8, head[1]],
                });
            }

            Some(ship)
        } else {
            None
        }
    }

    /// Checks that the given ship position is valid.
    ///
    /// If the player is CPU-controlled, a ship in a space next to another ship
    /// will be considered invalid.
    fn valid_ship_position(&self, new_ship: &[[u8; 2]]) -> bool {
        new_ship.iter().all(|s| {
            self.valid_space(s)
                && !self.ship_is_in_space(s)
                && !(self.ship_is_next_to(s) && self.is_cpu)
        })
    }

    /// Gets a reference to the ships.
    pub fn ships(&self) -> &[Ship] {
        &self.ships
    }

    /// Gets a reference to a ship if it is in the given position.
    fn ship(&self, pos: &[u8; 2]) -> Option<&Ship> {
        self.ships.iter().find(|s| s.pos().contains(pos))
    }

    /// Returns whether a ship occupies the specified grid coordinates.
    pub fn ship_is_in_space(&self, pos: &[u8; 2]) -> bool {
        self.ships
            .iter()
            .any(|s| s.pos().contains(pos) && !s.is_placement())
    }

    /// Returns whether there is a ship next to the specified grid coordinates.
    fn ship_is_next_to(&self, pos: &[u8; 2]) -> bool {
        let x = pos[0];
        let y = pos[1];

        if x > 0 {
            // Left
            self.ship_is_in_space(&[x - 1, y])
        } else if x < self.grid_size[0] - 1 {
            // Right
            self.ship_is_in_space(&[x + 1, y])
        } else if y > 0 {
            // Above
            self.ship_is_in_space(&[x, y - 1])
        } else if y < self.grid_size[1] - 1 {
            // Below
            self.ship_is_in_space(&[x, y + 1])
        } else {
            false
        }
    }

    /// Gets a reference to the spaces.
    pub fn spaces(&self) -> &[Space] {
        &self.spaces
    }

    /// Returns whether the given position is valid.
    fn valid_space(&self, pos: &[u8; 2]) -> bool {
        pos[0] < self.grid_size[0] && pos[1] < self.grid_size[1]
    }

    /// Gets a reference to the space with the given position.
    pub fn space(&self, pos: &[u8; 2]) -> &Space {
        self.spaces.get(self.space_index(pos)).unwrap()
    }

    /// Calculates the index of the given position in the spaces vector.
    fn space_index(&self, pos: &[u8; 2]) -> usize {
        self.grid_size[0] as usize * pos[0] as usize + pos[1] as usize
    }

    /// Returns the coordinates of a movement from `pos` in a `direction`.
    /// Returns `None` if the movement is not possible.
    fn movement(&self, pos: &[u8; 2], direction: Direction) -> Option<[u8; 2]> {
        let valid = match direction {
            Direction::North => pos[1] > 0,
            Direction::East => pos[0] < self.grid_size[0] - 1,
            Direction::South => pos[1] < self.grid_size[1] - 1,
            Direction::West => pos[0] > 0,
        };

        match valid {
            true => Some(match direction {
                Direction::North => [pos[0], pos[1] - 1],
                Direction::East => [pos[0] + 1, pos[1]],
                Direction::South => [pos[0], pos[1] + 1],
                Direction::West => [pos[0] - 1, pos[1]],
            }),
            false => None,
        }
    }

    /// Finds the first non-hit, unchecked space in a `direction` from `pos`.
    /// Can also make sure the space is at the end of a `line` of hit spaces.
    /// Returns `None` if the first non-hit space has been checked or if a grid
    /// boundary is reached.
    fn find_unchecked_space(
        &self,
        pos: &[u8; 2],
        direction: Direction,
        check_for_line: bool,
    ) -> Option<[u8; 2]> {
        let mut check_pos = self.movement(pos, direction);

        while let Some(next_pos) = check_pos {
            let next_space = self.space(&next_pos);

            match next_space.is_hit() {
                true => check_pos = self.movement(&next_pos, direction),
                false => {
                    if !next_space.is_unchecked() {
                        check_pos = None;
                    }
                    break;
                }
            };
        }

        if check_for_line && check_pos.is_some() {
            let unchecked = check_pos.unwrap();
            let opposite_dir = direction.opposite();
            let prev_pos = self.movement(&unchecked, opposite_dir).unwrap();

            if &prev_pos == pos {
                check_pos = None;
            }
        }

        check_pos
    }

    /// Returns the coordinates of the player's grid cursor.
    pub fn grid_cursor(&self) -> &[u8; 2] {
        &self.grid_cursor
    }

    /// Moves the player's grid cursor in the given `direction`.
    ///
    /// # Errors
    ///
    /// Returns an error if moving the grid cursor in `direction` would move it out of bounds.
    pub fn move_grid_cursor(&mut self, direction: Direction) -> Result<(), &'static str> {
        if let Some(new_cursor) = self.movement(&self.grid_cursor, direction) {
            self.set_grid_cursor(&new_cursor)?;

            Ok(())
        } else {
            Err("tried to move grid cursor out of bounds")
        }
    }

    /// Sets the player's grid cursor position.
    ///
    /// # Errors
    ///
    /// Returns an error if no space exists at `pos`.
    pub fn set_grid_cursor(&mut self, pos: &[u8; 2]) -> Result<(), &'static str> {
        if self.space_index(pos) < self.spaces.len() {
            self.grid_cursor = *pos;

            Ok(())
        } else {
            Err("tried to set the grid cursor to a nonexistent space")
        }
    }

    pub fn is_cpu(&self) -> bool {
        self.is_cpu
    }

    pub fn placement_ship(&self) -> Result<&Ship, &'static str> {
        let ships_len = self.ships.len();

        if ships_len == 0 {
            Err("player has no ships")
        } else if !self.ships[ships_len - 1].is_placement() {
            Err("player has no placement ship")
        } else {
            Ok(&self.ships[self.ships.len() - 1])
        }
    }

    pub fn placement_ship_mut(&mut self) -> Result<&mut Ship, &'static str> {
        let ships_len = self.ships.len();

        if ships_len == 0 {
            Err("player has no ships")
        } else if !self.ships[ships_len - 1].is_placement() {
            Err("player has no placement ship")
        } else {
            Ok(&mut self.ships[ships_len - 1])
        }
    }
}
<commit_msg>Better<commit_after>use crate::{direction::Direction, ship::Ship, space::Space};
use std::cmp;

pub struct Player {
    is_cpu: bool,
    spaces: Vec<Space>,
    ships: Vec<Ship>,
    grid_size: [u8; 2],
    grid_cursor: [u8; 2],
}

impl Player {
    pub fn new(grid_size: [u8; 2], ship_count: usize, is_cpu: bool) -> Player {
        Player {
            is_cpu: is_cpu,
            spaces: Space::all_grid_spaces(&grid_size),
            ships: Vec::with_capacity(ship_count),
            grid_size: grid_size,
            grid_cursor: [0, 0],
        }
    }

    /// Selects a space.
    ///
    /// # Errors
    ///
    /// Returns an error if the space at `pos` was already checked.
    pub fn select_space(&mut self, pos: &[u8; 2]) -> Result<(), &'static str> {
        let space_index = self.space_index(pos);
        let ship_hit = self.ships.iter().position(|s| s.pos().contains(pos));
        self.spaces[space_index].set_checked(ship_hit.is_some())?;

        Ok(())
    }

    /// Sets the ship at the given position as sunk if all spaces it occupies
    /// have been checked, and returns whether the ship was sunk.
    ///
    /// # Errors
    ///
    /// Returns an error if no ship is at the given position, or if the ship
    /// state is not active.
    pub fn sink_ship_if_all_hit(&mut self, pos: &[u8; 2]) -> Result<bool, &'static str> {
        if let Some(index) = self.ships.iter().position(|s| s.pos().contains(pos)) {
            let sunk = self.ships[index]
                .pos()
                .iter()
                .all(|p| self.space(p).is_hit());

            if sunk {
                self.ships[index].set_sunk()?;
            }

            Ok(sunk)
        } else {
            Err("no ship at the given position")
        }
    }

    /// Returns whether all of the player's ships have been sunk.
    pub fn all_ships_sunk(&self) -> bool {
        self.ships.iter().all(|ship| ship.is_sunk())
    }

    /// Returns suggestions for the best spaces to check based on the player's hit spaces and ships.
    ///
    /// This is intended for use in cases where the active player is computer-controlled, to
    /// determine the space they check.  However, it could also be used to suggest a space that a
    /// human player could check.
    pub fn suggested_checks(&self) -> Vec<[u8; 2]> {
        let mut select = vec![];
        let directions = Direction::all();
        let hit_spaces = self
            .spaces
            .iter()
            .filter(|s| s.is_hit() && self.ship(s.pos()).unwrap().is_active())
            .collect::<Vec<&Space>>();

        // Check for a line of hit spaces.
        for space in &hit_spaces {
            for direction in &directions {
                let unchecked = self.find_unchecked_space(space.pos(), *direction, true);

                if let Some(pos) = unchecked {
                    if !select.contains(&pos) {
                        select.push(pos);
                    }
                }
            }
        }

        // If a hit space was found, but no hit spaces next to it, look for unchecked spaces next
        // to it.
        if hit_spaces.len() > 0 && select.is_empty() {
            for direction in &directions {
                let unchecked = self.find_unchecked_space(hit_spaces[0].pos(), *direction, false);

                if let Some(pos) = unchecked {
                    select.push(pos);
                }
            }
        }

        // If no candidates have been found yet, just add any unchecked space.
        // TODO: smarter checking for spaces that remaining ships could realistically occupy.
        if select.is_empty() {
            select = self
                .spaces
                .iter()
                .filter(|space| space.is_unchecked())
                .map(|space| *space.pos())
                .collect::<Vec<[u8; 2]>>();
        }

        select
    }

    pub fn add_ship(
        &mut self,
        head: [u8; 2],
        direction: Direction,
        length: u8,
        placement: bool,
    ) -> Result<(), &'static str> {
        if self.ships.len() == self.ships.capacity() {
            Err("tried to add ship to a player with all ships already added")
        } else {
            let pos = self
                .get_ship_position(head, direction, length)
                .ok_or("tried to place a ship partially out of bounds")?;

            if !placement && !self.valid_ship_position(&pos) {
                Err("tried to place a ship in an invalid position")
            } else {
                let mut ship = Ship::new(pos)?;

                if !placement {
                    ship.set_active()?;
                }

                self.ships.push(ship);

                Ok(())
            }
        }
    }

    /// Moves the player's placement ship in the given direction.
    ///
    /// # Errors
    ///
    /// Returns an error if the player does not have a placement ship, or if the ship could not be
    /// moved in `direction` without going out of bounds.
    pub fn move_placement_ship(&mut self, direction: Direction) -> Result<(), &'static str> {
        let index = self.ships.len() - 1;
        let old_head = self.ships[index].pos()[0];
        let new_head = self
            .movement(&old_head, direction)
            .ok_or("movement not possible without going out of bounds")?;
        let ship_pos = self
            .get_ship_position(
                new_head,
                self.ships[index].dir(),
                self.ships[index].len() as u8,
            )
            .ok_or("movement not possible without going out of bounds")?;

        self.ships[index].set_pos(ship_pos)?;

        Ok(())
    }

    pub fn place_placement_ship(&mut self) -> Result<(), &'static str> {
        let index = self.ships.len() - 1;

        // Ensure the ship doesn't overlap with another ship.
        if !self.valid_ship_position(&self.ships[index].pos()) {
            Err("placement ship overlaps with another ship")
        } else {
            self.ships[index].set_active()?;

            Ok(())
        }
    }

    /// Rotates the player's placement ship during the ship placement game state.
    ///
    /// # Errors
    ///
    /// Returns an error if the player does not have a placement ship.
    pub fn rotate_placement_ship(&mut self) -> Result<(), &'static str> {
        let index = self.ships.len() - 1;
        let ship_len = self.ships[index].len() as u8;
        let dir = self.ships[index].dir().rotated();

        // If the current ship position would cause the rotation to position the ship partially out
        // of bounds, adjust the position such that the ship will be entirely within bounds.
        let old_head = self.ships[index].pos()[0];
        let new_head = match dir {
            Direction::North => [
                old_head[0],
                cmp::min(old_head[1], self.grid_size[1] - ship_len),
            ],
            Direction::East => [cmp::max(old_head[0], ship_len - 1), old_head[1]],
            Direction::South => [old_head[0], cmp::max(old_head[1], ship_len - 1)],
            Direction::West => [
                cmp::min(old_head[0], self.grid_size[0] - ship_len),
                old_head[1],
            ],
        };

        // get_ship_position() should always return Some(ship_pos) in this situation.
        let ship_pos = self.get_ship_position(new_head, dir, ship_len).unwrap();
        self.ships[index].set_pos(ship_pos)?;

        Ok(())
    }

    /// Returns a ship position, given its head position, direction and length.
    ///
    /// `direction` refers to the direction the ship is facing, not the
    /// direction in which positions are generated.
    /// Returns `None` if the resulting ship position would not be contained
    /// within the grid.
    pub fn get_ship_position(
        &self,
        head: [u8; 2],
        direction: Direction,
        length: u8,
    ) -> Option<Vec<[u8; 2]>> {
        let valid = match direction {
            Direction::North => head[1] + length <= self.grid_size[1],
            Direction::East => head[0] >= length - 1,
            Direction::South => head[1] >= length - 1,
            Direction::West => head[0] + length <= self.grid_size[0],
        };

        if valid {
            let mut ship = Vec::with_capacity(length as usize);

            for pos in 0..length {
                let pos_u8 = pos as u8;

                ship.push(match direction {
                    Direction::North => [head[0], head[1] + pos_u8],
                    Direction::East => [head[0] - pos_u8, head[1]],
                    Direction::South => [head[0], head[1] - pos_u8],
                    Direction::West => [head[0] + pos_u8, head[1]],
                });
            }

            Some(ship)
        } else {
            None
        }
    }

    /// Checks that the given ship position is valid.
    ///
    /// If the player is CPU-controlled, a ship in a space next to another ship
    /// will be considered invalid.
    fn valid_ship_position(&self, new_ship: &[[u8; 2]]) -> bool {
        new_ship.iter().all(|s| {
            self.valid_space(s)
                && !self.ship_is_in_space(s)
                && !(self.ship_is_next_to(s) && self.is_cpu)
        })
    }

    /// Gets a reference to the ships.
    pub fn ships(&self) -> &[Ship] {
        &self.ships
    }

    /// Gets a reference to a ship if it is in the given position.
    fn ship(&self, pos: &[u8; 2]) -> Option<&Ship> {
        self.ships.iter().find(|s| s.pos().contains(pos))
    }

    /// Returns whether a ship occupies the specified grid coordinates.
    pub fn ship_is_in_space(&self, pos: &[u8; 2]) -> bool {
        self.ships
            .iter()
            .any(|s| s.pos().contains(pos) && !s.is_placement())
    }

    /// Returns whether there is a ship next to the specified grid coordinates.
    fn ship_is_next_to(&self, pos: &[u8; 2]) -> bool {
        let x = pos[0];
        let y = pos[1];

        // Left
        x > 0 && self.ship_is_in_space(&[x - 1, y])
            // Right
            || x < self.grid_size[0] - 1 && self.ship_is_in_space(&[x + 1, y])
            // Above
            || y > 0 && self.ship_is_in_space(&[x, y - 1])
            // Below
            || y < self.grid_size[1] - 1 && self.ship_is_in_space(&[x, y + 1])
    }

    /// Gets a reference to the spaces.
    pub fn spaces(&self) -> &[Space] {
        &self.spaces
    }

    /// Returns whether the given position is valid.
    fn valid_space(&self, pos: &[u8; 2]) -> bool {
        pos[0] < self.grid_size[0] && pos[1] < self.grid_size[1]
    }

    /// Gets a reference to the space with the given position.
    pub fn space(&self, pos: &[u8; 2]) -> &Space {
        self.spaces.get(self.space_index(pos)).unwrap()
    }

    /// Calculates the index of the given position in the spaces vector.
    fn space_index(&self, pos: &[u8; 2]) -> usize {
        self.grid_size[0] as usize * pos[0] as usize + pos[1] as usize
    }

    /// Returns the coordinates of a movement from `pos` in a `direction`.
    /// Returns `None` if the movement is not possible.
    fn movement(&self, pos: &[u8; 2], direction: Direction) -> Option<[u8; 2]> {
        let valid = match direction {
            Direction::North => pos[1] > 0,
            Direction::East => pos[0] < self.grid_size[0] - 1,
            Direction::South => pos[1] < self.grid_size[1] - 1,
            Direction::West => pos[0] > 0,
        };

        match valid {
            true => Some(match direction {
                Direction::North => [pos[0], pos[1] - 1],
                Direction::East => [pos[0] + 1, pos[1]],
                Direction::South => [pos[0], pos[1] + 1],
                Direction::West => [pos[0] - 1, pos[1]],
            }),
            false => None,
        }
    }

    /// Finds the first non-hit, unchecked space in a `direction` from `pos`.
    /// Can also make sure the space is at the end of a `line` of hit spaces.
    /// Returns `None` if the first non-hit space has been checked or if a grid
    /// boundary is reached.
    fn find_unchecked_space(
        &self,
        pos: &[u8; 2],
        direction: Direction,
        check_for_line: bool,
    ) -> Option<[u8; 2]> {
        let mut check_pos = self.movement(pos, direction);

        while let Some(next_pos) = check_pos {
            let next_space = self.space(&next_pos);

            match next_space.is_hit() {
                true => check_pos = self.movement(&next_pos, direction),
                false => {
                    if !next_space.is_unchecked() {
                        check_pos = None;
                    }
                    break;
                }
            };
        }

        if check_for_line && check_pos.is_some() {
            let unchecked = check_pos.unwrap();
            let opposite_dir = direction.opposite();
            let prev_pos = self.movement(&unchecked, opposite_dir).unwrap();

            if &prev_pos == pos {
                check_pos = None;
            }
        }

        check_pos
    }

    /// Returns the coordinates of the player's grid cursor.
    pub fn grid_cursor(&self) -> &[u8; 2] {
        &self.grid_cursor
    }

    /// Moves the player's grid cursor in the given `direction`.
    ///
    /// # Errors
    ///
    /// Returns an error if moving the grid cursor in `direction` would move it out of bounds.
    pub fn move_grid_cursor(&mut self, direction: Direction) -> Result<(), &'static str> {
        if let Some(new_cursor) = self.movement(&self.grid_cursor, direction) {
            self.set_grid_cursor(&new_cursor)?;

            Ok(())
        } else {
            Err("tried to move grid cursor out of bounds")
        }
    }

    /// Sets the player's grid cursor position.
    ///
    /// # Errors
    ///
    /// Returns an error if no space exists at `pos`.
    pub fn set_grid_cursor(&mut self, pos: &[u8; 2]) -> Result<(), &'static str> {
        if self.space_index(pos) < self.spaces.len() {
            self.grid_cursor = *pos;

            Ok(())
        } else {
            Err("tried to set the grid cursor to a nonexistent space")
        }
    }

    pub fn is_cpu(&self) -> bool {
        self.is_cpu
    }

    pub fn placement_ship(&self) -> Result<&Ship, &'static str> {
        let ships_len = self.ships.len();

        if ships_len == 0 {
            Err("player has no ships")
        } else if !self.ships[ships_len - 1].is_placement() {
            Err("player has no placement ship")
        } else {
            Ok(&self.ships[self.ships.len() - 1])
        }
    }

    pub fn placement_ship_mut(&mut self) -> Result<&mut Ship, &'static str> {
        let ships_len = self.ships.len();

        if ships_len == 0 {
            Err("player has no ships")
        } else if !self.ships[ships_len - 1].is_placement() {
            Err("player has no placement ship")
        } else {
            Ok(&mut self.ships[ships_len - 1])
        }
    }
}
<|endoftext|>


<commit_before>extern crate chrono;

use self::chrono::offset::Local;
use std::fmt;
use std::fs::{File, OpenOptions};
use std::io::{self, Write};

#[derive(Clone, Copy)]
pub enum Level {
    None,
    UserError,
    Critical,
    Error,
    Warn,
    Info,
    Debug,
}

impl fmt::Display for Level {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            Level::None => write!(f, "NONE"),
            Level::UserError => write!(f, "USERERROR"),
            Level::Critical => write!(f, "CRITICAL"),
            Level::Error => write!(f, "ERROR"),
            Level::Warn => write!(f, "WARNING"),
            Level::Info => write!(f, "INFO"),
            Level::Debug => write!(f, "DEBUG"),
        }
    }
}

pub struct Logger {
    logfile: Option<File>,
}

impl Logger {
    pub fn new() -> Logger {
        Logger {
            logfile: None,
        }
    }

    pub fn set_logfile(&mut self, filename: &str) {
        let file = OpenOptions::new()
            .create(true)
            .append(true)
            .open(filename);

        match file {
            Ok(file) => self.logfile = Some(file),
            Err(error) => eprintln!("Couldn't open `{}' as a logfile: {}", filename, error),
        }
    }

    pub fn log(&mut self, level: Level, message: &str) -> io::Result<()> {
        if let Some(ref mut logfile) = self.logfile {
            let timestamp = Local::now().format("%Y-%m-%d %H:%M:%S");
            let line = format!("[{}] {}: {}\n", timestamp, level, message);

            logfile.write_all(line.as_bytes())?;
        }

        Ok(())
    }
}

#[cfg(test)]
mod tests {
    extern crate tempfile;

    use super::*;

    use self::tempfile::TempDir;
    use self::chrono::{TimeZone, Duration};
    use std::io::{self, BufReader, BufRead};
    use std::path;

    fn setup_logger() -> io::Result<(TempDir, path::PathBuf, Logger)> {
        let tmp = TempDir::new()?;
        let logfile = {
            let mut logfile = tmp.path().to_owned();
            logfile.push("example.log");
            logfile
        };
        assert!(!logfile.exists());

        let mut logger = Logger::new();
        logger.set_logfile(logfile.to_str().unwrap());

        Ok((tmp, logfile, logger))
    }

    fn parse_log_line(line: &str) -> Option<(&str, &str, &str)> {
        if !line.starts_with("[") {
            return None;
        }

        let timestamp_end = line.find(']').expect("Failed to find the end of the timestamp");
        // Timestamp starts with "[", we skip it by starting at 1 rather than 0.
        let timestamp = &line[1..timestamp_end];

        // "]" is an ASCII character, so it occupies one byte in UTF-8. As a result, we
        // can simply add one to get the next character's byte offset. And since the
        // next char should be a space, which is ASCII as well, we can just add 2.
        //
        // If timestamp is followed by something non-ASCII, indexing into &str will
        // panic and fail the test, which is good.
        if &line[timestamp_end+1..timestamp_end+2] != " " {
            return None;
        }

        let level_end =
            line[timestamp_end+2..]
            .find(':')
            .expect("Failed to find the end of the loglevel");
        let level = &line[timestamp_end+2..timestamp_end+2+level_end];

        // Message starts after ": " that follows the level, hence +2.
        let message = &line[timestamp_end+2+level_end+2..];

        Some((timestamp, level, message))
    }

    #[test]
    fn t_set_logfile() -> io::Result<()> {
        let (_tmp, logfile, _logger) = setup_logger()?;

        assert!(logfile.exists());

        Ok(())
    }

    #[test]
    fn t_log_writes_message_to_the_file() -> io::Result<()> {
        let (_tmp, logfile, mut logger) = setup_logger()?;

        let messages = vec![
            "Hello, world!",
            "I'm doing fine, how are you?",
            "Time to wrap up, see ya!",
        ];

        let start_time = Local::now();
        for msg in &messages {
            logger.log(Level::Debug, msg)?;
        }
        let finish_time = Local::now();

        // Dropping logger to force it to flush the log and close the file
        drop(logger);

        let file = File::open(logfile)?;
        let reader = BufReader::new(file);
        for (line, expected) in reader.lines().zip(messages) {
            match line {
                Ok(line) => {
                    let (timestamp_str, _level, message) =
                        parse_log_line(&line)
                        .expect("Failed to split the log line into parts");

                    let timestamp =
                        Local::now()
                        .timezone()
                        .datetime_from_str(timestamp_str, "%Y-%m-%d %H:%M:%S")
                        .expect("Failed to parse the timestamp from the log file");
                    // `start_time` and `end_time` may have millisecond precision or better,
                    // whereas `timestamp` is limited to seconds. Therefore, we account for
                    // a situation where `start_time` is slightly bigger than `timestamp`.
                    assert!(timestamp - start_time > Duration::seconds(-1));
                    assert!(finish_time >= timestamp);

                    assert_eq!(message, expected);
                }
                Err(e) => return Err(e),
            }
        }

        Ok(())
    }

    #[test]
    fn t_different_loglevels_have_different_names() -> io::Result<()> {
        let (_tmp, logfile, mut logger) = setup_logger()?;

        let levels = vec![
            (Level::UserError, "USERERROR"),
            (Level::Critical, "CRITICAL"),
            (Level::Error, "ERROR"),
            (Level::Warn, "WARNING"),
            (Level::Info, "INFO"),
            (Level::Debug, "DEBUG"),
        ];

        let msg = "Some test message";

        for (level, _level_str) in &levels {
            logger.log(*level, msg)?;
        }

        // Dropping logger to force it to flush the log and close the file
        drop(logger);

        let file = File::open(logfile)?;
        let reader = BufReader::new(file);
        for (line, expected) in reader.lines().zip(levels.iter().map(|(_, l)| l)) {
            match line {
                Ok(line) => {
                    let (_timestamp_str, level, _message) =
                        parse_log_line(&line)
                        .expect("Failed to split the log line into parts");

                    assert_eq!(&level, expected);
                }
                Err(e) => return Err(e),
            }
        }

        Ok(())
    }
}
<commit_msg>Add a "threshold" for log messages' levels<commit_after>extern crate chrono;

use self::chrono::offset::Local;
use std::fmt;
use std::fs::{File, OpenOptions};
use std::io::{self, Write};

#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum Level {
    None,
    UserError,
    Critical,
    Error,
    Warn,
    Info,
    Debug,
}

impl fmt::Display for Level {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            Level::None => write!(f, "NONE"),
            Level::UserError => write!(f, "USERERROR"),
            Level::Critical => write!(f, "CRITICAL"),
            Level::Error => write!(f, "ERROR"),
            Level::Warn => write!(f, "WARNING"),
            Level::Info => write!(f, "INFO"),
            Level::Debug => write!(f, "DEBUG"),
        }
    }
}

pub struct Logger {
    logfile: Option<File>,
    loglevel: Level,
}

impl Logger {
    pub fn new() -> Logger {
        Logger {
            logfile: None,
            loglevel: Level::None,
        }
    }

    pub fn set_logfile(&mut self, filename: &str) {
        let file = OpenOptions::new()
            .create(true)
            .append(true)
            .open(filename);

        match file {
            Ok(file) => self.logfile = Some(file),
            Err(error) => eprintln!("Couldn't open `{}' as a logfile: {}", filename, error),
        }
    }

    pub fn log(&mut self, level: Level, message: &str) -> io::Result<()> {
        if level > self.loglevel {
            return Ok(());
        }

        if let Some(ref mut logfile) = self.logfile {
            let timestamp = Local::now().format("%Y-%m-%d %H:%M:%S");
            let line = format!("[{}] {}: {}\n", timestamp, level, message);

            logfile.write_all(line.as_bytes())?;
        }

        Ok(())
    }

    pub fn set_loglevel(&mut self, level: Level) {
        self.loglevel = level;
    }
}

#[cfg(test)]
mod tests {
    extern crate tempfile;

    use super::*;

    use self::tempfile::TempDir;
    use self::chrono::{TimeZone, Duration};
    use std::io::{self, BufReader, BufRead};
    use std::path;

    fn setup_logger() -> io::Result<(TempDir, path::PathBuf, Logger)> {
        let tmp = TempDir::new()?;
        let logfile = {
            let mut logfile = tmp.path().to_owned();
            logfile.push("example.log");
            logfile
        };
        assert!(!logfile.exists());

        let mut logger = Logger::new();
        logger.set_logfile(logfile.to_str().unwrap());

        Ok((tmp, logfile, logger))
    }

    fn parse_log_line(line: &str) -> Option<(&str, &str, &str)> {
        if !line.starts_with("[") {
            return None;
        }

        let timestamp_end = line.find(']').expect("Failed to find the end of the timestamp");
        // Timestamp starts with "[", we skip it by starting at 1 rather than 0.
        let timestamp = &line[1..timestamp_end];

        // "]" is an ASCII character, so it occupies one byte in UTF-8. As a result, we
        // can simply add one to get the next character's byte offset. And since the
        // next char should be a space, which is ASCII as well, we can just add 2.
        //
        // If timestamp is followed by something non-ASCII, indexing into &str will
        // panic and fail the test, which is good.
        if &line[timestamp_end+1..timestamp_end+2] != " " {
            return None;
        }

        let level_end =
            line[timestamp_end+2..]
            .find(':')
            .expect("Failed to find the end of the loglevel");
        let level = &line[timestamp_end+2..timestamp_end+2+level_end];

        // Message starts after ": " that follows the level, hence +2.
        let message = &line[timestamp_end+2+level_end+2..];

        Some((timestamp, level, message))
    }

    fn log_contains_n_lines(logfile: &path::Path, n: usize)  -> io::Result<()> {
        let file = File::open(logfile)?;
        let reader = BufReader::new(file);
        assert_eq!(reader.lines().count(), n);
        Ok(())
    }

    #[test]
    fn t_set_logfile() -> io::Result<()> {
        let (_tmp, logfile, _logger) = setup_logger()?;

        assert!(logfile.exists());

        Ok(())
    }

    #[test]
    fn t_log_writes_message_to_the_file() -> io::Result<()> {
        let (_tmp, logfile, mut logger) = setup_logger()?;

        let messages = vec![
            "Hello, world!",
            "I'm doing fine, how are you?",
            "Time to wrap up, see ya!",
        ];

        let start_time = Local::now();
        for msg in &messages {
            logger.log(Level::Debug, msg)?;
        }
        let finish_time = Local::now();

        // Dropping logger to force it to flush the log and close the file
        drop(logger);

        let file = File::open(logfile)?;
        let reader = BufReader::new(file);
        for (line, expected) in reader.lines().zip(messages) {
            match line {
                Ok(line) => {
                    let (timestamp_str, _level, message) =
                        parse_log_line(&line)
                        .expect("Failed to split the log line into parts");

                    let timestamp =
                        Local::now()
                        .timezone()
                        .datetime_from_str(timestamp_str, "%Y-%m-%d %H:%M:%S")
                        .expect("Failed to parse the timestamp from the log file");
                    // `start_time` and `end_time` may have millisecond precision or better,
                    // whereas `timestamp` is limited to seconds. Therefore, we account for
                    // a situation where `start_time` is slightly bigger than `timestamp`.
                    assert!(timestamp - start_time > Duration::seconds(-1));
                    assert!(finish_time >= timestamp);

                    assert_eq!(message, expected);
                }
                Err(e) => return Err(e),
            }
        }

        Ok(())
    }

    #[test]
    fn t_different_loglevels_have_different_names() -> io::Result<()> {
        let (_tmp, logfile, mut logger) = setup_logger()?;

        let levels = vec![
            (Level::UserError, "USERERROR"),
            (Level::Critical, "CRITICAL"),
            (Level::Error, "ERROR"),
            (Level::Warn, "WARNING"),
            (Level::Info, "INFO"),
            (Level::Debug, "DEBUG"),
        ];

        let msg = "Some test message";

        for (level, _level_str) in &levels {
            logger.log(*level, msg)?;
        }

        // Dropping logger to force it to flush the log and close the file
        drop(logger);

        let file = File::open(logfile)?;
        let reader = BufReader::new(file);
        for (line, expected) in reader.lines().zip(levels.iter().map(|(_, l)| l)) {
            match line {
                Ok(line) => {
                    let (_timestamp_str, level, _message) =
                        parse_log_line(&line)
                        .expect("Failed to split the log line into parts");

                    assert_eq!(&level, expected);
                }
                Err(e) => return Err(e),
            }
        }

        Ok(())
    }

    #[test]
    fn t_if_curlevel_is_none_nothing_is_logged() -> io::Result<()> {
        let (_tmp, logfile, mut logger) = setup_logger()?;

        logger.set_loglevel(Level::None);

        let levels = vec![
            (Level::UserError, "USERERROR"),
            (Level::Critical, "CRITICAL"),
            (Level::Error, "ERROR"),
            (Level::Warn, "WARNING"),
            (Level::Info, "INFO"),
            (Level::Debug, "DEBUG"),
        ];

        let msg = "Some test message";

        for (level, _level_str) in &levels {
            logger.log(*level, msg)?;
        }

        // Dropping logger to force it to flush the log and close the file
        drop(logger);

        log_contains_n_lines(&logfile, 0)?;

        Ok(())
    }

    #[test]
    fn t_user_errors_are_logged_at_all_curlevels_beside_none() -> io::Result<()> {
        {
            let (_tmp, logfile, mut logger) = setup_logger()?;
            logger.set_loglevel(Level::None);

            logger.log(Level::UserError, "hello")?;

            drop(logger);

            log_contains_n_lines(&logfile, 0)?;
        }

        let levels = vec![
            Level::UserError,
            Level::Critical,
            Level::Error,
            Level::Warn,
            Level::Info,
            Level::Debug,
        ];

        for level in levels {
            let (_tmp, logfile, mut logger) = setup_logger()?;
            logger.set_loglevel(level);

            logger.log(Level::UserError, "hello")?;

            drop(logger);

            log_contains_n_lines(&logfile, 1)?;
        };

        Ok(())
    }

    #[test]
    fn t_critial_msgs_are_logged_at_curlevels_starting_with_critical() -> io::Result<()> {
        let nolog_levels = vec![
            Level::None,
            Level::UserError,
        ];

        for level in nolog_levels {
            let (_tmp, logfile, mut logger) = setup_logger()?;
            logger.set_loglevel(level);

            logger.log(Level::Critical, "hello")?;

            drop(logger);

            log_contains_n_lines(&logfile, 0)?;
        }

        let log_levels = vec![
            Level::Critical,
            Level::Error,
            Level::Warn,
            Level::Info,
            Level::Debug,
        ];

        for level in log_levels {
            let (_tmp, logfile, mut logger) = setup_logger()?;
            logger.set_loglevel(level);

            logger.log(Level::Critical, "hello")?;

            drop(logger);

            log_contains_n_lines(&logfile, 1)?;
        };

        Ok(())
    }

    #[test]
    fn t_error_msgs_are_logged_at_curlevels_starting_with_error() -> io::Result<()> {
        let nolog_levels = vec![
            Level::None,
            Level::UserError,
            Level::Critical,
        ];

        for level in nolog_levels {
            let (_tmp, logfile, mut logger) = setup_logger()?;
            logger.set_loglevel(level);

            logger.log(Level::Error, "hello")?;

            drop(logger);

            log_contains_n_lines(&logfile, 0)?;
        }

        let log_levels = vec![
            Level::Error,
            Level::Warn,
            Level::Info,
            Level::Debug,
        ];

        for level in log_levels {
            let (_tmp, logfile, mut logger) = setup_logger()?;
            logger.set_loglevel(level);

            logger.log(Level::Error, "hello")?;

            drop(logger);

            log_contains_n_lines(&logfile, 1)?;
        };

        Ok(())
    }

    #[test]
    fn t_warning_msgs_are_logged_at_curlevels_starting_with_warning() -> io::Result<()> {
        let nolog_levels = vec![
            Level::None,
            Level::UserError,
            Level::Critical,
            Level::Error,
        ];

        for level in nolog_levels {
            let (_tmp, logfile, mut logger) = setup_logger()?;
            logger.set_loglevel(level);

            logger.log(Level::Warn, "hello")?;

            drop(logger);

            log_contains_n_lines(&logfile, 0)?;
        }

        let log_levels = vec![
            Level::Warn,
            Level::Info,
            Level::Debug,
        ];

        for level in log_levels {
            let (_tmp, logfile, mut logger) = setup_logger()?;
            logger.set_loglevel(level);

            logger.log(Level::Warn, "hello")?;

            drop(logger);

            log_contains_n_lines(&logfile, 1)?;
        };

        Ok(())
    }

    #[test]
    fn t_info_msgs_are_logged_at_curlevels_starting_with_info() -> io::Result<()> {
        let nolog_levels = vec![
            Level::None,
            Level::UserError,
            Level::Critical,
            Level::Error,
            Level::Warn,
        ];

        for level in nolog_levels {
            let (_tmp, logfile, mut logger) = setup_logger()?;
            logger.set_loglevel(level);

            logger.log(Level::Info, "hello")?;

            drop(logger);

            log_contains_n_lines(&logfile, 0)?;
        }

        let log_levels = vec![
            Level::Info,
            Level::Debug,
        ];

        for level in log_levels {
            let (_tmp, logfile, mut logger) = setup_logger()?;
            logger.set_loglevel(level);

            logger.log(Level::Info, "hello")?;

            drop(logger);

            log_contains_n_lines(&logfile, 1)?;
        };

        Ok(())
    }

    #[test]
    fn t_debug_msgs_are_logged_only_at_curlevel_debug() -> io::Result<()> {
        let nolog_levels = vec![
            Level::None,
            Level::UserError,
            Level::Critical,
            Level::Error,
            Level::Warn,
            Level::Info,
        ];

        for level in nolog_levels {
            let (_tmp, logfile, mut logger) = setup_logger()?;
            logger.set_loglevel(level);

            logger.log(Level::Debug, "hello")?;

            drop(logger);

            log_contains_n_lines(&logfile, 0)?;
        }

        let log_levels = vec![
            Level::Debug,
        ];

        for level in log_levels {
            let (_tmp, logfile, mut logger) = setup_logger()?;
            logger.set_loglevel(level);

            logger.log(Level::Debug, "hello")?;

            drop(logger);

            log_contains_n_lines(&logfile, 1)?;
        };

        Ok(())
    }
}
<|endoftext|>


<commit_before>// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

// Format list-like macro invocations. These are invocations whose token trees
// can be interpreted as expressions and separated by commas.
// Note that these token trees do not actually have to be interpreted as
// expressions by the compiler. An example of an invocation we would reformat is
// foo!( x, y, z ). The token x may represent an identifier in the code, but we
// interpreted as an expression.
// Macro uses which are not-list like, such as bar!(key => val), will not be
// reformatted.
// List-like invocations with parentheses will be formatted as function calls,
// and those with brackets will be formatted as array literals.

use syntax::ast;
use syntax::codemap::BytePos;
use syntax::parse::new_parser_from_tts;
use syntax::parse::parser::Parser;
use syntax::parse::token::Token;
use syntax::symbol;
use syntax::tokenstream::TokenStream;
use syntax::util::ThinVec;

use codemap::SpanUtils;
use comment::{contains_comment, FindUncommented};
use expr::{rewrite_array, rewrite_call_inner};
use rewrite::{Rewrite, RewriteContext};
use shape::{Indent, Shape};
use utils::mk_sp;

const FORCED_BRACKET_MACROS: &[&str] = &["vec!"];

// FIXME: use the enum from libsyntax?
#[derive(Clone, Copy, PartialEq, Eq)]
enum MacroStyle {
    Parens,
    Brackets,
    Braces,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MacroPosition {
    Item,
    Statement,
    Expression,
}

impl MacroStyle {
    fn opener(&self) -> &'static str {
        match *self {
            MacroStyle::Parens => "(",
            MacroStyle::Brackets => "[",
            MacroStyle::Braces => "{",
        }
    }
}

pub enum MacroArg {
    Expr(ast::Expr),
    Ty(ast::Ty),
    Pat(ast::Pat),
}

impl Rewrite for MacroArg {
    fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
        match *self {
            MacroArg::Expr(ref expr) => expr.rewrite(context, shape),
            MacroArg::Ty(ref ty) => ty.rewrite(context, shape),
            MacroArg::Pat(ref pat) => pat.rewrite(context, shape),
        }
    }
}

fn parse_macro_arg(parser: &mut Parser) -> Option<MacroArg> {
    macro_rules! parse_macro_arg {
        ($target:tt, $macro_arg:ident, $parser:ident) => {
            let mut cloned_parser = (*parser).clone();
            match cloned_parser.$parser() {
                Ok($target) => {
                    if parser.sess.span_diagnostic.has_errors() {
                        parser.sess.span_diagnostic.reset_err_count();
                    } else {
                        // Parsing succeeded.
                        *parser = cloned_parser;
                        return Some(MacroArg::$macro_arg((*$target).clone()));
                    }
                }
                Err(mut e) => {
                    e.cancel();
                    parser.sess.span_diagnostic.reset_err_count();
                }
            }
        }
    }

    parse_macro_arg!(expr, Expr, parse_expr);
    parse_macro_arg!(ty, Ty, parse_ty);
    parse_macro_arg!(pat, Pat, parse_pat);

    None
}

pub fn rewrite_macro(
    mac: &ast::Mac,
    extra_ident: Option<ast::Ident>,
    context: &RewriteContext,
    shape: Shape,
    position: MacroPosition,
) -> Option<String> {
    let context = &mut context.clone();
    context.inside_macro = true;
    if context.config.use_try_shorthand() {
        if let Some(expr) = convert_try_mac(mac, context) {
            return expr.rewrite(context, shape);
        }
    }

    let original_style = macro_style(mac, context);

    let macro_name = match extra_ident {
        None => format!("{}!", mac.node.path),
        Some(ident) => {
            if ident == symbol::keywords::Invalid.ident() {
                format!("{}!", mac.node.path)
            } else {
                format!("{}! {}", mac.node.path, ident)
            }
        }
    };

    let style = if FORCED_BRACKET_MACROS.contains(&&macro_name[..]) {
        MacroStyle::Brackets
    } else {
        original_style
    };

    let ts: TokenStream = mac.node.stream();
    if ts.is_empty() && !contains_comment(&context.snippet(mac.span)) {
        return match style {
            MacroStyle::Parens if position == MacroPosition::Item => {
                Some(format!("{}();", macro_name))
            }
            MacroStyle::Parens => Some(format!("{}()", macro_name)),
            MacroStyle::Brackets => Some(format!("{}[]", macro_name)),
            MacroStyle::Braces => Some(format!("{}{{}}", macro_name)),
        };
    }

    let mut parser = new_parser_from_tts(context.parse_session, ts.trees().collect());
    let mut arg_vec = Vec::new();
    let mut vec_with_semi = false;
    let mut trailing_comma = false;

    if MacroStyle::Braces != style {
        loop {
            match parse_macro_arg(&mut parser) {
                Some(arg) => arg_vec.push(arg),
                None => return Some(context.snippet(mac.span).to_owned()),
            }

            match parser.token {
                Token::Eof => break,
                Token::Comma => (),
                Token::Semi => {
                    // Try to parse `vec![expr; expr]`
                    if FORCED_BRACKET_MACROS.contains(&&macro_name[..]) {
                        parser.bump();
                        if parser.token != Token::Eof {
                            match parse_macro_arg(&mut parser) {
                                Some(arg) => {
                                    arg_vec.push(arg);
                                    parser.bump();
                                    if parser.token == Token::Eof && arg_vec.len() == 2 {
                                        vec_with_semi = true;
                                        break;
                                    }
                                }
                                None => return Some(context.snippet(mac.span).to_owned()),
                            }
                        }
                    }
                    return Some(context.snippet(mac.span).to_owned());
                }
                _ => return Some(context.snippet(mac.span).to_owned()),
            }

            parser.bump();

            if parser.token == Token::Eof {
                trailing_comma = true;
                break;
            }
        }
    }

    match style {
        MacroStyle::Parens => {
            // Format macro invocation as function call, forcing no trailing
            // comma because not all macros support them.
            rewrite_call_inner(
                context,
                &macro_name,
                &arg_vec.iter().map(|e| &*e).collect::<Vec<_>>()[..],
                mac.span,
                shape,
                context.config.width_heuristics().fn_call_width,
                trailing_comma,
            ).map(|rw| match position {
                MacroPosition::Item => format!("{};", rw),
                _ => rw,
            })
        }
        MacroStyle::Brackets => {
            let mac_shape = shape.offset_left(macro_name.len())?;
            // Handle special case: `vec![expr; expr]`
            if vec_with_semi {
                let (lbr, rbr) = if context.config.spaces_within_parens_and_brackets() {
                    ("[ ", " ]")
                } else {
                    ("[", "]")
                };
                // 6 = `vec!` + `; `
                let total_overhead = lbr.len() + rbr.len() + 6;
                let nested_shape = mac_shape.block_indent(context.config.tab_spaces());
                let lhs = arg_vec[0].rewrite(context, nested_shape)?;
                let rhs = arg_vec[1].rewrite(context, nested_shape)?;
                if !lhs.contains('\n') && !rhs.contains('\n')
                    && lhs.len() + rhs.len() + total_overhead <= shape.width
                {
                    Some(format!("{}{}{}; {}{}", macro_name, lbr, lhs, rhs, rbr))
                } else {
                    Some(format!(
                        "{}{}\n{}{};\n{}{}\n{}{}",
                        macro_name,
                        lbr,
                        nested_shape.indent.to_string(context.config),
                        lhs,
                        nested_shape.indent.to_string(context.config),
                        rhs,
                        shape.indent.to_string(context.config),
                        rbr
                    ))
                }
            } else {
                // If we are rewriting `vec!` macro or other special macros,
                // then we can rewrite this as an usual array literal.
                // Otherwise, we must preserve the original existence of trailing comma.
                if FORCED_BRACKET_MACROS.contains(&macro_name.as_str()) {
                    context.inside_macro = false;
                    trailing_comma = false;
                }
                // Convert `MacroArg` into `ast::Expr`, as `rewrite_array` only accepts the latter.
                let sp = mk_sp(
                    context
                        .codemap
                        .span_after(mac.span, original_style.opener()),
                    mac.span.hi() - BytePos(1),
                );
                let arg_vec = &arg_vec.iter().map(|e| &*e).collect::<Vec<_>>()[..];
                let rewrite = rewrite_array(arg_vec, sp, context, mac_shape, trailing_comma)?;

                Some(format!("{}{}", macro_name, rewrite))
            }
        }
        MacroStyle::Braces => {
            // Skip macro invocations with braces, for now.
            indent_macro_snippet(context, context.snippet(mac.span), shape.indent)
        }
    }
}

/// Tries to convert a macro use into a short hand try expression. Returns None
/// when the macro is not an instance of try! (or parsing the inner expression
/// failed).
pub fn convert_try_mac(mac: &ast::Mac, context: &RewriteContext) -> Option<ast::Expr> {
    if &format!("{}", mac.node.path)[..] == "try" {
        let ts: TokenStream = mac.node.tts.clone().into();
        let mut parser = new_parser_from_tts(context.parse_session, ts.trees().collect());

        Some(ast::Expr {
            id: ast::NodeId::new(0), // dummy value
            node: ast::ExprKind::Try(parser.parse_expr().ok()?),
            span: mac.span, // incorrect span, but shouldn't matter too much
            attrs: ThinVec::new(),
        })
    } else {
        None
    }
}

fn macro_style(mac: &ast::Mac, context: &RewriteContext) -> MacroStyle {
    let snippet = context.snippet(mac.span);
    let paren_pos = snippet.find_uncommented("(").unwrap_or(usize::max_value());
    let bracket_pos = snippet.find_uncommented("[").unwrap_or(usize::max_value());
    let brace_pos = snippet.find_uncommented("{").unwrap_or(usize::max_value());

    if paren_pos < bracket_pos && paren_pos < brace_pos {
        MacroStyle::Parens
    } else if bracket_pos < brace_pos {
        MacroStyle::Brackets
    } else {
        MacroStyle::Braces
    }
}

/// Indent each line according to the specified `indent`.
/// e.g.
/// ```rust
/// foo!{
/// x,
/// y,
/// foo(
///     a,
///     b,
///     c,
/// ),
/// }
/// ```
/// will become
/// ```rust
/// foo!{
///     x,
///     y,
///     foo(
///         a,
///         b,
///         c,
//      ),
/// }
/// ```
fn indent_macro_snippet(
    context: &RewriteContext,
    macro_str: &str,
    indent: Indent,
) -> Option<String> {
    let mut lines = macro_str.lines();
    let first_line = lines.next().map(|s| s.trim_right())?;
    let mut trimmed_lines = Vec::with_capacity(16);

    let min_prefix_space_width = lines
        .filter_map(|line| {
            let prefix_space_width = if is_empty_line(line) {
                None
            } else {
                Some(get_prefix_space_width(context, line))
            };
            trimmed_lines.push((line.trim(), prefix_space_width));
            prefix_space_width
        })
        .min()?;

    Some(
        String::from(first_line) + "\n"
            + &trimmed_lines
                .iter()
                .map(|&(line, prefix_space_width)| match prefix_space_width {
                    Some(original_indent_width) => {
                        let new_indent_width = indent.width()
                            + original_indent_width
                                .checked_sub(min_prefix_space_width)
                                .unwrap_or(0);
                        let new_indent = Indent::from_width(context.config, new_indent_width);
                        format!("{}{}", new_indent.to_string(context.config), line.trim())
                    }
                    None => String::new(),
                })
                .collect::<Vec<_>>()
                .join("\n"),
    )
}

fn get_prefix_space_width(context: &RewriteContext, s: &str) -> usize {
    let mut width = 0;
    for c in s.chars() {
        match c {
            ' ' => width += 1,
            '\t' => width += context.config.tab_spaces(),
            _ => return width,
        }
    }
    width
}

fn is_empty_line(s: &str) -> bool {
    s.is_empty() || s.chars().all(char::is_whitespace)
}
<commit_msg>Do not set inside_macro flag when converting try!() to '?'<commit_after>// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

// Format list-like macro invocations. These are invocations whose token trees
// can be interpreted as expressions and separated by commas.
// Note that these token trees do not actually have to be interpreted as
// expressions by the compiler. An example of an invocation we would reformat is
// foo!( x, y, z ). The token x may represent an identifier in the code, but we
// interpreted as an expression.
// Macro uses which are not-list like, such as bar!(key => val), will not be
// reformatted.
// List-like invocations with parentheses will be formatted as function calls,
// and those with brackets will be formatted as array literals.

use syntax::ast;
use syntax::codemap::BytePos;
use syntax::parse::new_parser_from_tts;
use syntax::parse::parser::Parser;
use syntax::parse::token::Token;
use syntax::symbol;
use syntax::tokenstream::TokenStream;
use syntax::util::ThinVec;

use codemap::SpanUtils;
use comment::{contains_comment, FindUncommented};
use expr::{rewrite_array, rewrite_call_inner};
use rewrite::{Rewrite, RewriteContext};
use shape::{Indent, Shape};
use utils::mk_sp;

const FORCED_BRACKET_MACROS: &[&str] = &["vec!"];

// FIXME: use the enum from libsyntax?
#[derive(Clone, Copy, PartialEq, Eq)]
enum MacroStyle {
    Parens,
    Brackets,
    Braces,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MacroPosition {
    Item,
    Statement,
    Expression,
}

impl MacroStyle {
    fn opener(&self) -> &'static str {
        match *self {
            MacroStyle::Parens => "(",
            MacroStyle::Brackets => "[",
            MacroStyle::Braces => "{",
        }
    }
}

pub enum MacroArg {
    Expr(ast::Expr),
    Ty(ast::Ty),
    Pat(ast::Pat),
}

impl Rewrite for MacroArg {
    fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
        match *self {
            MacroArg::Expr(ref expr) => expr.rewrite(context, shape),
            MacroArg::Ty(ref ty) => ty.rewrite(context, shape),
            MacroArg::Pat(ref pat) => pat.rewrite(context, shape),
        }
    }
}

fn parse_macro_arg(parser: &mut Parser) -> Option<MacroArg> {
    macro_rules! parse_macro_arg {
        ($target:tt, $macro_arg:ident, $parser:ident) => {
            let mut cloned_parser = (*parser).clone();
            match cloned_parser.$parser() {
                Ok($target) => {
                    if parser.sess.span_diagnostic.has_errors() {
                        parser.sess.span_diagnostic.reset_err_count();
                    } else {
                        // Parsing succeeded.
                        *parser = cloned_parser;
                        return Some(MacroArg::$macro_arg((*$target).clone()));
                    }
                }
                Err(mut e) => {
                    e.cancel();
                    parser.sess.span_diagnostic.reset_err_count();
                }
            }
        }
    }

    parse_macro_arg!(expr, Expr, parse_expr);
    parse_macro_arg!(ty, Ty, parse_ty);
    parse_macro_arg!(pat, Pat, parse_pat);

    None
}

pub fn rewrite_macro(
    mac: &ast::Mac,
    extra_ident: Option<ast::Ident>,
    context: &RewriteContext,
    shape: Shape,
    position: MacroPosition,
) -> Option<String> {
    let context = &mut context.clone();
    context.inside_macro = true;
    if context.config.use_try_shorthand() {
        if let Some(expr) = convert_try_mac(mac, context) {
            context.inside_macro = false;
            return expr.rewrite(context, shape);
        }
    }

    let original_style = macro_style(mac, context);

    let macro_name = match extra_ident {
        None => format!("{}!", mac.node.path),
        Some(ident) => {
            if ident == symbol::keywords::Invalid.ident() {
                format!("{}!", mac.node.path)
            } else {
                format!("{}! {}", mac.node.path, ident)
            }
        }
    };

    let style = if FORCED_BRACKET_MACROS.contains(&&macro_name[..]) {
        MacroStyle::Brackets
    } else {
        original_style
    };

    let ts: TokenStream = mac.node.stream();
    if ts.is_empty() && !contains_comment(&context.snippet(mac.span)) {
        return match style {
            MacroStyle::Parens if position == MacroPosition::Item => {
                Some(format!("{}();", macro_name))
            }
            MacroStyle::Parens => Some(format!("{}()", macro_name)),
            MacroStyle::Brackets => Some(format!("{}[]", macro_name)),
            MacroStyle::Braces => Some(format!("{}{{}}", macro_name)),
        };
    }

    let mut parser = new_parser_from_tts(context.parse_session, ts.trees().collect());
    let mut arg_vec = Vec::new();
    let mut vec_with_semi = false;
    let mut trailing_comma = false;

    if MacroStyle::Braces != style {
        loop {
            match parse_macro_arg(&mut parser) {
                Some(arg) => arg_vec.push(arg),
                None => return Some(context.snippet(mac.span).to_owned()),
            }

            match parser.token {
                Token::Eof => break,
                Token::Comma => (),
                Token::Semi => {
                    // Try to parse `vec![expr; expr]`
                    if FORCED_BRACKET_MACROS.contains(&&macro_name[..]) {
                        parser.bump();
                        if parser.token != Token::Eof {
                            match parse_macro_arg(&mut parser) {
                                Some(arg) => {
                                    arg_vec.push(arg);
                                    parser.bump();
                                    if parser.token == Token::Eof && arg_vec.len() == 2 {
                                        vec_with_semi = true;
                                        break;
                                    }
                                }
                                None => return Some(context.snippet(mac.span).to_owned()),
                            }
                        }
                    }
                    return Some(context.snippet(mac.span).to_owned());
                }
                _ => return Some(context.snippet(mac.span).to_owned()),
            }

            parser.bump();

            if parser.token == Token::Eof {
                trailing_comma = true;
                break;
            }
        }
    }

    match style {
        MacroStyle::Parens => {
            // Format macro invocation as function call, forcing no trailing
            // comma because not all macros support them.
            rewrite_call_inner(
                context,
                &macro_name,
                &arg_vec.iter().map(|e| &*e).collect::<Vec<_>>()[..],
                mac.span,
                shape,
                context.config.width_heuristics().fn_call_width,
                trailing_comma,
            ).map(|rw| match position {
                MacroPosition::Item => format!("{};", rw),
                _ => rw,
            })
        }
        MacroStyle::Brackets => {
            let mac_shape = shape.offset_left(macro_name.len())?;
            // Handle special case: `vec![expr; expr]`
            if vec_with_semi {
                let (lbr, rbr) = if context.config.spaces_within_parens_and_brackets() {
                    ("[ ", " ]")
                } else {
                    ("[", "]")
                };
                // 6 = `vec!` + `; `
                let total_overhead = lbr.len() + rbr.len() + 6;
                let nested_shape = mac_shape.block_indent(context.config.tab_spaces());
                let lhs = arg_vec[0].rewrite(context, nested_shape)?;
                let rhs = arg_vec[1].rewrite(context, nested_shape)?;
                if !lhs.contains('\n') && !rhs.contains('\n')
                    && lhs.len() + rhs.len() + total_overhead <= shape.width
                {
                    Some(format!("{}{}{}; {}{}", macro_name, lbr, lhs, rhs, rbr))
                } else {
                    Some(format!(
                        "{}{}\n{}{};\n{}{}\n{}{}",
                        macro_name,
                        lbr,
                        nested_shape.indent.to_string(context.config),
                        lhs,
                        nested_shape.indent.to_string(context.config),
                        rhs,
                        shape.indent.to_string(context.config),
                        rbr
                    ))
                }
            } else {
                // If we are rewriting `vec!` macro or other special macros,
                // then we can rewrite this as an usual array literal.
                // Otherwise, we must preserve the original existence of trailing comma.
                if FORCED_BRACKET_MACROS.contains(&macro_name.as_str()) {
                    context.inside_macro = false;
                    trailing_comma = false;
                }
                // Convert `MacroArg` into `ast::Expr`, as `rewrite_array` only accepts the latter.
                let sp = mk_sp(
                    context
                        .codemap
                        .span_after(mac.span, original_style.opener()),
                    mac.span.hi() - BytePos(1),
                );
                let arg_vec = &arg_vec.iter().map(|e| &*e).collect::<Vec<_>>()[..];
                let rewrite = rewrite_array(arg_vec, sp, context, mac_shape, trailing_comma)?;

                Some(format!("{}{}", macro_name, rewrite))
            }
        }
        MacroStyle::Braces => {
            // Skip macro invocations with braces, for now.
            indent_macro_snippet(context, context.snippet(mac.span), shape.indent)
        }
    }
}

/// Tries to convert a macro use into a short hand try expression. Returns None
/// when the macro is not an instance of try! (or parsing the inner expression
/// failed).
pub fn convert_try_mac(mac: &ast::Mac, context: &RewriteContext) -> Option<ast::Expr> {
    if &format!("{}", mac.node.path)[..] == "try" {
        let ts: TokenStream = mac.node.tts.clone().into();
        let mut parser = new_parser_from_tts(context.parse_session, ts.trees().collect());

        Some(ast::Expr {
            id: ast::NodeId::new(0), // dummy value
            node: ast::ExprKind::Try(parser.parse_expr().ok()?),
            span: mac.span, // incorrect span, but shouldn't matter too much
            attrs: ThinVec::new(),
        })
    } else {
        None
    }
}

fn macro_style(mac: &ast::Mac, context: &RewriteContext) -> MacroStyle {
    let snippet = context.snippet(mac.span);
    let paren_pos = snippet.find_uncommented("(").unwrap_or(usize::max_value());
    let bracket_pos = snippet.find_uncommented("[").unwrap_or(usize::max_value());
    let brace_pos = snippet.find_uncommented("{").unwrap_or(usize::max_value());

    if paren_pos < bracket_pos && paren_pos < brace_pos {
        MacroStyle::Parens
    } else if bracket_pos < brace_pos {
        MacroStyle::Brackets
    } else {
        MacroStyle::Braces
    }
}

/// Indent each line according to the specified `indent`.
/// e.g.
/// ```rust
/// foo!{
/// x,
/// y,
/// foo(
///     a,
///     b,
///     c,
/// ),
/// }
/// ```
/// will become
/// ```rust
/// foo!{
///     x,
///     y,
///     foo(
///         a,
///         b,
///         c,
//      ),
/// }
/// ```
fn indent_macro_snippet(
    context: &RewriteContext,
    macro_str: &str,
    indent: Indent,
) -> Option<String> {
    let mut lines = macro_str.lines();
    let first_line = lines.next().map(|s| s.trim_right())?;
    let mut trimmed_lines = Vec::with_capacity(16);

    let min_prefix_space_width = lines
        .filter_map(|line| {
            let prefix_space_width = if is_empty_line(line) {
                None
            } else {
                Some(get_prefix_space_width(context, line))
            };
            trimmed_lines.push((line.trim(), prefix_space_width));
            prefix_space_width
        })
        .min()?;

    Some(
        String::from(first_line) + "\n"
            + &trimmed_lines
                .iter()
                .map(|&(line, prefix_space_width)| match prefix_space_width {
                    Some(original_indent_width) => {
                        let new_indent_width = indent.width()
                            + original_indent_width
                                .checked_sub(min_prefix_space_width)
                                .unwrap_or(0);
                        let new_indent = Indent::from_width(context.config, new_indent_width);
                        format!("{}{}", new_indent.to_string(context.config), line.trim())
                    }
                    None => String::new(),
                })
                .collect::<Vec<_>>()
                .join("\n"),
    )
}

fn get_prefix_space_width(context: &RewriteContext, s: &str) -> usize {
    let mut width = 0;
    for c in s.chars() {
        match c {
            ' ' => width += 1,
            '\t' => width += context.config.tab_spaces(),
            _ => return width,
        }
    }
    width
}

fn is_empty_line(s: &str) -> bool {
    s.is_empty() || s.chars().all(char::is_whitespace)
}
<|endoftext|>


<commit_before>//! Helper macros for implementing NBT format encoding and decoding via `serde`.

macro_rules! return_expr_for_serialized_types_method {
    ($expr:expr, $func:ident($($arg:ty),*)) => {
        #[inline]
        fn $func(self, $(_: $arg,)*)
                 -> ::std::result::Result<Self::Ok, Self::Error>
        {
            $expr
        }
    };
    ($expr:expr, $func:ident($($arg:ty),*), result: $result:path) => {
        #[inline]
        fn $func(self, $(_: $arg,)*)
                 -> ::std::result::Result<$result, Self::Error>
        {
            $expr
        }
    };
    ($expr:expr, $func:ident($($arg:ty),*), where: $where:path) => {
        #[inline]
        fn $func<__T: ?Sized>(self, $(_: $arg,)*)
                              -> ::std::result::Result<Self::Ok, Self::Error>
            where __T: $where
        {
            $expr
        }
    };
}

macro_rules! return_expr_for_serialized_types_helper {
    ($expr:expr, bool) => {
        return_expr_for_serialized_types_method!{$expr, serialize_bool(bool)}
    };
    ($expr:expr, i8) => {
        return_expr_for_serialized_types_method!{$expr, serialize_i8(i8)}
    };
    ($expr:expr, i16) => {
        return_expr_for_serialized_types_method!{$expr, serialize_i16(i16)}
    };
    ($expr:expr, i32) => {
        return_expr_for_serialized_types_method!{$expr, serialize_i32(i32)}
    };
    ($expr:expr, i64) => {
        return_expr_for_serialized_types_method!{$expr, serialize_i64(i64)}
    };
    ($expr:expr, u8) => {
        return_expr_for_serialized_types_method!{$expr, serialize_u8(u8)}
    };
    ($expr:expr, u16) => {
        return_expr_for_serialized_types_method!{$expr, serialize_u16(u16)}
    };
    ($expr:expr, u32) => {
        return_expr_for_serialized_types_method!{$expr, serialize_u32(u32)}
    };
    ($expr:expr, u64) => {
        return_expr_for_serialized_types_method!{$expr, serialize_u64(u64)}
    };
    ($expr:expr, f32) => {
        return_expr_for_serialized_types_method!{$expr, serialize_f32(f32)}
    };
    ($expr:expr, f64) => {
        return_expr_for_serialized_types_method!{$expr, serialize_f64(f64)}
    };
    ($expr:expr, char) => {
        return_expr_for_serialized_types_method!{$expr, serialize_char(char)}
    };
    ($expr:expr, str) => {
        return_expr_for_serialized_types_method!{$expr, serialize_str(&str)}
    };
    ($expr:expr, bytes) => {
        return_expr_for_serialized_types_method!{$expr, serialize_bytes(&[u8])}
    };
    ($expr:expr, none) => {
        return_expr_for_serialized_types_method!{$expr, serialize_none()}
    };
    ($expr:expr, unit) => {
        return_expr_for_serialized_types_method!{$expr, serialize_unit()}
    };
    ($expr:expr, unit_struct) => {
        return_expr_for_serialized_types_method!{
            $expr, serialize_unit_struct(&'static str)
        }
    };
    ($expr:expr, unit_variant) => {
        return_expr_for_serialized_types_method!{
            $expr, serialize_unit_variant(&'static str, u32, &'static str)
        }
    };
    ($expr:expr, some) => {
        return_expr_for_serialized_types_method!{
            $expr, serialize_some(&__T),
            where: ::serde::ser::Serialize
        }
    };
    ($expr:expr, newtype_struct) => {
        return_expr_for_serialized_types_method!{
            $expr, serialize_newtype_struct(&'static str, &__T),
            where: ::serde::ser::Serialize
        }
    };
    ($expr:expr, newtype_variant) => {
        return_expr_for_serialized_types_method!{
            $expr, serialize_newtype_variant(&'static str, u32,
                                              &'static str, &__T),
            where: ::serde::ser::Serialize
        }
    };
    ($expr:expr, seq) => {
        return_expr_for_serialized_types_method!{
            $expr, serialize_seq(Option<usize>),
            result: Self::SerializeSeq
        }
    };
    ($expr:expr, tuple) => {
        return_expr_for_serialized_types_method!{
            $expr, serialize_tuple(usize),
            result: Self::SerializeTuple
        }
    };
    ($expr:expr, tuple_struct) => {
        return_expr_for_serialized_types_method!{
            $expr, serialize_tuple_struct(&'static str, usize),
            result: Self::SerializeTupleStruct
        }
    };
    ($expr:expr, tuple_variant) => {
        return_expr_for_serialized_types_method!{
            $expr, serialize_tuple_variant(&'static str, u32, &'static str,
                                            usize),
            result: Self::SerializeTupleVariant
        }
    };
    ($expr:expr, map) => {
        return_expr_for_serialized_types_method!{
            $expr, serialize_map(Option<usize>),
            result: Self::SerializeMap
        }
    };
    ($expr:expr, struct) => {
        return_expr_for_serialized_types_method!{
            $expr, serialize_struct(&'static str, usize),
            result: Self::SerializeStruct
        }
    };
    ($expr:expr, struct_variant) => {
        return_expr_for_serialized_types_method!{
            $expr, serialize_struct_variant(&'static str, u32, &'static str,
                                             usize),
            result: Self::SerializeStructVariant
        }
    };
}

/// Helper macro for implementing the `serde::se::Serializer` trait.
///
/// Implement the serializer methods for each `$type` with body `$expr`.
///
/// This macro is very similar to `serde::forward_to_deserialize`, but instead
/// of "forwarding" it allows arbitrary expressions in the body, so long as they
/// are all the same.
///
/// This macro can be used to stub out `Serializer` implementations.
macro_rules! return_expr_for_serialized_types {
    ($expr:expr; $($type:tt)*) => {
        $(return_expr_for_serialized_types_helper!{$expr, $type})*
    };
}

macro_rules! unrepresentable {
    ($($type:tt)*) => {
        $(return_expr_for_serialized_types_helper!{Err(Error::UnrepresentableType("$type")), $type})*
    };
}
<commit_msg>Fix UnrepresentableType error message<commit_after>//! Helper macros for implementing NBT format encoding and decoding via `serde`.

macro_rules! return_expr_for_serialized_types_method {
    ($expr:expr, $func:ident($($arg:ty),*)) => {
        #[inline]
        fn $func(self, $(_: $arg,)*)
                 -> ::std::result::Result<Self::Ok, Self::Error>
        {
            $expr
        }
    };
    ($expr:expr, $func:ident($($arg:ty),*), result: $result:path) => {
        #[inline]
        fn $func(self, $(_: $arg,)*)
                 -> ::std::result::Result<$result, Self::Error>
        {
            $expr
        }
    };
    ($expr:expr, $func:ident($($arg:ty),*), where: $where:path) => {
        #[inline]
        fn $func<__T: ?Sized>(self, $(_: $arg,)*)
                              -> ::std::result::Result<Self::Ok, Self::Error>
            where __T: $where
        {
            $expr
        }
    };
}

macro_rules! return_expr_for_serialized_types_helper {
    ($expr:expr, bool) => {
        return_expr_for_serialized_types_method!{$expr, serialize_bool(bool)}
    };
    ($expr:expr, i8) => {
        return_expr_for_serialized_types_method!{$expr, serialize_i8(i8)}
    };
    ($expr:expr, i16) => {
        return_expr_for_serialized_types_method!{$expr, serialize_i16(i16)}
    };
    ($expr:expr, i32) => {
        return_expr_for_serialized_types_method!{$expr, serialize_i32(i32)}
    };
    ($expr:expr, i64) => {
        return_expr_for_serialized_types_method!{$expr, serialize_i64(i64)}
    };
    ($expr:expr, u8) => {
        return_expr_for_serialized_types_method!{$expr, serialize_u8(u8)}
    };
    ($expr:expr, u16) => {
        return_expr_for_serialized_types_method!{$expr, serialize_u16(u16)}
    };
    ($expr:expr, u32) => {
        return_expr_for_serialized_types_method!{$expr, serialize_u32(u32)}
    };
    ($expr:expr, u64) => {
        return_expr_for_serialized_types_method!{$expr, serialize_u64(u64)}
    };
    ($expr:expr, f32) => {
        return_expr_for_serialized_types_method!{$expr, serialize_f32(f32)}
    };
    ($expr:expr, f64) => {
        return_expr_for_serialized_types_method!{$expr, serialize_f64(f64)}
    };
    ($expr:expr, char) => {
        return_expr_for_serialized_types_method!{$expr, serialize_char(char)}
    };
    ($expr:expr, str) => {
        return_expr_for_serialized_types_method!{$expr, serialize_str(&str)}
    };
    ($expr:expr, bytes) => {
        return_expr_for_serialized_types_method!{$expr, serialize_bytes(&[u8])}
    };
    ($expr:expr, none) => {
        return_expr_for_serialized_types_method!{$expr, serialize_none()}
    };
    ($expr:expr, unit) => {
        return_expr_for_serialized_types_method!{$expr, serialize_unit()}
    };
    ($expr:expr, unit_struct) => {
        return_expr_for_serialized_types_method!{
            $expr, serialize_unit_struct(&'static str)
        }
    };
    ($expr:expr, unit_variant) => {
        return_expr_for_serialized_types_method!{
            $expr, serialize_unit_variant(&'static str, u32, &'static str)
        }
    };
    ($expr:expr, some) => {
        return_expr_for_serialized_types_method!{
            $expr, serialize_some(&__T),
            where: ::serde::ser::Serialize
        }
    };
    ($expr:expr, newtype_struct) => {
        return_expr_for_serialized_types_method!{
            $expr, serialize_newtype_struct(&'static str, &__T),
            where: ::serde::ser::Serialize
        }
    };
    ($expr:expr, newtype_variant) => {
        return_expr_for_serialized_types_method!{
            $expr, serialize_newtype_variant(&'static str, u32,
                                              &'static str, &__T),
            where: ::serde::ser::Serialize
        }
    };
    ($expr:expr, seq) => {
        return_expr_for_serialized_types_method!{
            $expr, serialize_seq(Option<usize>),
            result: Self::SerializeSeq
        }
    };
    ($expr:expr, tuple) => {
        return_expr_for_serialized_types_method!{
            $expr, serialize_tuple(usize),
            result: Self::SerializeTuple
        }
    };
    ($expr:expr, tuple_struct) => {
        return_expr_for_serialized_types_method!{
            $expr, serialize_tuple_struct(&'static str, usize),
            result: Self::SerializeTupleStruct
        }
    };
    ($expr:expr, tuple_variant) => {
        return_expr_for_serialized_types_method!{
            $expr, serialize_tuple_variant(&'static str, u32, &'static str,
                                            usize),
            result: Self::SerializeTupleVariant
        }
    };
    ($expr:expr, map) => {
        return_expr_for_serialized_types_method!{
            $expr, serialize_map(Option<usize>),
            result: Self::SerializeMap
        }
    };
    ($expr:expr, struct) => {
        return_expr_for_serialized_types_method!{
            $expr, serialize_struct(&'static str, usize),
            result: Self::SerializeStruct
        }
    };
    ($expr:expr, struct_variant) => {
        return_expr_for_serialized_types_method!{
            $expr, serialize_struct_variant(&'static str, u32, &'static str,
                                             usize),
            result: Self::SerializeStructVariant
        }
    };
}

/// Helper macro for implementing the `serde::se::Serializer` trait.
///
/// Implement the serializer methods for each `$type` with body `$expr`.
///
/// This macro is very similar to `serde::forward_to_deserialize`, but instead
/// of "forwarding" it allows arbitrary expressions in the body, so long as they
/// are all the same.
///
/// This macro can be used to stub out `Serializer` implementations.
macro_rules! return_expr_for_serialized_types {
    ($expr:expr; $($type:tt)*) => {
        $(return_expr_for_serialized_types_helper!{$expr, $type})*
    };
}

macro_rules! unrepresentable {
    ($($type:tt)*) => {
        $(return_expr_for_serialized_types_helper!{Err(Error::UnrepresentableType(stringify!($type))), $type})*
    };
}
<|endoftext|>