<commit_before>use cairo::cairo::Cairo;
use collections::vec_deque::VecDeque;
use std::sync::Arc;
use syscall::Result;
use types::Rect;

pub trait Widget {
    fn paint_on(&self, cr: &Cairo);
    fn move_to(&self, pos: Rect) -> Result<()>;
}

pub struct WidgetTree<T> {
    paint_needed: bool,
    by_zorder: VecDeque<Arc<T>>,
    focus: Option<Arc<T>>,
}

fn ref_eq<T>(a: &T, b: &T) -> bool {
    a as *const T == b as *const T
}

impl<T: Widget> WidgetTree<T> {
    pub fn new() -> Self {
        WidgetTree {
            paint_needed: true,
            by_zorder: VecDeque::new(),
            focus: None
        }
    }

    pub fn add(&mut self, widget: Arc<T>) {
        self.by_zorder.push_front(widget.clone());
        self.focus = Some(widget);
        self.paint_needed = true;
    }

    pub fn remove(&mut self, widget: &Arc<T>) {
        let index_opt =
            self.by_zorder
                .iter()
                .position(|w| ref_eq::<T>(&*w, &*widget));

        if let Some(index) = index_opt {
            self.by_zorder.remove(index);
        }

        let has_focus =
            self.focus
                .as_ref()
                .map_or(false, |old_focus| ref_eq::<T>(&*old_focus, &*widget));

        if has_focus {
            self.focus =
                index_opt
                    .and_then(|index| self.by_zorder.get(index))
                    .or_else(|| self.by_zorder.front())
                    .map(|w| (*w).clone());
        }

        self.paint_needed = true;
    }

    pub fn move_to(&mut self, widget: &Arc<T>, pos: Rect) -> Result<()> {
        widget.move_to(pos)?;
        self.paint_needed = true;
        Ok(())
    }

    pub fn paint_on(&mut self, cr: &Cairo) {
        cr.set_source_rgb(0.0, 0.0, 0.5);
        cr.paint();

        let mut i = self.by_zorder.iter();
        while let Some(widget) = i.next_back() {
            widget.paint_on(cr);
        }

        self.paint_needed = false;
    }

    pub fn get_paint_needed(&mut self) -> bool {
        self.paint_needed
    }

    pub fn set_paint_needed(&mut self) {
        self.paint_needed = true;
    }

    pub fn get_focus_mut(&mut self) -> Option<&mut Arc<T>> {
        self.focus.as_mut()
    }
}

#[cfg(feature = "test")]
pub mod test {
    test! {
    }
}
<commit_msg>Another user mode test<commit_after>use cairo::cairo::Cairo;
use collections::vec_deque::VecDeque;
use std::sync::Arc;
use syscall::Result;
use types::Rect;

pub trait Widget {
    fn paint_on(&self, cr: &Cairo);
    fn move_to(&self, pos: Rect) -> Result<()>;
}

pub struct WidgetTree<T> {
    paint_needed: bool,
    by_zorder: VecDeque<Arc<T>>,
    focus: Option<Arc<T>>,
}

fn ref_eq<T>(a: &T, b: &T) -> bool {
    a as *const T == b as *const T
}

impl<T> WidgetTree<T> {
    pub fn new() -> Self {
        WidgetTree {
            paint_needed: true,
            by_zorder: VecDeque::new(),
            focus: None
        }
    }

    pub fn add(&mut self, widget: Arc<T>) {
        self.by_zorder.push_front(widget.clone());
        self.focus = Some(widget);
        self.paint_needed = true;
    }

    pub fn remove(&mut self, widget: &Arc<T>) {
        let index_opt =
            self.by_zorder
                .iter()
                .position(|w| ref_eq::<T>(w.as_ref(), widget.as_ref()));

        if let Some(index) = index_opt {
            self.by_zorder.remove(index);
        }

        let has_focus =
            self.focus
                .as_ref()
                .map_or(false, |old_focus| ref_eq::<T>(&*old_focus, &*widget));

        if has_focus {
            self.focus =
                index_opt
                    .and_then(|index| self.by_zorder.get(index))
                    .or_else(|| self.by_zorder.front())
                    .map(|w| (*w).clone());
        }

        self.paint_needed = true;
    }

    pub fn get_paint_needed(&mut self) -> bool {
        self.paint_needed
    }

    pub fn set_paint_needed(&mut self) {
        self.paint_needed = true;
    }

    pub fn get_focus(&mut self) -> Option<&Arc<T>> {
        self.focus.as_ref()
    }

    pub fn get_focus_mut(&mut self) -> Option<&mut Arc<T>> {
        self.focus.as_mut()
    }
}

impl<T: Widget> WidgetTree<T> {
    pub fn move_to(&mut self, widget: &Arc<T>, pos: Rect) -> Result<()> {
        widget.move_to(pos)?;
        self.paint_needed = true;
        Ok(())
    }

    pub fn paint_on(&mut self, cr: &Cairo) {
        cr.set_source_rgb(0.0, 0.0, 0.5);
        cr.paint();

        let mut i = self.by_zorder.iter();
        while let Some(widget) = i.next_back() {
            widget.paint_on(cr);
        }

        self.paint_needed = false;
    }
}

#[cfg(feature = "test")]
pub mod test {
    use super::*;

    pub trait PartialEqWith {
        type Inner;
        fn eq_with<F: FnOnce(&Self::Inner, &Self::Inner) -> bool>(&self, other: &Self, f: F) -> bool;
    }

    impl<T> PartialEqWith for Option<T> {
        type Inner = T;

        fn eq_with<F: FnOnce(&Self::Inner, &Self::Inner) -> bool>(&self, other: &Self, f: F) -> bool {
            match (self.as_ref(), other.as_ref()) {
                (Some(ref a), Some(ref b)) => f(a, b),
                (None, None) => true,
                _ => false
            }
        }
    }

    test! {
        fn add_changes_focus() {
            let mut tree = WidgetTree::new();
            assert_eq!(None, tree.get_focus());

            let one = Arc::new(1);
            tree.add(one.clone());
            assert!(Some(one).eq_with(&tree.get_focus().cloned(), |a, b| {
                ref_eq::<i32>(a.as_ref(), b.as_ref())
            }));
        }
    }
}
<|endoftext|>


<commit_before>use LalafellBot;
use listeners::ReceivesEvents;
use commands::*;
use discord::model::{Event, Message, ReactionEmoji};

use std::sync::Arc;
use std::collections::HashMap;

pub struct CommandListener<'a> {
  bot: Arc<LalafellBot>,
  commands: HashMap<Vec<String>, Box<Command<'a> + Send + Sync>>
}

impl<'a> CommandListener<'a> {
  pub fn new(bot: Arc<LalafellBot>) -> CommandListener<'a> {
    CommandListener {
      bot: bot,
      commands: Default::default()
    }
  }

  pub fn add_command<T: AsRef<str>>(&mut self, names: &[T], command: Box<Command<'a> + Send + Sync>) {
    self.commands.insert(names.iter().map(|t| t.as_ref().to_string()).collect(), command);
  }

  fn check_command(&self, message: &Message) {
    let parts: Vec<&str> = message.content.split_whitespace().collect();
    if parts.is_empty() {
      return;
    }
    let first = parts[0];
    if !first.starts_with('!') {
      return;
    }
    let command_name = &first[1..].to_lowercase();
    let params = &parts[1..];
    let (_, command) = match self.commands.iter().find(|&(names, _)| names.contains(&command_name.to_lowercase())) {
      Some(c) => c,
      None => return
    };
    let run_result = command.run(message, params);
    let command_success = run_result.is_ok();
    match run_result {
      Ok(info) => {
        match info.message {
          Some(embed) => {
            let color = if command_success { 0x196358 } else { 0x63191b };
            self.bot.discord.send_embed(message.channel_id, "", |e| embed(e).color(color)).ok();
          },
          None => {
            let emoji = if command_success { "\u{2705}" } else { "\u{274c}" };
            self.bot.discord.add_reaction(message.channel_id, message.id, ReactionEmoji::Unicode(emoji.to_string())).ok();
          }
        }
      },
      Err(CommandFailure::Internal(info)) => {
        self.bot.discord.send_embed(message.channel_id, "",
                                    |e| e.description("An internal error happened while processing this command.")).ok();
        for err in info.error.iter() {
          error!("error: {:#?}", err);
        }
      },
      Err(CommandFailure::External(info)) => {
        if let Some(embed) = info.message {
          self.bot.discord.send_embed(message.channel_id, "", embed).ok();
        }
      }
    }
  }
}

impl<'a> ReceivesEvents for CommandListener<'a> {
  fn receive(&self, event: &Event) {
    let message = match *event {
      Event::MessageCreate(ref m) => m,
      _ => return
    };
    self.check_command(message);
  }
}
<commit_msg>fix: properly color messages<commit_after>use LalafellBot;
use listeners::ReceivesEvents;
use commands::*;
use discord::model::{Event, Message, ReactionEmoji};

use std::sync::Arc;
use std::collections::HashMap;

pub struct CommandListener<'a> {
  bot: Arc<LalafellBot>,
  commands: HashMap<Vec<String>, Box<Command<'a> + Send + Sync>>
}

impl<'a> CommandListener<'a> {
  pub fn new(bot: Arc<LalafellBot>) -> CommandListener<'a> {
    CommandListener {
      bot: bot,
      commands: Default::default()
    }
  }

  pub fn add_command<T: AsRef<str>>(&mut self, names: &[T], command: Box<Command<'a> + Send + Sync>) {
    self.commands.insert(names.iter().map(|t| t.as_ref().to_string()).collect(), command);
  }

  fn check_command(&self, message: &Message) {
    let parts: Vec<&str> = message.content.split_whitespace().collect();
    if parts.is_empty() {
      return;
    }
    let first = parts[0];
    if !first.starts_with('!') {
      return;
    }
    let command_name = &first[1..].to_lowercase();
    let params = &parts[1..];
    let (_, command) = match self.commands.iter().find(|&(names, _)| names.contains(&command_name.to_lowercase())) {
      Some(c) => c,
      None => return
    };
    let run_result = command.run(message, params);
    match run_result {
      Ok(info) => match info.message {
        Some(embed) => { self.bot.discord.send_embed(message.channel_id, "", |e| embed(e).color(0x196358)).ok(); },
        None => { self.bot.discord.add_reaction(message.channel_id, message.id, ReactionEmoji::Unicode("\u{2705}".to_string())).ok(); }
      },
      Err(CommandFailure::Internal(info)) => {
        self.bot.discord.send_embed(message.channel_id, "",
                                    |e| e.description("An internal error happened while processing this command.")).ok();
        for err in info.error.iter() {
          error!("error: {:#?}", err);
        }
      },
      Err(CommandFailure::External(info)) => match info.message {
        Some(embed) => { self.bot.discord.send_embed(message.channel_id, "", |e| embed(e).color(0x63191b)).ok(); },
        None => { self.bot.discord.add_reaction(message.channel_id, message.id, ReactionEmoji::Unicode("\u{274c}".to_string())).ok(); }
      }
    }
  }
}

impl<'a> ReceivesEvents for CommandListener<'a> {
  fn receive(&self, event: &Event) {
    let message = match *event {
      Event::MessageCreate(ref m) => m,
      _ => return
    };
    self.check_command(message);
  }
}
<|endoftext|>


<commit_before>use std::io::{BufReader, Write};
use std::net::{TcpListener, TcpStream};
use std::thread;

use birch::network::NetworkConnection;
use birch::socket::IRCReader;

fn main() {
    // Hardcoding things for now just to test everything out.
    let mut stream = TcpStream::connect("irc.freenode.net:6667").unwrap();
    thread::spawn(move || {
        let mut reader = BufReader::new(stream.try_clone().unwrap());
        let mut net = NetworkConnection::new("ep`", &mut stream);
        net.initialize().unwrap();

        loop {
            let msg = reader.read_message();
            if let Ok(msg) = msg {
                println!("[birch <- \u{1b}[37;1mnet\u{1b}[0m] {}", msg);
                net.handle(&msg).expect("failed to handle message");
            } else {
                println!("read failed");
                break;
            }
        }
    });

    // TODO: hook this up
    let listener = TcpListener::bind("127.0.0.1:9123").unwrap();
    println!("listening started, ready to accept");

    for stream in listener.incoming() {
        thread::spawn(|| {
            let mut stream = stream.unwrap();
            stream.write_all(b"Hello World\r\n").unwrap();
        });
    }
}
<commit_msg>Add a TCP read timeout to network connection<commit_after>use std::io::{BufReader, Write};
use std::net::{TcpListener, TcpStream};
use std::thread;
use std::time::Duration;

use birch::network::NetworkConnection;
use birch::socket::IRCReader;

fn main() {
    // Hardcoding things for now just to test everything out.
    let mut stream = TcpStream::connect("irc.freenode.net:6667").unwrap();
    stream
        .set_read_timeout(Some(Duration::from_secs(180)))
        .unwrap();

    thread::spawn(move || {
        let mut reader = BufReader::new(stream.try_clone().unwrap());
        let mut net = NetworkConnection::new("ep`", &mut stream);
        net.initialize().unwrap();

        loop {
            let msg = reader.read_message();
            if let Ok(msg) = msg {
                println!("[birch <- \u{1b}[37;1mnet\u{1b}[0m] {}", msg);
                net.handle(&msg).expect("failed to handle message");
            } else {
                println!("read failed");
                break;
            }
        }
    });

    // TODO: hook this up
    let listener = TcpListener::bind("127.0.0.1:9123").unwrap();
    println!("listening started, ready to accept");

    for stream in listener.incoming() {
        thread::spawn(|| {
            let mut stream = stream.unwrap();
            stream.write_all(b"Hello World\r\n").unwrap();
        });
    }
}
<|endoftext|>


<commit_before>use std::comm::SharedChan;
use std::hashmap::HashMap;
use std::hash::Hash;

fn main() {
    // Reading 10 books from Project Gutenberg
    let mut docs: ~[~str] = ~[~"books/Beowulf.txt", ~"books/Adventures_in_Wonderland.txt", ~"books/Pride_and_Prejudice.txt",
                                ~"books/herlock_Holmes.txt", ~"books/The_Prince.txt", ~"books/Dorian_Gray.txt", ~"books/Dracula.txt",
                                ~"books/Dubliners.txt", ~"books/Great_Expectations.txt", ~"books/Siddhartha.txt"];

    docs = docs.map(|file| {
        readFile(file.to_owned())
    });

    // Defining instance of mapper to get word counts
    fn mapper(doc: ~str) -> ~[(~str, uint)] {
        let words: ~[~str] = doc.split_iter(' ')
            .filter(|&x| x != "")
            .map(|x| {
                x.to_owned()
            }).collect();

        let mut ret: ~[(~str, uint)] = ~[];
        for w in words.iter() {
            let tup: (~str, uint) = (w.to_str(), 1);
            ret.push(tup);
        }

        ret
    }

    // Defining instance of reducer to get word counts
    fn reducer(key: ~str, vals: ~[uint]) -> ~[(~str, uint)] {
        let mut result: uint = 0;
        for val in vals.iter() {
            result += *val;
        }
        ~[(key, result)]
    }

    // Launching job
    docs.mapreduce::<~str,uint>(mapper, reducer);

}

// Exposing trait
trait MapReduce {
    fn mapreduce<K2: Clone + Send + Hash + Equiv<K2> + Eq, V2: Clone + Send>( &self, extern fn(~str) -> ~[(K2, V2)], extern fn(K2, ~[V2]) -> ~[(K2, V2)] );
}

// Implementation of mapreduce trait
impl MapReduce for ~[~str] {
    fn mapreduce<K2: Clone + Send + Hash + Equiv<K2> + Eq, V2: Clone + Send>( &self, mapper: extern fn(~str) -> ~[(K2, V2)], reducer: extern fn(K2, ~[V2]) -> ~[(K2, V2)] ) {
        // First we map in parallel
        let (port, chan): (Port<~[(K2, V2)]>, Chan<~[(K2, V2)]>) = stream();
        let chan = SharedChan::new(chan);
        let mut chans: int = 0;
        for doc in self.iter() {
            let child_chan = chan.clone();
            let doc_owned = doc.clone();
            chans += 1;
            do spawn {
                let ivals: ~[(K2, V2)] = mapper(doc_owned.clone());
                child_chan.send(ivals);
            }
        }

        // Aggregate intermediate keys
        let mut key_vals_map: HashMap<K2, ~[V2]> = HashMap::new();
        for _ in range(0, chans) {
            let ivals: ~[(K2, V2)] = port.recv();

            for ival in ivals.iter() {

		let mut key: K2;
		let mut val: V2;
	    	match (*ival).clone() {
		      (a, b) => { key = a; val = b;},
		}

                if key_vals_map.contains_key_equiv(&key) {
                    let list = key_vals_map.get_mut(&key);
                    list.push(val);
                } else {
                    key_vals_map.find_or_insert(key, ~[val]);
                }
            }
        }

        // Finally, reduce in parallel
        chans = 0;
        key_vals_map.each_key(|key| {
                let values = key_vals_map.get(key);
                let child_chan = chan.clone();
                let key_owned = key.clone();
                let values_owned = values.clone();
                chans += 1;
                do spawn {
                    let rvals: ~[(K2, V2)] = reducer(key_owned.clone(), values_owned.clone());
                    child_chan.send(rvals);
                }
                true
            });

        // Print reduced values
        for _ in range(0, chans) {
            let rvals: ~[(K2, V2)] = port.recv();
            println(fmt!("%?", rvals));
        }
    }
}

// Auxiliary function to read entire file
fn readFile(filename: ~str) -> ~str {
    let contents = std::io::read_whole_file_str(&std::path::PosixPath{
        is_absolute: false,
        components: ~[filename]
    });

    let ret = match contents {
        Ok(T) => T,
        _ => ~""
    };
    ret
}
<commit_msg>fixed typo in filename<commit_after>use std::comm::SharedChan;
use std::hashmap::HashMap;
use std::hash::Hash;

fn main() {
    // Reading 10 books from Project Gutenberg
    let mut docs: ~[~str] = ~[~"books/Beowulf.txt", ~"books/Adventures_in_Wonderland.txt", ~"books/Pride_and_Prejudice.txt",
                                ~"books/Sherlock_Holmes.txt", ~"books/The_Prince.txt", ~"books/Dorian_Gray.txt", ~"books/Dracula.txt",
                                ~"books/Dubliners.txt", ~"books/Great_Expectations.txt", ~"books/Siddhartha.txt"];

    docs = docs.map(|file| {
        readFile(file.to_owned())
    });

    // Defining instance of mapper to get word counts
    fn mapper(doc: ~str) -> ~[(~str, uint)] {
        let words: ~[~str] = doc.split_iter(' ')
            .filter(|&x| x != "")
            .map(|x| {
                x.to_owned()
            }).collect();

        let mut ret: ~[(~str, uint)] = ~[];
        for w in words.iter() {
            let tup: (~str, uint) = (w.to_str(), 1);
            ret.push(tup);
        }

        ret
    }

    // Defining instance of reducer to get word counts
    fn reducer(key: ~str, vals: ~[uint]) -> ~[(~str, uint)] {
        let mut result: uint = 0;
        for val in vals.iter() {
            result += *val;
        }
        ~[(key, result)]
    }

    // Launching job
    docs.mapreduce::<~str,uint>(mapper, reducer);

}

// Exposing trait
trait MapReduce {
    fn mapreduce<K2: Clone + Send + Hash + Equiv<K2> + Eq, V2: Clone + Send>( &self, extern fn(~str) -> ~[(K2, V2)], extern fn(K2, ~[V2]) -> ~[(K2, V2)] );
}

// Implementation of mapreduce trait
impl MapReduce for ~[~str] {
    fn mapreduce<K2: Clone + Send + Hash + Equiv<K2> + Eq, V2: Clone + Send>( &self, mapper: extern fn(~str) -> ~[(K2, V2)], reducer: extern fn(K2, ~[V2]) -> ~[(K2, V2)] ) {
        // First we map in parallel
        let (port, chan): (Port<~[(K2, V2)]>, Chan<~[(K2, V2)]>) = stream();
        let chan = SharedChan::new(chan);
        let mut chans: int = 0;
        for doc in self.iter() {
            let child_chan = chan.clone();
            let doc_owned = doc.clone();
            chans += 1;
            do spawn {
                let ivals: ~[(K2, V2)] = mapper(doc_owned.clone());
                child_chan.send(ivals);
            }
        }

        // Aggregate intermediate keys
        let mut key_vals_map: HashMap<K2, ~[V2]> = HashMap::new();
        for _ in range(0, chans) {
            let ivals: ~[(K2, V2)] = port.recv();

            for ival in ivals.iter() {

		let mut key: K2;
		let mut val: V2;
	    	match (*ival).clone() {
		      (a, b) => { key = a; val = b;},
		}

                if key_vals_map.contains_key_equiv(&key) {
                    let list = key_vals_map.get_mut(&key);
                    list.push(val);
                } else {
                    key_vals_map.find_or_insert(key, ~[val]);
                }
            }
        }

        // Finally, reduce in parallel
        chans = 0;
        key_vals_map.each_key(|key| {
                let values = key_vals_map.get(key);
                let child_chan = chan.clone();
                let key_owned = key.clone();
                let values_owned = values.clone();
                chans += 1;
                do spawn {
                    let rvals: ~[(K2, V2)] = reducer(key_owned.clone(), values_owned.clone());
                    child_chan.send(rvals);
                }
                true
            });

        // Print reduced values
        for _ in range(0, chans) {
            let rvals: ~[(K2, V2)] = port.recv();
            println(fmt!("%?", rvals));
        }
    }
}

// Auxiliary function to read entire file
fn readFile(filename: ~str) -> ~str {
    let contents = std::io::read_whole_file_str(&std::path::PosixPath{
        is_absolute: false,
        components: ~[filename]
    });

    let ret = match contents {
        Ok(T) => T,
        _ => ~""
    };
    ret
}
<|endoftext|>


<commit_before>use cairo;
use markup5ever::local_name;
use std::cell::RefCell;
use std::f64;

use crate::allowed_url::Fragment;
use crate::aspect_ratio::*;
use crate::bbox::*;
use crate::coord_units::CoordUnits;
use crate::drawing_ctx::{DrawingCtx, NodeStack};
use crate::error::{AttributeResultExt, PaintServerError, RenderingError};
use crate::float_eq_cairo::ApproxEqCairo;
use crate::length::*;
use crate::node::*;
use crate::paint_server::{PaintSource, ResolvedPaintSource};
use crate::parsers::ParseValue;
use crate::properties::ComputedValues;
use crate::property_bag::PropertyBag;
use crate::rect::RectangleExt;
use crate::unit_interval::UnitInterval;
use crate::viewbox::*;

coord_units!(PatternUnits, CoordUnits::ObjectBoundingBox);
coord_units!(PatternContentUnits, CoordUnits::UserSpaceOnUse);

#[derive(Clone, Default)]
pub struct NodePattern {
    pub units: Option<PatternUnits>,
    pub content_units: Option<PatternContentUnits>,
    // This Option<Option<ViewBox>> is a bit strange.  We want a field
    // with value None to mean, "this field isn't resolved yet".  However,
    // the vbox can very well be *not* specified in the SVG file.
    // In that case, the fully resolved pattern will have a .vbox=Some(None) value.
    pub vbox: Option<Option<ViewBox>>,
    pub preserve_aspect_ratio: Option<AspectRatio>,
    pub affine: Option<cairo::Matrix>,
    pub x: Option<LengthHorizontal>,
    pub y: Option<LengthVertical>,
    pub width: Option<LengthHorizontal>,
    pub height: Option<LengthVertical>,

    // Point back to our corresponding node, or to the fallback node which has children.
    // If the value is None, it means we are fully resolved and didn't find any children
    // among the fallbacks.
    pub node: RefCell<Option<RsvgNode>>,

    pub fallback: Option<Fragment>,
}

impl NodeTrait for NodePattern {
    fn set_atts(&mut self, _: Option<&RsvgNode>, pbag: &PropertyBag<'_>) -> NodeResult {
        for (attr, value) in pbag.iter() {
            match attr {
                local_name!("patternUnits") => self.units = Some(attr.parse(value)?),
                local_name!("patternContentUnits") => self.content_units = Some(attr.parse(value)?),
                local_name!("viewBox") => self.vbox = Some(Some(attr.parse(value)?)),
                local_name!("preserveAspectRatio") => {
                    self.preserve_aspect_ratio = Some(attr.parse(value)?)
                }
                local_name!("patternTransform") => self.affine = Some(attr.parse(value)?),
                local_name!("xlink:href") => {
                    self.fallback = Some(Fragment::parse(value).attribute(attr)?);
                }
                local_name!("x") => self.x = Some(attr.parse(value)?),
                local_name!("y") => self.y = Some(attr.parse(value)?),
                local_name!("width") => {
                    self.width =
                        Some(attr.parse_and_validate(value, LengthHorizontal::check_nonnegative)?)
                }
                local_name!("height") => {
                    self.height =
                        Some(attr.parse_and_validate(value, LengthVertical::check_nonnegative)?)
                }
                _ => (),
            }
        }

        Ok(())
    }

    fn overflow_hidden(&self) -> bool {
        true
    }
}

impl PaintSource for NodePattern {
    type Resolved = NodePattern;

    fn resolve(
        &self,
        node: &RsvgNode,
        draw_ctx: &mut DrawingCtx,
    ) -> Result<Self::Resolved, PaintServerError> {

        let mut result = node.borrow().get_impl::<NodePattern>().clone();
        *result.node.borrow_mut() = Some(node.clone());

        let mut stack = NodeStack::new();

        while !result.is_resolved() {
            if let Some(ref fallback) = result.fallback {
                if let Some(acquired) = draw_ctx
                    .acquired_nodes()
                    .get_node_of_type(fallback, NodeType::Pattern)
                {
                    let a_node = acquired.get();

                    if stack.contains(a_node) {
                        return Err(PaintServerError::CircularReference(fallback.clone()));
                    }

                    let node_data = a_node.borrow();

                    let fallback_pattern = node_data.get_impl::<NodePattern>();
                    *fallback_pattern.node.borrow_mut() = Some(a_node.clone());

                    result = result.resolve_from_fallback(fallback_pattern);

                    stack.push(a_node);
                } else {
                    result = result.resolve_from_defaults();
                }
            } else {
                result = result.resolve_from_defaults();
            }
        }

        Ok(result)
    }
}

impl ResolvedPaintSource for NodePattern {
    fn set_pattern_on_draw_context(
        self,
        values: &ComputedValues,
        draw_ctx: &mut DrawingCtx,
        _opacity: &UnitInterval,
        bbox: &BoundingBox,
    ) -> Result<bool, RenderingError> {
        assert!(self.is_resolved());

        if self.node.borrow().is_none() {
            // This means we didn't find any children among the fallbacks,
            // so there is nothing to render.
            return Ok(false);
        }

        let units = self.units.unwrap();
        let content_units = self.content_units.unwrap();
        let pattern_affine = self.affine.unwrap();
        let vbox = self.vbox.unwrap();
        let preserve_aspect_ratio = self.preserve_aspect_ratio.unwrap();

        let (pattern_x, pattern_y, pattern_width, pattern_height) = {
            let params = if units == PatternUnits(CoordUnits::ObjectBoundingBox) {
                draw_ctx.push_view_box(1.0, 1.0)
            } else {
                draw_ctx.get_view_params()
            };

            let pattern_x = self.x.unwrap().normalize(values, &params);
            let pattern_y = self.y.unwrap().normalize(values, &params);
            let pattern_width = self.width.unwrap().normalize(values, &params);
            let pattern_height = self.height.unwrap().normalize(values, &params);

            (pattern_x, pattern_y, pattern_width, pattern_height)
        };

        // Work out the size of the rectangle so it takes into account the object bounding box

        let bbwscale: f64;
        let bbhscale: f64;

        match units {
            PatternUnits(CoordUnits::ObjectBoundingBox) => {
                let bbrect = bbox.rect.unwrap();
                bbwscale = bbrect.width;
                bbhscale = bbrect.height;
            }

            PatternUnits(CoordUnits::UserSpaceOnUse) => {
                bbwscale = 1.0;
                bbhscale = 1.0;
            }
        }

        let cr = draw_ctx.get_cairo_context();
        let affine = cr.get_matrix();
        let taffine = cairo::Matrix::multiply(&pattern_affine, &affine);

        let mut scwscale = (taffine.xx * taffine.xx + taffine.xy * taffine.xy).sqrt();
        let mut schscale = (taffine.yx * taffine.yx + taffine.yy * taffine.yy).sqrt();

        let pw: i32 = (pattern_width * bbwscale * scwscale) as i32;
        let ph: i32 = (pattern_height * bbhscale * schscale) as i32;

        let scaled_width = pattern_width * bbwscale;
        let scaled_height = pattern_height * bbhscale;

        if scaled_width.abs() < f64::EPSILON
            || scaled_height.abs() < f64::EPSILON
            || pw < 1
            || ph < 1
        {
            return Ok(false);
        }

        scwscale = f64::from(pw) / scaled_width;
        schscale = f64::from(ph) / scaled_height;

        let mut affine: cairo::Matrix = cairo::Matrix::identity();

        // Create the pattern coordinate system
        match units {
            PatternUnits(CoordUnits::ObjectBoundingBox) => {
                let bbrect = bbox.rect.unwrap();
                affine.translate(
                    bbrect.x + pattern_x * bbrect.width,
                    bbrect.y + pattern_y * bbrect.height,
                );
            }

            PatternUnits(CoordUnits::UserSpaceOnUse) => {
                affine.translate(pattern_x, pattern_y);
            }
        }

        // Apply the pattern transform
        affine = cairo::Matrix::multiply(&affine, &pattern_affine);

        let mut caffine: cairo::Matrix;

        // Create the pattern contents coordinate system
        let _params = if let Some(vbox) = vbox {
            // If there is a vbox, use that
            let (mut x, mut y, w, h) = preserve_aspect_ratio.compute(
                &vbox,
                &cairo::Rectangle::new(
                    0.0,
                    0.0,
                    pattern_width * bbwscale,
                    pattern_height * bbhscale,
                ),
            );

            x -= vbox.x * w / vbox.width;
            y -= vbox.y * h / vbox.height;

            caffine = cairo::Matrix::new(w / vbox.width, 0.0, 0.0, h / vbox.height, x, y);

            draw_ctx.push_view_box(vbox.width, vbox.height)
        } else if content_units == PatternContentUnits(CoordUnits::ObjectBoundingBox) {
            // If coords are in terms of the bounding box, use them
            let bbrect = bbox.rect.unwrap();

            caffine = cairo::Matrix::identity();
            caffine.scale(bbrect.width, bbrect.height);

            draw_ctx.push_view_box(1.0, 1.0)
        } else {
            caffine = cairo::Matrix::identity();
            draw_ctx.get_view_params()
        };

        if !scwscale.approx_eq_cairo(1.0) || !schscale.approx_eq_cairo(1.0) {
            let mut scalematrix = cairo::Matrix::identity();
            scalematrix.scale(scwscale, schscale);
            caffine = cairo::Matrix::multiply(&caffine, &scalematrix);

            scalematrix = cairo::Matrix::identity();
            scalematrix.scale(1.0 / scwscale, 1.0 / schscale);

            affine = cairo::Matrix::multiply(&scalematrix, &affine);
        }

        // Draw to another surface

        let cr_save = draw_ctx.get_cairo_context();

        let surface = cr_save
            .get_target()
            .create_similar(cairo::Content::ColorAlpha, pw, ph);

        let cr_pattern = cairo::Context::new(&surface);

        draw_ctx.set_cairo_context(&cr_pattern);

        // Set up transformations to be determined by the contents units

        // Draw everything
        let pattern_node_borrow = self.node.borrow();
        let pattern_node = pattern_node_borrow.as_ref().unwrap();
        let pattern_cascaded = CascadedValues::new_from_node(pattern_node);
        let pattern_values = pattern_cascaded.get();

        cr_pattern.set_matrix(caffine);

        let res = draw_ctx.with_discrete_layer(&pattern_node, pattern_values, false, &mut |dc| {
            pattern_node.draw_children(&pattern_cascaded, dc, false)
        });

        // Return to the original coordinate system and rendering context

        draw_ctx.set_cairo_context(&cr_save);

        // Set the final surface as a Cairo pattern into the Cairo context

        let surface_pattern = cairo::SurfacePattern::create(&surface);
        surface_pattern.set_extend(cairo::Extend::Repeat);

        let mut matrix = affine;
        matrix.invert();

        surface_pattern.set_matrix(matrix);
        surface_pattern.set_filter(cairo::Filter::Best);

        cr_save.set_source(&surface_pattern);

        res.and_then(|_| Ok(true))
    }
}

impl NodePattern {
    fn is_resolved(&self) -> bool {
        self.units.is_some()
            && self.content_units.is_some()
            && self.vbox.is_some()
            && self.preserve_aspect_ratio.is_some()
            && self.affine.is_some()
            && self.x.is_some()
            && self.y.is_some()
            && self.width.is_some()
            && self.height.is_some()
            && self.children_are_resolved()
    }

    fn resolve_from_fallback(&self, fallback: &NodePattern) -> NodePattern {
        let units = self.units.or(fallback.units);
        let content_units = self.content_units.or(fallback.content_units);
        let vbox = self.vbox.or(fallback.vbox);
        let preserve_aspect_ratio = self.preserve_aspect_ratio.or(fallback.preserve_aspect_ratio);
        let affine = self.affine.or(fallback.affine);
        let x = self.x.or(fallback.x);
        let y = self.y.or(fallback.y);
        let width = self.width.or(fallback.width);
        let height = self.height.or(fallback.height);

        let node = if !self.children_are_resolved() {
            fallback.node.clone()
        } else {
            self.node.clone()
        };

        let fallback = fallback.fallback.clone();

        NodePattern {
            units,
            content_units,
            vbox,
            preserve_aspect_ratio,
            affine,
            x,
            y,
            width,
            height,
            node,
            fallback,
        }
    }

    fn resolve_from_defaults(&self) -> NodePattern {
        let units = self.units.or(Some(PatternUnits::default()));
        let content_units = self.content_units.or(Some(PatternContentUnits::default()));
        let vbox = self.vbox.or(Some(None));
        let preserve_aspect_ratio = self.preserve_aspect_ratio.or(Some(AspectRatio::default()));
        let affine = self.affine.or(Some(cairo::Matrix::identity()));
        let x = self.x.or(Some(Default::default()));
        let y = self.y.or(Some(Default::default()));
        let width = self.width.or(Some(Default::default()));
        let height = self.height.or(Some(Default::default()));
        let node = self.node.clone();
        let fallback = None;

        NodePattern {
            units,
            content_units,
            vbox,
            preserve_aspect_ratio,
            affine,
            x,
            y,
            width,
            height,
            node,
            fallback,
        }
    }

    fn children_are_resolved(&self) -> bool {
        if let Some(ref node) = *self.node.borrow() {
            node.has_children()
        } else {
            // We are an empty pattern; there is nothing further that
            // can be resolved for children.
            true
        }
    }
}

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

    #[test]
    fn pattern_resolved_from_defaults_is_really_resolved() {
        let pat = NodePattern::default();
        let res = pat.resolve_from_defaults();
        assert!(res.is_resolved());
    }
}
<commit_msg>NodePattern: make fields private<commit_after>use cairo;
use markup5ever::local_name;
use std::cell::RefCell;
use std::f64;

use crate::allowed_url::Fragment;
use crate::aspect_ratio::*;
use crate::bbox::*;
use crate::coord_units::CoordUnits;
use crate::drawing_ctx::{DrawingCtx, NodeStack};
use crate::error::{AttributeResultExt, PaintServerError, RenderingError};
use crate::float_eq_cairo::ApproxEqCairo;
use crate::length::*;
use crate::node::*;
use crate::paint_server::{PaintSource, ResolvedPaintSource};
use crate::parsers::ParseValue;
use crate::properties::ComputedValues;
use crate::property_bag::PropertyBag;
use crate::rect::RectangleExt;
use crate::unit_interval::UnitInterval;
use crate::viewbox::*;

coord_units!(PatternUnits, CoordUnits::ObjectBoundingBox);
coord_units!(PatternContentUnits, CoordUnits::UserSpaceOnUse);

#[derive(Clone, Default)]
pub struct NodePattern {
    units: Option<PatternUnits>,
    content_units: Option<PatternContentUnits>,
    // This Option<Option<ViewBox>> is a bit strange.  We want a field
    // with value None to mean, "this field isn't resolved yet".  However,
    // the vbox can very well be *not* specified in the SVG file.
    // In that case, the fully resolved pattern will have a .vbox=Some(None) value.
    vbox: Option<Option<ViewBox>>,
    preserve_aspect_ratio: Option<AspectRatio>,
    affine: Option<cairo::Matrix>,
    x: Option<LengthHorizontal>,
    y: Option<LengthVertical>,
    width: Option<LengthHorizontal>,
    height: Option<LengthVertical>,

    // Point back to our corresponding node, or to the fallback node which has children.
    // If the value is None, it means we are fully resolved and didn't find any children
    // among the fallbacks.
    node: RefCell<Option<RsvgNode>>,

    fallback: Option<Fragment>,
}

impl NodeTrait for NodePattern {
    fn set_atts(&mut self, _: Option<&RsvgNode>, pbag: &PropertyBag<'_>) -> NodeResult {
        for (attr, value) in pbag.iter() {
            match attr {
                local_name!("patternUnits") => self.units = Some(attr.parse(value)?),
                local_name!("patternContentUnits") => self.content_units = Some(attr.parse(value)?),
                local_name!("viewBox") => self.vbox = Some(Some(attr.parse(value)?)),
                local_name!("preserveAspectRatio") => {
                    self.preserve_aspect_ratio = Some(attr.parse(value)?)
                }
                local_name!("patternTransform") => self.affine = Some(attr.parse(value)?),
                local_name!("xlink:href") => {
                    self.fallback = Some(Fragment::parse(value).attribute(attr)?);
                }
                local_name!("x") => self.x = Some(attr.parse(value)?),
                local_name!("y") => self.y = Some(attr.parse(value)?),
                local_name!("width") => {
                    self.width =
                        Some(attr.parse_and_validate(value, LengthHorizontal::check_nonnegative)?)
                }
                local_name!("height") => {
                    self.height =
                        Some(attr.parse_and_validate(value, LengthVertical::check_nonnegative)?)
                }
                _ => (),
            }
        }

        Ok(())
    }

    fn overflow_hidden(&self) -> bool {
        true
    }
}

impl PaintSource for NodePattern {
    type Resolved = NodePattern;

    fn resolve(
        &self,
        node: &RsvgNode,
        draw_ctx: &mut DrawingCtx,
    ) -> Result<Self::Resolved, PaintServerError> {

        let mut result = node.borrow().get_impl::<NodePattern>().clone();
        *result.node.borrow_mut() = Some(node.clone());

        let mut stack = NodeStack::new();

        while !result.is_resolved() {
            if let Some(ref fallback) = result.fallback {
                if let Some(acquired) = draw_ctx
                    .acquired_nodes()
                    .get_node_of_type(fallback, NodeType::Pattern)
                {
                    let a_node = acquired.get();

                    if stack.contains(a_node) {
                        return Err(PaintServerError::CircularReference(fallback.clone()));
                    }

                    let node_data = a_node.borrow();

                    let fallback_pattern = node_data.get_impl::<NodePattern>();
                    *fallback_pattern.node.borrow_mut() = Some(a_node.clone());

                    result = result.resolve_from_fallback(fallback_pattern);

                    stack.push(a_node);
                } else {
                    result = result.resolve_from_defaults();
                }
            } else {
                result = result.resolve_from_defaults();
            }
        }

        Ok(result)
    }
}

impl ResolvedPaintSource for NodePattern {
    fn set_pattern_on_draw_context(
        self,
        values: &ComputedValues,
        draw_ctx: &mut DrawingCtx,
        _opacity: &UnitInterval,
        bbox: &BoundingBox,
    ) -> Result<bool, RenderingError> {
        assert!(self.is_resolved());

        if self.node.borrow().is_none() {
            // This means we didn't find any children among the fallbacks,
            // so there is nothing to render.
            return Ok(false);
        }

        let units = self.units.unwrap();
        let content_units = self.content_units.unwrap();
        let pattern_affine = self.affine.unwrap();
        let vbox = self.vbox.unwrap();
        let preserve_aspect_ratio = self.preserve_aspect_ratio.unwrap();

        let (pattern_x, pattern_y, pattern_width, pattern_height) = {
            let params = if units == PatternUnits(CoordUnits::ObjectBoundingBox) {
                draw_ctx.push_view_box(1.0, 1.0)
            } else {
                draw_ctx.get_view_params()
            };

            let pattern_x = self.x.unwrap().normalize(values, &params);
            let pattern_y = self.y.unwrap().normalize(values, &params);
            let pattern_width = self.width.unwrap().normalize(values, &params);
            let pattern_height = self.height.unwrap().normalize(values, &params);

            (pattern_x, pattern_y, pattern_width, pattern_height)
        };

        // Work out the size of the rectangle so it takes into account the object bounding box

        let bbwscale: f64;
        let bbhscale: f64;

        match units {
            PatternUnits(CoordUnits::ObjectBoundingBox) => {
                let bbrect = bbox.rect.unwrap();
                bbwscale = bbrect.width;
                bbhscale = bbrect.height;
            }

            PatternUnits(CoordUnits::UserSpaceOnUse) => {
                bbwscale = 1.0;
                bbhscale = 1.0;
            }
        }

        let cr = draw_ctx.get_cairo_context();
        let affine = cr.get_matrix();
        let taffine = cairo::Matrix::multiply(&pattern_affine, &affine);

        let mut scwscale = (taffine.xx * taffine.xx + taffine.xy * taffine.xy).sqrt();
        let mut schscale = (taffine.yx * taffine.yx + taffine.yy * taffine.yy).sqrt();

        let pw: i32 = (pattern_width * bbwscale * scwscale) as i32;
        let ph: i32 = (pattern_height * bbhscale * schscale) as i32;

        let scaled_width = pattern_width * bbwscale;
        let scaled_height = pattern_height * bbhscale;

        if scaled_width.abs() < f64::EPSILON
            || scaled_height.abs() < f64::EPSILON
            || pw < 1
            || ph < 1
        {
            return Ok(false);
        }

        scwscale = f64::from(pw) / scaled_width;
        schscale = f64::from(ph) / scaled_height;

        let mut affine: cairo::Matrix = cairo::Matrix::identity();

        // Create the pattern coordinate system
        match units {
            PatternUnits(CoordUnits::ObjectBoundingBox) => {
                let bbrect = bbox.rect.unwrap();
                affine.translate(
                    bbrect.x + pattern_x * bbrect.width,
                    bbrect.y + pattern_y * bbrect.height,
                );
            }

            PatternUnits(CoordUnits::UserSpaceOnUse) => {
                affine.translate(pattern_x, pattern_y);
            }
        }

        // Apply the pattern transform
        affine = cairo::Matrix::multiply(&affine, &pattern_affine);

        let mut caffine: cairo::Matrix;

        // Create the pattern contents coordinate system
        let _params = if let Some(vbox) = vbox {
            // If there is a vbox, use that
            let (mut x, mut y, w, h) = preserve_aspect_ratio.compute(
                &vbox,
                &cairo::Rectangle::new(
                    0.0,
                    0.0,
                    pattern_width * bbwscale,
                    pattern_height * bbhscale,
                ),
            );

            x -= vbox.x * w / vbox.width;
            y -= vbox.y * h / vbox.height;

            caffine = cairo::Matrix::new(w / vbox.width, 0.0, 0.0, h / vbox.height, x, y);

            draw_ctx.push_view_box(vbox.width, vbox.height)
        } else if content_units == PatternContentUnits(CoordUnits::ObjectBoundingBox) {
            // If coords are in terms of the bounding box, use them
            let bbrect = bbox.rect.unwrap();

            caffine = cairo::Matrix::identity();
            caffine.scale(bbrect.width, bbrect.height);

            draw_ctx.push_view_box(1.0, 1.0)
        } else {
            caffine = cairo::Matrix::identity();
            draw_ctx.get_view_params()
        };

        if !scwscale.approx_eq_cairo(1.0) || !schscale.approx_eq_cairo(1.0) {
            let mut scalematrix = cairo::Matrix::identity();
            scalematrix.scale(scwscale, schscale);
            caffine = cairo::Matrix::multiply(&caffine, &scalematrix);

            scalematrix = cairo::Matrix::identity();
            scalematrix.scale(1.0 / scwscale, 1.0 / schscale);

            affine = cairo::Matrix::multiply(&scalematrix, &affine);
        }

        // Draw to another surface

        let cr_save = draw_ctx.get_cairo_context();

        let surface = cr_save
            .get_target()
            .create_similar(cairo::Content::ColorAlpha, pw, ph);

        let cr_pattern = cairo::Context::new(&surface);

        draw_ctx.set_cairo_context(&cr_pattern);

        // Set up transformations to be determined by the contents units

        // Draw everything
        let pattern_node_borrow = self.node.borrow();
        let pattern_node = pattern_node_borrow.as_ref().unwrap();
        let pattern_cascaded = CascadedValues::new_from_node(pattern_node);
        let pattern_values = pattern_cascaded.get();

        cr_pattern.set_matrix(caffine);

        let res = draw_ctx.with_discrete_layer(&pattern_node, pattern_values, false, &mut |dc| {
            pattern_node.draw_children(&pattern_cascaded, dc, false)
        });

        // Return to the original coordinate system and rendering context

        draw_ctx.set_cairo_context(&cr_save);

        // Set the final surface as a Cairo pattern into the Cairo context

        let surface_pattern = cairo::SurfacePattern::create(&surface);
        surface_pattern.set_extend(cairo::Extend::Repeat);

        let mut matrix = affine;
        matrix.invert();

        surface_pattern.set_matrix(matrix);
        surface_pattern.set_filter(cairo::Filter::Best);

        cr_save.set_source(&surface_pattern);

        res.and_then(|_| Ok(true))
    }
}

impl NodePattern {
    fn is_resolved(&self) -> bool {
        self.units.is_some()
            && self.content_units.is_some()
            && self.vbox.is_some()
            && self.preserve_aspect_ratio.is_some()
            && self.affine.is_some()
            && self.x.is_some()
            && self.y.is_some()
            && self.width.is_some()
            && self.height.is_some()
            && self.children_are_resolved()
    }

    fn resolve_from_fallback(&self, fallback: &NodePattern) -> NodePattern {
        let units = self.units.or(fallback.units);
        let content_units = self.content_units.or(fallback.content_units);
        let vbox = self.vbox.or(fallback.vbox);
        let preserve_aspect_ratio = self.preserve_aspect_ratio.or(fallback.preserve_aspect_ratio);
        let affine = self.affine.or(fallback.affine);
        let x = self.x.or(fallback.x);
        let y = self.y.or(fallback.y);
        let width = self.width.or(fallback.width);
        let height = self.height.or(fallback.height);

        let node = if !self.children_are_resolved() {
            fallback.node.clone()
        } else {
            self.node.clone()
        };

        let fallback = fallback.fallback.clone();

        NodePattern {
            units,
            content_units,
            vbox,
            preserve_aspect_ratio,
            affine,
            x,
            y,
            width,
            height,
            node,
            fallback,
        }
    }

    fn resolve_from_defaults(&self) -> NodePattern {
        let units = self.units.or(Some(PatternUnits::default()));
        let content_units = self.content_units.or(Some(PatternContentUnits::default()));
        let vbox = self.vbox.or(Some(None));
        let preserve_aspect_ratio = self.preserve_aspect_ratio.or(Some(AspectRatio::default()));
        let affine = self.affine.or(Some(cairo::Matrix::identity()));
        let x = self.x.or(Some(Default::default()));
        let y = self.y.or(Some(Default::default()));
        let width = self.width.or(Some(Default::default()));
        let height = self.height.or(Some(Default::default()));
        let node = self.node.clone();
        let fallback = None;

        NodePattern {
            units,
            content_units,
            vbox,
            preserve_aspect_ratio,
            affine,
            x,
            y,
            width,
            height,
            node,
            fallback,
        }
    }

    fn children_are_resolved(&self) -> bool {
        if let Some(ref node) = *self.node.borrow() {
            node.has_children()
        } else {
            // We are an empty pattern; there is nothing further that
            // can be resolved for children.
            true
        }
    }
}

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

    #[test]
    fn pattern_resolved_from_defaults_is_really_resolved() {
        let pat = NodePattern::default();
        let res = pat.resolve_from_defaults();
        assert!(res.is_resolved());
    }
}
<|endoftext|>


<commit_before>use std::{fs, io, path::Path};

#[allow(unused_imports)]
use eyre::{bail, eyre, Result};
use path_utils::lexiclean::Lexiclean;

/// Extract an archive to a destination
#[allow(unused_variables)]
pub fn extract(archive: &Path, dest: &Path, strip: usize, subdir: Option<&str>) -> Result<()> {
    tracing::info!("Extracting `{}` to `{}`", archive.display(), dest.display());

    let ext = match archive.extension() {
        Some(ext) => ext.to_string_lossy().to_string(),
        None => {
            bail!(
                "Archive file name `{}` has no extension so I don't know how to extract from it",
                archive.display()
            );
        }
    };

    match ext.as_str() {
        #[cfg(feature = "zip")]
        "zip" => extract_zip(archive, dest, strip, subdir),
        #[cfg(feature = "tar")]
        _ => extract_tar(&ext, archive, dest, strip, subdir),
        #[cfg(not(feature = "tar"))]
        _ => bail!("Unhandled archive extension {}", ext),
    }
}

/// Extract a tar archive
#[cfg(feature = "tar")]
pub fn extract_tar(
    ext: &str,
    archive: &Path,
    dest: &Path,
    strip: usize,
    subdir: Option<&str>,
) -> Result<()> {
    let file = fs::File::open(&archive)?;
    let mut archive = tar::Archive::new(match ext {
        "tar" => Box::new(file) as Box<dyn io::Read>,
        #[cfg(feature = "tar-gz")]
        "gz" | "tgz" => Box::new(flate2::read::GzDecoder::new(file)),
        #[cfg(feature = "tar-xz")]
        "xz" => Box::new(xz2::read::XzDecoder::new(file)),
        _ => bail!("Unhandled archive extension {}", ext),
    });

    let subdir: Vec<String> = match subdir {
        Some(subdir) => subdir.split('/').map(String::from).collect(),
        None => Vec::new(),
    };

    let mut count = 0;
    for mut entry in archive.entries()?.flatten() {
        let path = entry.path()?.display().to_string();
        let mut components: Vec<String> = path.split('/').map(String::from).collect();

        // Strip path components
        if strip > 0 {
            components.drain(0..strip);
        }

        // Only extract entries in specified subdirectories
        let mut extract = true;
        for dir in &subdir {
            if components.first() == Some(dir) {
                components.remove(0);
            } else {
                extract = false;
                break;
            }
        }
        if !extract {
            continue;
        }

        // Do not extract paths that traverse out of destination
        let out_path = dest.join(&components.join("/")).lexiclean();
        if out_path.strip_prefix(dest).is_err() {
            continue;
        }

        // Unpack to destination
        entry.unpack(&out_path)?;
        count += 1;
    }

    tracing::debug!("Extracted {} entries", count);
    Ok(())
}

/// Extract a zip archive
#[cfg(feature = "zip")]
pub fn extract_zip(archive: &Path, dest: &Path, strip: usize, subdir: Option<&str>) -> Result<()> {
    let file = fs::File::open(&archive)?;
    let mut archive = zip::ZipArchive::new(file)?;

    let subdir: Vec<String> = match subdir {
        Some(subdir) => subdir.split('/').map(String::from).collect(),
        None => Vec::new(),
    };

    let mut count = 0;
    for index in 0..archive.len() {
        let mut entry = archive.by_index(index)?;
        let path = entry
            .enclosed_name()
            .ok_or_else(|| eyre!("Zip archive entry has no enclosed name"))?
            .display()
            .to_string();
        let mut components: Vec<String> = path.split('/').map(String::from).collect();

        // Strip path components
        if strip > 0 {
            components.drain(0..strip);
        }

        // Only extract entries in specified subdirectories
        let mut extract = true;
        for dir in &subdir {
            if components.first() == Some(dir) {
                components.remove(0);
            } else {
                extract = false;
                break;
            }
        }
        if !extract {
            continue;
        }

        // Do not extract paths that traverse out of destination
        let out_path = dest.join(&components.join("/")).lexiclean();
        if out_path.strip_prefix(dest).is_err() {
            continue;
        }

        // Unpack to destination
        if entry.is_file() {
            if let Some(parent) = out_path.parent() {
                fs::create_dir_all(parent)?;
            }
            let mut out_file = fs::File::create(out_path)?;
            std::io::copy(&mut entry, &mut out_file)?;
            count += 1;
        }
    }

    tracing::debug!("Extracted {} entries", count);
    Ok(())
}
<commit_msg>chore(Archive utils): Export `tar` and `zip`<commit_after>use std::{fs, io, path::Path};

#[allow(unused_imports)]
use eyre::{bail, eyre, Result};
use path_utils::lexiclean::Lexiclean;

#[cfg(feature = "tar")]
pub use ::tar;

#[cfg(feature = "zip")]
pub use ::zip;

/// Extract an archive to a destination
#[allow(unused_variables)]
pub fn extract(archive: &Path, dest: &Path, strip: usize, subdir: Option<&str>) -> Result<()> {
    tracing::info!("Extracting `{}` to `{}`", archive.display(), dest.display());

    let ext = match archive.extension() {
        Some(ext) => ext.to_string_lossy().to_string(),
        None => {
            bail!(
                "Archive file name `{}` has no extension so I don't know how to extract from it",
                archive.display()
            );
        }
    };

    match ext.as_str() {
        #[cfg(feature = "zip")]
        "zip" => extract_zip(archive, dest, strip, subdir),
        #[cfg(feature = "tar")]
        _ => extract_tar(&ext, archive, dest, strip, subdir),
        #[cfg(not(feature = "tar"))]
        _ => bail!("Unhandled archive extension {}", ext),
    }
}

/// Extract a tar archive
#[cfg(feature = "tar")]
pub fn extract_tar(
    ext: &str,
    archive: &Path,
    dest: &Path,
    strip: usize,
    subdir: Option<&str>,
) -> Result<()> {
    let file = fs::File::open(&archive)?;
    let mut archive = tar::Archive::new(match ext {
        "tar" => Box::new(file) as Box<dyn io::Read>,
        #[cfg(feature = "tar-gz")]
        "gz" | "tgz" => Box::new(flate2::read::GzDecoder::new(file)),
        #[cfg(feature = "tar-xz")]
        "xz" => Box::new(xz2::read::XzDecoder::new(file)),
        _ => bail!("Unhandled archive extension {}", ext),
    });

    let subdir: Vec<String> = match subdir {
        Some(subdir) => subdir.split('/').map(String::from).collect(),
        None => Vec::new(),
    };

    let mut count = 0;
    for mut entry in archive.entries()?.flatten() {
        let path = entry.path()?.display().to_string();
        let mut components: Vec<String> = path.split('/').map(String::from).collect();

        // Strip path components
        if strip > 0 {
            components.drain(0..strip);
        }

        // Only extract entries in specified subdirectories
        let mut extract = true;
        for dir in &subdir {
            if components.first() == Some(dir) {
                components.remove(0);
            } else {
                extract = false;
                break;
            }
        }
        if !extract {
            continue;
        }

        // Do not extract paths that traverse out of destination
        let out_path = dest.join(&components.join("/")).lexiclean();
        if out_path.strip_prefix(dest).is_err() {
            continue;
        }

        // Unpack to destination
        entry.unpack(&out_path)?;
        count += 1;
    }

    tracing::debug!("Extracted {} entries", count);
    Ok(())
}

/// Extract a zip archive
#[cfg(feature = "zip")]
pub fn extract_zip(archive: &Path, dest: &Path, strip: usize, subdir: Option<&str>) -> Result<()> {
    let file = fs::File::open(&archive)?;
    let mut archive = zip::ZipArchive::new(file)?;

    let subdir: Vec<String> = match subdir {
        Some(subdir) => subdir.split('/').map(String::from).collect(),
        None => Vec::new(),
    };

    let mut count = 0;
    for index in 0..archive.len() {
        let mut entry = archive.by_index(index)?;
        let path = entry
            .enclosed_name()
            .ok_or_else(|| eyre!("Zip archive entry has no enclosed name"))?
            .display()
            .to_string();
        let mut components: Vec<String> = path.split('/').map(String::from).collect();

        // Strip path components
        if strip > 0 {
            components.drain(0..strip);
        }

        // Only extract entries in specified subdirectories
        let mut extract = true;
        for dir in &subdir {
            if components.first() == Some(dir) {
                components.remove(0);
            } else {
                extract = false;
                break;
            }
        }
        if !extract {
            continue;
        }

        // Do not extract paths that traverse out of destination
        let out_path = dest.join(&components.join("/")).lexiclean();
        if out_path.strip_prefix(dest).is_err() {
            continue;
        }

        // Unpack to destination
        if entry.is_file() {
            if let Some(parent) = out_path.parent() {
                fs::create_dir_all(parent)?;
            }
            let mut out_file = fs::File::create(out_path)?;
            std::io::copy(&mut entry, &mut out_file)?;
            count += 1;
        }
    }

    tracing::debug!("Extracted {} entries", count);
    Ok(())
}
<|endoftext|>


<commit_before>use {Token, SyntaxKind, TextUnit};
use super::{Event};
use super::super::is_insignificant;
use syntax_kinds::{L_CURLY, R_CURLY, ERROR};
use tree::EOF;

pub(crate) struct Parser<'t> {
    #[allow(unused)]
    text: &'t str,
    #[allow(unused)]
    start_offsets: Vec<TextUnit>,
    tokens: Vec<Token>, // non-whitespace tokens

    pos: usize,
    events: Vec<Event>,

    curly_level: i32,
    curly_limit: Option<i32>,
}

impl<'t> Parser<'t> {
    pub(crate) fn new(text: &'t str, raw_tokens: &'t [Token]) -> Parser<'t> {
        let mut tokens = Vec::new();
        let mut start_offsets = Vec::new();
        let mut len = TextUnit::new(0);
        for &token in raw_tokens.iter() {
            if !is_insignificant(token.kind) {
                tokens.push(token);
                start_offsets.push(len);
            }
            len += token.len;
        }

        Parser {
            text,
            start_offsets,
            tokens,

            pos: 0,
            events: Vec::new(),
            curly_level: 0,
            curly_limit: None,
        }
    }

    pub(crate) fn pos(&self) -> usize {
        self.pos
    }

    pub(crate) fn into_events(self) -> Vec<Event> {
        assert!(self.curly_limit.is_none());
        assert!(self.current() == EOF);
        self.events
    }

    pub(crate) fn current(&self) -> SyntaxKind {
        if self.pos == self.tokens.len() {
            return EOF;
        }
        let token = self.tokens[self.pos];
        if let Some(limit) = self.curly_limit {
            if limit == self.curly_level && token.kind == R_CURLY {
                return EOF
            }
        }
        token.kind
    }

    pub(crate) fn start(&mut self, kind: SyntaxKind) {
        self.event(Event::Start { kind });
    }

    pub(crate) fn finish(&mut self) {
        self.event(Event::Finish);
    }

    pub(crate) fn error<'p>(&'p mut self) -> ErrorBuilder<'p, 't> {
        ErrorBuilder::new(self)
    }

    pub(crate) fn bump(&mut self) -> SyntaxKind {
        let kind = self.current();
        match kind {
            L_CURLY => self.curly_level += 1,
            R_CURLY => self.curly_level -= 1,
            EOF => return EOF,
            _ => (),
        }
        self.pos += 1;
        self.event(Event::Token { kind, n_raw_tokens: 1 });
        kind
    }

    pub(crate) fn raw_lookahead(&self, n: usize) -> SyntaxKind {
        self.tokens.get(self.pos + n).map(|t| t.kind).unwrap_or(EOF)
    }

    pub(crate) fn curly_block<F: FnOnce(&mut Parser)>(&mut self, f: F) -> bool {
        let old_level = self.curly_level;
        let old_limit = self.curly_limit;
        if !self.expect(L_CURLY) {
            return false
        }
        self.curly_limit = Some(self.curly_level);
        f(self);
        assert!(self.curly_level > old_level);
        self.curly_limit = old_limit;
        if !self.expect(R_CURLY) {
            self.start(ERROR);
            while self.curly_level > old_level {
                if self.bump() == EOF {
                    break;
                }
            }
            self.finish();
        }
        true
    }

    fn event(&mut self, event: Event) {
        self.events.push(event)
    }
}

pub(crate) struct ErrorBuilder<'p, 't: 'p> {
    message: Option<String>,
    parser: &'p mut Parser<'t>
}

impl<'t, 'p> ErrorBuilder<'p, 't> {
    fn new(parser: &'p mut Parser<'t>) -> Self {
        ErrorBuilder { message: None, parser }
    }

    pub fn message<M: Into<String>>(mut self, m: M) -> Self {
        self.message = Some(m.into());
        self
    }

    pub fn emit(self) {
        let message = self.message.expect("Error message not set");
        self.parser.event(Event::Error { message });
    }
}
<commit_msg>Encapsulate position<commit_after>use {Token, SyntaxKind, TextUnit};
use super::{Event};
use super::super::is_insignificant;
use syntax_kinds::{L_CURLY, R_CURLY, ERROR};
use tree::EOF;

pub(crate) struct Parser<'t> {
    #[allow(unused)]
    text: &'t str,
    #[allow(unused)]
    start_offsets: Vec<TextUnit>,
    tokens: Vec<Token>, // non-whitespace tokens

    pos: usize,
    events: Vec<Event>,

    curly_level: i32,
    curly_limit: Option<i32>,
}

#[derive(Debug, Clone, Copy,PartialEq, Eq)]
pub(crate) struct Pos(u32);

impl<'t> Parser<'t> {
    pub(crate) fn new(text: &'t str, raw_tokens: &'t [Token]) -> Parser<'t> {
        let mut tokens = Vec::new();
        let mut start_offsets = Vec::new();
        let mut len = TextUnit::new(0);
        for &token in raw_tokens.iter() {
            if !is_insignificant(token.kind) {
                tokens.push(token);
                start_offsets.push(len);
            }
            len += token.len;
        }

        Parser {
            text,
            start_offsets,
            tokens,

            pos: 0,
            events: Vec::new(),
            curly_level: 0,
            curly_limit: None,
        }
    }

    pub(crate) fn pos(&self) -> Pos {
        Pos(self.pos as u32)
    }

    pub(crate) fn into_events(self) -> Vec<Event> {
        assert!(self.curly_limit.is_none());
        assert!(self.current() == EOF);
        self.events
    }

    pub(crate) fn current(&self) -> SyntaxKind {
        if self.pos == self.tokens.len() {
            return EOF;
        }
        let token = self.tokens[self.pos];
        if let Some(limit) = self.curly_limit {
            if limit == self.curly_level && token.kind == R_CURLY {
                return EOF
            }
        }
        token.kind
    }

    pub(crate) fn start(&mut self, kind: SyntaxKind) {
        self.event(Event::Start { kind });
    }

    pub(crate) fn finish(&mut self) {
        self.event(Event::Finish);
    }

    pub(crate) fn error<'p>(&'p mut self) -> ErrorBuilder<'p, 't> {
        ErrorBuilder::new(self)
    }

    pub(crate) fn bump(&mut self) -> SyntaxKind {
        let kind = self.current();
        match kind {
            L_CURLY => self.curly_level += 1,
            R_CURLY => self.curly_level -= 1,
            EOF => return EOF,
            _ => (),
        }
        self.pos += 1;
        self.event(Event::Token { kind, n_raw_tokens: 1 });
        kind
    }

    pub(crate) fn raw_lookahead(&self, n: usize) -> SyntaxKind {
        self.tokens.get(self.pos + n).map(|t| t.kind).unwrap_or(EOF)
    }

    pub(crate) fn curly_block<F: FnOnce(&mut Parser)>(&mut self, f: F) -> bool {
        let old_level = self.curly_level;
        let old_limit = self.curly_limit;
        if !self.expect(L_CURLY) {
            return false
        }
        self.curly_limit = Some(self.curly_level);
        f(self);
        assert!(self.curly_level > old_level);
        self.curly_limit = old_limit;
        if !self.expect(R_CURLY) {
            self.start(ERROR);
            while self.curly_level > old_level {
                if self.bump() == EOF {
                    break;
                }
            }
            self.finish();
        }
        true
    }

    fn event(&mut self, event: Event) {
        self.events.push(event)
    }
}

pub(crate) struct ErrorBuilder<'p, 't: 'p> {
    message: Option<String>,
    parser: &'p mut Parser<'t>
}

impl<'t, 'p> ErrorBuilder<'p, 't> {
    fn new(parser: &'p mut Parser<'t>) -> Self {
        ErrorBuilder { message: None, parser }
    }

    pub fn message<M: Into<String>>(mut self, m: M) -> Self {
        self.message = Some(m.into());
        self
    }

    pub fn emit(self) {
        let message = self.message.expect("Error message not set");
        self.parser.event(Event::Error { message });
    }
}
<|endoftext|>


<commit_before>// rustfmt-normalize_comments: true
itemmacro!(this, is.now().formatted(yay));

itemmacro!(
    really,
    long.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaabbb()
        .is
        .formatted()
);

itemmacro!{this, is.bracket().formatted()}

peg_file! modname("mygrammarfile.rustpeg");

fn main() {
    foo!();

    bar!(a, b, c);

    bar!(a, b, c,);

    baz!(1 + 2 + 3, quux.kaas());

    quux!(
        AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA,
        BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB
    );

    kaas!(
        // comments
        a, // post macro
        b  // another
    );

    trailingcomma!(a, b, c,);
    // Preserve trailing comma only when necessary.
    ok!(file.seek(SeekFrom::Start(
        table.map(|table| fixture.offset(table)).unwrap_or(0),
    )));

    noexpr!( i am not an expression, OK? );

    vec![a, b, c];

    vec![
        AAAAAA,
        AAAAAA,
        AAAAAA,
        AAAAAA,
        AAAAAA,
        AAAAAA,
        AAAAAA,
        AAAAAA,
        AAAAAA,
        BBBBB,
        5,
        100 - 30,
        1.33,
        b,
        b,
        b,
    ];

    vec![a /* comment */];

    // Trailing spaces after a comma
    vec![a];

    vec![a; b];
    vec![a; b];
    vec![a; b];

    vec![a, b; c];
    vec![a; b, c];

    vec![
        a;
        (|x| {
            let y = x + 1;
            let z = y + 1;
            z
        })(2)
    ];
    vec![
        a;
        xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
    ];
    vec![a; unsafe { x + 1 }];

    unknown_bracket_macro__comma_should_not_be_stripped![a,];

    foo(makro!(1, 3));

    hamkaas!{ () };

    macrowithbraces! {dont,    format, me}

    x!(fn);

    some_macro!();

    some_macro![];

    some_macro!{
        // comment
    };

    some_macro!{
        // comment
    };

    some_macro!(
        // comment
        not function like
    );

    // #1712
    let image = gray_image!(
        00, 01, 02;
        10, 11, 12;
        20, 21, 22);

    // #1092
    chain!(input, a:take!(max_size), || []);
}

impl X {
    empty_invoc!{}
}

fn issue_1279() {
    println!("dsfs"); // a comment
}

fn issue_1555() {
    let hello = &format!(
        "HTTP/1.1 200 OK\r\nServer: {}\r\n\r\n{}",
        "65454654654654654654654655464", "4"
    );
}

fn issue1178() {
    macro_rules! foo {
        (#[$attr:meta] $name:ident) => {}
    }

    foo!(
        #[doc = "bar"]
        baz
    );
}

fn issue1739() {
    sql_function!(
        add_rss_item,
        add_rss_item_t,
        (
            a: types::Integer,
            b: types::Timestamptz,
            c: types::Text,
            d: types::Text,
            e: types::Text
        )
    );

    w.slice_mut(s![
        ..,
        init_size[1] - extreeeeeeeeeeeeeeeeeeeeeeeem..init_size[1],
        ..
    ]).par_map_inplace(|el| *el = 0.);
}

fn issue_1885() {
    let threads = people
        .into_iter()
        .map(|name| {
            chan_select! {
                rx.recv() => {}
            }
        })
        .collect::<Vec<_>>();
}

fn issue_1917() {
    mod x {
        quickcheck! {
            fn test(a: String, s: String, b: String) -> TestResult {
                if a.find(&s).is_none() {

                    TestResult::from_bool(true)
                } else {
                    TestResult::discard()
                }
            }
        }
    }
}

fn issue_1921() {
    // Macro with tabs.
    lazy_static! {
        static ref ONE: u32 = 1;
        static ref TWO: u32 = 2;
        static ref THREE: u32 = 3;
        static ref FOUR: u32 = {
            let mut acc = 1;
            acc += 1;
            acc += 2;
            acc
        }
    }
}

// #1577
fn issue1577() {
    let json = json!({
        "foo": "bar",
    });
}

gfx_pipeline!(pipe {
    vbuf: gfx::VertexBuffer<Vertex> = (),
    out: gfx::RenderTarget<ColorFormat> = "Target0",
});

// #1919
#[test]
fn __bindgen_test_layout_HandleWithDtor_open0_int_close0_instantiation() {
    assert_eq!(
        ::std::mem::size_of::<HandleWithDtor<::std::os::raw::c_int>>(),
        8usize,
        concat!(
            "Size of template specialization: ",
            stringify!(HandleWithDtor<::std::os::raw::c_int>)
        )
    );
    assert_eq!(
        ::std::mem::align_of::<HandleWithDtor<::std::os::raw::c_int>>(),
        8usize,
        concat!(
            "Alignment of template specialization: ",
            stringify!(HandleWithDtor<::std::os::raw::c_int>)
        )
    );
}

// #878
macro_rules! try_opt {
    ($expr:expr) => (match $expr {
        Some(val) => val,

        None => { return None; }
    })
}

// #2214
// macro call whose argument is an array with trailing comma.
fn issue2214() {
    make_test!(
        str_searcher_ascii_haystack,
        "bb",
        "abbcbbd",
        [
            Reject(0, 1),
            Match(1, 3),
            Reject(3, 4),
            Match(4, 6),
            Reject(6, 7),
        ]
    );
}

fn special_case_macros() {
    // format!
    let s = format!(
        "Arr! While plunderin' the hold, we got '{}' when given '{}' (we expected '{}')",
        result, input, expected
    );

    // assert!
    assert!(
        result,
        "Arr! While plunderin' the hold, we got '{}' when given '{}' (we expected '{}')",
        result, input, expected
    );
}

// #1209
impl Foo {
    /// foo
    pub fn foo(&self) -> Bar<foo!()> {}
}
<commit_msg>Update a test<commit_after>// rustfmt-normalize_comments: true
itemmacro!(this, is.now().formatted(yay));

itemmacro!(
    really,
    long.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaabbb()
        .is
        .formatted()
);

itemmacro!{this, is.bracket().formatted()}

peg_file! modname("mygrammarfile.rustpeg");

fn main() {
    foo!();

    bar!(a, b, c);

    bar!(a, b, c,);

    baz!(1 + 2 + 3, quux.kaas());

    quux!(
        AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA,
        BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB
    );

    kaas!(
        // comments
        a, // post macro
        b  // another
    );

    trailingcomma!(a, b, c,);
    // Preserve trailing comma only when necessary.
    ok!(file.seek(SeekFrom::Start(
        table.map(|table| fixture.offset(table)).unwrap_or(0),
    )));

    noexpr!( i am not an expression, OK? );

    vec![a, b, c];

    vec![
        AAAAAA,
        AAAAAA,
        AAAAAA,
        AAAAAA,
        AAAAAA,
        AAAAAA,
        AAAAAA,
        AAAAAA,
        AAAAAA,
        BBBBB,
        5,
        100 - 30,
        1.33,
        b,
        b,
        b,
    ];

    vec![a /* comment */];

    // Trailing spaces after a comma
    vec![a];

    vec![a; b];
    vec![a; b];
    vec![a; b];

    vec![a, b; c];
    vec![a; b, c];

    vec![
        a;
        (|x| {
            let y = x + 1;
            let z = y + 1;
            z
        })(2)
    ];
    vec![
        a;
        xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
    ];
    vec![a; unsafe { x + 1 }];

    unknown_bracket_macro__comma_should_not_be_stripped![a,];

    foo(makro!(1, 3));

    hamkaas!{ () };

    macrowithbraces! {dont,    format, me}

    x!(fn);

    some_macro!();

    some_macro![];

    some_macro!{
        // comment
    };

    some_macro!{
        // comment
    };

    some_macro!(
        // comment
        not function like
    );

    // #1712
    let image = gray_image!(
        00, 01, 02;
        10, 11, 12;
        20, 21, 22);

    // #1092
    chain!(input, a: take!(max_size), || []);
}

impl X {
    empty_invoc!{}
}

fn issue_1279() {
    println!("dsfs"); // a comment
}

fn issue_1555() {
    let hello = &format!(
        "HTTP/1.1 200 OK\r\nServer: {}\r\n\r\n{}",
        "65454654654654654654654655464", "4"
    );
}

fn issue1178() {
    macro_rules! foo {
        (#[$attr:meta] $name:ident) => {}
    }

    foo!(
        #[doc = "bar"]
        baz
    );
}

fn issue1739() {
    sql_function!(
        add_rss_item,
        add_rss_item_t,
        (
            a: types::Integer,
            b: types::Timestamptz,
            c: types::Text,
            d: types::Text,
            e: types::Text
        )
    );

    w.slice_mut(s![
        ..,
        init_size[1] - extreeeeeeeeeeeeeeeeeeeeeeeem..init_size[1],
        ..
    ]).par_map_inplace(|el| *el = 0.);
}

fn issue_1885() {
    let threads = people
        .into_iter()
        .map(|name| {
            chan_select! {
                rx.recv() => {}
            }
        })
        .collect::<Vec<_>>();
}

fn issue_1917() {
    mod x {
        quickcheck! {
            fn test(a: String, s: String, b: String) -> TestResult {
                if a.find(&s).is_none() {

                    TestResult::from_bool(true)
                } else {
                    TestResult::discard()
                }
            }
        }
    }
}

fn issue_1921() {
    // Macro with tabs.
    lazy_static! {
        static ref ONE: u32 = 1;
        static ref TWO: u32 = 2;
        static ref THREE: u32 = 3;
        static ref FOUR: u32 = {
            let mut acc = 1;
            acc += 1;
            acc += 2;
            acc
        }
    }
}

// #1577
fn issue1577() {
    let json = json!({
        "foo": "bar",
    });
}

gfx_pipeline!(pipe {
    vbuf: gfx::VertexBuffer<Vertex> = (),
    out: gfx::RenderTarget<ColorFormat> = "Target0",
});

// #1919
#[test]
fn __bindgen_test_layout_HandleWithDtor_open0_int_close0_instantiation() {
    assert_eq!(
        ::std::mem::size_of::<HandleWithDtor<::std::os::raw::c_int>>(),
        8usize,
        concat!(
            "Size of template specialization: ",
            stringify!(HandleWithDtor<::std::os::raw::c_int>)
        )
    );
    assert_eq!(
        ::std::mem::align_of::<HandleWithDtor<::std::os::raw::c_int>>(),
        8usize,
        concat!(
            "Alignment of template specialization: ",
            stringify!(HandleWithDtor<::std::os::raw::c_int>)
        )
    );
}

// #878
macro_rules! try_opt {
    ($expr:expr) => (match $expr {
        Some(val) => val,

        None => { return None; }
    })
}

// #2214
// macro call whose argument is an array with trailing comma.
fn issue2214() {
    make_test!(
        str_searcher_ascii_haystack,
        "bb",
        "abbcbbd",
        [
            Reject(0, 1),
            Match(1, 3),
            Reject(3, 4),
            Match(4, 6),
            Reject(6, 7),
        ]
    );
}

fn special_case_macros() {
    // format!
    let s = format!(
        "Arr! While plunderin' the hold, we got '{}' when given '{}' (we expected '{}')",
        result, input, expected
    );

    // assert!
    assert!(
        result,
        "Arr! While plunderin' the hold, we got '{}' when given '{}' (we expected '{}')",
        result, input, expected
    );
}

// #1209
impl Foo {
    /// foo
    pub fn foo(&self) -> Bar<foo!()> {}
}
<|endoftext|>