<commit_before>#![feature(net)]
#![feature(io)]
#![feature(std_misc)]

use std::thread::Thread;
use std::sync::mpsc::{channel, Sender, Receiver};
use std::net::UdpSocket;
use std::net::IpAddr;
use std::old_io::Timer;
use std::old_io::timer;
use std::time::duration::Duration;

// ================================================================================================

const CRTP_VERSION : &'static str = env!("CARGO_PKG_VERSION");

struct SSRC(u32);
struct RtpTimestamp(u32);
struct NtpTimestamp(u64);

struct SenderInfo {
  ntp_ts     : u64, // FIXME: should be NtpTimestamp,
  rtp_ts     : u32, // FIXME: should be RtpTimestamp,
  pckt_count : u32,
  byte_count : u32
}

struct ReportBlock {
  ssrc       : SSRC,
  fract_lost : u8,
  cumul_lost : u32,
  ext_seq    : u32,
  jitter     : u32,
  lsr        : u32,
  dlsr       : u32
}

struct SdesChunk {
  ssrc  : SSRC,
  cname : Option<String>,
  name  : Option<String>,
  email : Option<String>,
  phone : Option<String>,
  loc   : Option<String>,
  tool  : Option<String>,
  note  : Option<String>
}

enum RtcpPacket {
  SR(SSRC, Vec<ReportBlock>, SenderInfo),
  RR(SSRC, Vec<ReportBlock>),
  SDES(Vec<SdesChunk>),
  BYE(Vec<SSRC>, String),
}

struct CompoundRtcpPacket {
  packets : Vec<RtcpPacket>
}

struct RtpPacket;

// ================================================================================================

struct RtpSessionParameters {
  rtp_tx  :   Sender<RtpPacket>,
  rtp_rx  : Receiver<RtpPacket>,
  rtcp_tx :   Sender<CompoundRtcpPacket>,
  rtcp_rx : Receiver<CompoundRtcpPacket>
}

struct RtpSessionStatistics {
  pckt_count : u64
}

struct RtpSession {
  parameters : RtpSessionParameters,
  ssrc       : u32
}

impl RtpSession {
  pub fn new(params : RtpSessionParameters) -> RtpSession {
    RtpSession {
      parameters : params,
      ssrc       : 0    // FIXME
    }
  }

  pub fn run(&mut self) -> RtpSessionStatistics {
    let stats = RtpSessionStatistics{pckt_count : 0};
    stats
  }
}

// ================================================================================================

fn parse_rtp_packet(buf : &mut [u8], buflen : usize) -> Option<RtpPacket> {
  println!("parse_rtp_packet");
  None
}

struct RtpSocket {
  local_addr : IpAddr,
  local_port : u16
}

impl RtpSocket {
  pub fn run(&self) -> (Sender<RtpPacket>, Receiver<RtpPacket>) {
    let rx_socket = UdpSocket::bind(&(self.local_addr, self.local_port)).unwrap();
    let tx_socket = rx_socket.try_clone().unwrap();

    let (to_app, from_net) = channel::<RtpPacket>();
    let (to_net, from_app) = channel::<RtpPacket>();

    Thread::spawn(move || {
      // The receiving thread
      loop {
        let mut buf = [0; 1500];
        let (amt, src) = rx_socket.recv_from(&mut buf).unwrap();

        match parse_rtp_packet(&mut buf, amt) {
          Some(packet) => to_app.send(packet).unwrap(),
          None => {
            println!("Unable to parse packet")
          }
        }
      }
    });

    Thread::spawn(move || {
      // The sending thread
      let packet = from_app.recv().unwrap();
      // FIXME: send the packet
    });

    (to_net, from_net)
  }
}

// ================================================================================================

fn parse_sr(p : bool, rc : u8, len : usize, packet : &[u8]) -> Option<RtcpPacket> {
  unimplemented!();
  None
}

fn parse_rr(p : bool, rc : u8, len : usize, packet : &[u8]) -> Option<RtcpPacket> {
  unimplemented!();
  None
}

fn parse_sdes(p : bool, rc : u8, len : usize, packet : &[u8]) -> Option<RtcpPacket> {
  unimplemented!();
  None
}

fn parse_bye(p : bool, rc : u8, len : usize, packet : &[u8]) -> Option<RtcpPacket> {
  unimplemented!();
  None
}

fn parse_app(p : bool, rc : u8, len : usize, packet : &[u8]) -> Option<RtcpPacket> {
  unimplemented!();
  None
}

fn parse_rtcp_packet(buf : &mut [u8], buflen : usize) -> Option<CompoundRtcpPacket> {
  if buflen < 4 {
    println!("parse_rtcp_packet: packet is too short to be RTCP");
    return None;
  }

  // FIXME: create a compound packet object

  let mut offset = 0;
  while offset != buflen {
    if offset + 3 >= buflen {
      println!("parse_rtcp_packet: packet is too short");
      return None;
    }

    let v   =   (buf[offset + 0] >> 6) & 0x03;
    let p   =  ((buf[offset + 0] >> 5) & 0x01) == 1;
    let rc  =   (buf[offset + 0] >> 0) & 0x1f;
    let pt  =    buf[offset + 1];
    let len = (((buf[offset + 2] as usize) << 8) & 0xff00) |
              (((buf[offset + 3] as usize) << 0) & 0x0fff);

    if offset + (4 * len) > buflen {
      println!("parse_rtcp_packet: packet is too long");
      return None;
    }

    if v != 2 {
      println!("parse_rtcp_packet: version number mismatch (v={})", v);
      return None;
    }

    let packet = &buf[offset..offset + (4 * (len + 1))];

    let parsed_packet = match pt {
      200 =>   parse_sr(p, rc, len, packet),
      201 =>   parse_rr(p, rc, len, packet),
      202 => parse_sdes(p, rc, len, packet),
      203 =>  parse_bye(p, rc, len, packet),
      204 =>  parse_app(p, rc, len, packet),
      _   => {
        println!("parse_rtcp_packet: unknown packet type (pt={})", pt);
        return None;
      }
    };

    // FIXME: append parsed_packet to the compound packet

    offset += 4 + (4 * len);
  }

  None  // FIXME: return the compound packet
}

struct RtcpSocket {
  local_addr : IpAddr,
  local_port : u16
}

impl RtcpSocket {
  pub fn run(&self) -> (Sender<CompoundRtcpPacket>, Receiver<CompoundRtcpPacket>) {
    let rx_socket = UdpSocket::bind(&(self.local_addr, self.local_port)).unwrap();
    let tx_socket = rx_socket.try_clone().unwrap();

    let (to_app, from_net) = channel::<CompoundRtcpPacket>();
    let (to_net, from_app) = channel::<CompoundRtcpPacket>();

    Thread::spawn(move || {
      // The receiving thread
      loop {
        let mut buf = [0; 1500];
        let (amt, src) = rx_socket.recv_from(&mut buf).unwrap();

        match parse_rtcp_packet(&mut buf, amt) {
          Some(packet) => to_app.send(packet).unwrap(),
          None => {
            println!("Unable to parse packet")
          }
        }
      }
    });

    Thread::spawn(move || {
      // The sending thread
      let packet = from_app.recv().unwrap();
      // FIXME: send the packet
    });

    (to_net, from_net)
  }
}

// ================================================================================================

fn main() {
  println!("CRTP v{}", CRTP_VERSION);

  let rtp_socket  =  RtpSocket{local_addr: IpAddr::new_v4(0,0,0,0), local_port : 3000};
  let (rtp_tx, rtp_rx) = rtp_socket.run();

  let rtcp_socket = RtcpSocket{local_addr: IpAddr::new_v4(0,0,0,0), local_port : 3001};
  let (rtcp_tx, rtcp_rx) = rtcp_socket.run();

  let session_parameters = RtpSessionParameters {
                             rtp_tx  : rtp_tx,
                             rtp_rx  : rtp_rx,
                             rtcp_tx : rtcp_tx,
                             rtcp_rx : rtcp_rx
                           };

  let mut session = RtpSession::new(session_parameters);
  let session_statistics = session.run();

  timer::sleep(Duration::hours(1));

}

// ================================================================================================
// vim: set ts=2 sw=2 tw=0 et ai:
<commit_msg>Catch-up with latest Rust nightly<commit_after>#![feature(net)]
#![feature(std_misc)]

use std::thread;
use std::sync::mpsc::{channel, Sender, Receiver};
use std::net::UdpSocket;
use std::net::IpAddr;
use std::old_io::timer;
use std::time::duration::Duration;

// ================================================================================================

const CRTP_VERSION : &'static str = env!("CARGO_PKG_VERSION");

struct SSRC(u32);
struct RtpTimestamp(u32);
struct NtpTimestamp(u64);

struct SenderInfo {
  ntp_ts     : u64, // FIXME: should be NtpTimestamp,
  rtp_ts     : u32, // FIXME: should be RtpTimestamp,
  pckt_count : u32,
  byte_count : u32
}

struct ReportBlock {
  ssrc       : SSRC,
  fract_lost : u8,
  cumul_lost : u32,
  ext_seq    : u32,
  jitter     : u32,
  lsr        : u32,
  dlsr       : u32
}

struct SdesChunk {
  ssrc  : SSRC,
  cname : Option<String>,
  name  : Option<String>,
  email : Option<String>,
  phone : Option<String>,
  loc   : Option<String>,
  tool  : Option<String>,
  note  : Option<String>
}

enum RtcpPacket {
  SR(SSRC, Vec<ReportBlock>, SenderInfo),
  RR(SSRC, Vec<ReportBlock>),
  SDES(Vec<SdesChunk>),
  BYE(Vec<SSRC>, String),
}

struct CompoundRtcpPacket {
  packets : Vec<RtcpPacket>
}

struct RtpPacket;

// ================================================================================================

struct RtpSessionParameters {
  rtp_tx  :   Sender<RtpPacket>,
  rtp_rx  : Receiver<RtpPacket>,
  rtcp_tx :   Sender<CompoundRtcpPacket>,
  rtcp_rx : Receiver<CompoundRtcpPacket>
}

struct RtpSessionStatistics {
  pckt_count : u64
}

struct RtpSession {
  parameters : RtpSessionParameters,
  ssrc       : u32
}

impl RtpSession {
  pub fn new(params : RtpSessionParameters) -> RtpSession {
    RtpSession {
      parameters : params,
      ssrc       : 0    // FIXME
    }
  }

  pub fn run(&mut self) -> RtpSessionStatistics {
    let stats = RtpSessionStatistics{pckt_count : 0};
    stats
  }
}

// ================================================================================================

fn parse_rtp_packet(buf : &mut [u8], buflen : usize) -> Option<RtpPacket> {
  println!("parse_rtp_packet");
  None
}

struct RtpSocket {
  local_addr : IpAddr,
  local_port : u16
}

impl RtpSocket {
  pub fn run(&self) -> (Sender<RtpPacket>, Receiver<RtpPacket>) {
    let rx_socket = UdpSocket::bind(&(self.local_addr, self.local_port)).unwrap();
    let tx_socket = rx_socket.try_clone().unwrap();

    let (to_app, from_net) = channel::<RtpPacket>();
    let (to_net, from_app) = channel::<RtpPacket>();

    thread::spawn(move || {
      // The receiving thread
      loop {
        let mut buf = [0; 1500];
        let (amt, src) = rx_socket.recv_from(&mut buf).unwrap();

        match parse_rtp_packet(&mut buf, amt) {
          Some(packet) => to_app.send(packet).unwrap(),
          None => {
            println!("Unable to parse packet")
          }
        }
      }
    });

    thread::spawn(move || {
      // The sending thread
      let packet = from_app.recv().unwrap();
      // FIXME: send the packet
    });

    (to_net, from_net)
  }
}

// ================================================================================================

fn parse_sr(p : bool, rc : u8, len : usize, packet : &[u8]) -> Option<RtcpPacket> {
  unimplemented!();
}

fn parse_rr(p : bool, rc : u8, len : usize, packet : &[u8]) -> Option<RtcpPacket> {
  unimplemented!();
}

fn parse_sdes(p : bool, rc : u8, len : usize, packet : &[u8]) -> Option<RtcpPacket> {
  unimplemented!();
}

fn parse_bye(p : bool, rc : u8, len : usize, packet : &[u8]) -> Option<RtcpPacket> {
  unimplemented!();
}

fn parse_app(p : bool, rc : u8, len : usize, packet : &[u8]) -> Option<RtcpPacket> {
  unimplemented!();
}

fn parse_rtcp_packet(buf : &mut [u8], buflen : usize) -> Option<CompoundRtcpPacket> {
  if buflen < 4 {
    println!("parse_rtcp_packet: packet is too short to be RTCP");
    return None;
  }

  // FIXME: create a compound packet object

  let mut offset = 0;
  while offset != buflen {
    if offset + 3 >= buflen {
      println!("parse_rtcp_packet: packet is too short");
      return None;
    }

    let v   =   (buf[offset + 0] >> 6) & 0x03;
    let p   =  ((buf[offset + 0] >> 5) & 0x01) == 1;
    let rc  =   (buf[offset + 0] >> 0) & 0x1f;
    let pt  =    buf[offset + 1];
    let len = (((buf[offset + 2] as usize) << 8) & 0xff00) |
              (((buf[offset + 3] as usize) << 0) & 0x0fff);

    if offset + (4 * len) > buflen {
      println!("parse_rtcp_packet: packet is too long");
      return None;
    }

    if v != 2 {
      println!("parse_rtcp_packet: version number mismatch (v={})", v);
      return None;
    }

    let packet = &buf[offset..offset + (4 * (len + 1))];

    let parsed_packet = match pt {
      200 =>   parse_sr(p, rc, len, packet),
      201 =>   parse_rr(p, rc, len, packet),
      202 => parse_sdes(p, rc, len, packet),
      203 =>  parse_bye(p, rc, len, packet),
      204 =>  parse_app(p, rc, len, packet),
      _   => {
        println!("parse_rtcp_packet: unknown packet type (pt={})", pt);
        return None;
      }
    };

    // FIXME: append parsed_packet to the compound packet

    offset += 4 + (4 * len);
  }

  None  // FIXME: return the compound packet
}

struct RtcpSocket {
  local_addr : IpAddr,
  local_port : u16
}

impl RtcpSocket {
  pub fn run(&self) -> (Sender<CompoundRtcpPacket>, Receiver<CompoundRtcpPacket>) {
    let rx_socket = UdpSocket::bind(&(self.local_addr, self.local_port)).unwrap();
    let tx_socket = rx_socket.try_clone().unwrap();

    let (to_app, from_net) = channel::<CompoundRtcpPacket>();
    let (to_net, from_app) = channel::<CompoundRtcpPacket>();

    thread::spawn(move || {
      // The receiving thread
      loop {
        let mut buf = [0; 1500];
        let (amt, src) = rx_socket.recv_from(&mut buf).unwrap();

        match parse_rtcp_packet(&mut buf, amt) {
          Some(packet) => to_app.send(packet).unwrap(),
          None => {
            println!("Unable to parse packet")
          }
        }
      }
    });

    thread::spawn(move || {
      // The sending thread
      let packet = from_app.recv().unwrap();
      // FIXME: send the packet
    });

    (to_net, from_net)
  }
}

// ================================================================================================

fn main() {
  println!("CRTP v{}", CRTP_VERSION);

  let rtp_socket  =  RtpSocket{local_addr: IpAddr::new_v4(0,0,0,0), local_port : 3000};
  let (rtp_tx, rtp_rx) = rtp_socket.run();

  let rtcp_socket = RtcpSocket{local_addr: IpAddr::new_v4(0,0,0,0), local_port : 3001};
  let (rtcp_tx, rtcp_rx) = rtcp_socket.run();

  let session_parameters = RtpSessionParameters {
                             rtp_tx  : rtp_tx,
                             rtp_rx  : rtp_rx,
                             rtcp_tx : rtcp_tx,
                             rtcp_rx : rtcp_rx
                           };

  let mut session = RtpSession::new(session_parameters);
  let session_statistics = session.run();

  timer::sleep(Duration::hours(1));

}

// ================================================================================================
// vim: set ts=2 sw=2 tw=0 et ai:
<|endoftext|>


<commit_before>#![feature(inclusive_range_fields, range_contains)]

extern crate dotenv;
extern crate itertools;
#[macro_use]
extern crate lazy_static;
extern crate rand;
extern crate serenity;

use std::collections::BTreeMap;
use std::env;
use std::ops::RangeInclusive;

use dotenv::dotenv;
use itertools::Itertools;
use rand::Rng;
use serenity::prelude::*;
use serenity::model::prelude::*;

trait Command {
    fn required_arg_count(&self) -> RangeInclusive<usize>; //impl RangeArgument<usize>;
    fn exec(&self, ctx: &Context, msg: &Message, args: &[&str]);
}
type CommandMap = BTreeMap<&'static str, Box<Command + Sync>>;

lazy_static! {
    static ref COMMAND_MAP: CommandMap = {
        let mut commands = CommandMap::new();
        commands.insert("help", Box::new(Help));
        commands.insert("flip", Box::new(Flip));
        commands.insert("roll", Box::new(Roll));
        commands
    };
}

fn main() {
    let _ = dotenv();

    let creds = env::var("Z_CREDENTIALS")
        .expect("Unspecified credentials: set Z_CREDENTIALS in the environment (or in `.env`).");
    let mut client = Client::new(&creds, Handler).unwrap();
    client.start().unwrap();
}

struct Handler;
impl EventHandler for Handler {
    fn ready(&self, ctx: Context, _: Ready) {
        ctx.set_presence(Some(Game::playing("Rust")), OnlineStatus::Online)
    }

    fn message(&self, ctx: Context, msg: Message) {
        if msg.content.chars().next() == Some('!') {
            let mut tokens = msg.content[1..].split_whitespace();
            let maybe_command = tokens.next();
            let args = tokens.collect::<Vec<_>>();

            if let Some(command) = maybe_command {
                if let Some(command_handler) = COMMAND_MAP.get(command) {
                    let valid_arg_range = command_handler.required_arg_count();
                    if valid_arg_range.contains(args.len()) {
                        command_handler.exec(&ctx, &msg, &*args);
                    } else {
                        msg.reply(&format!(
                            "This command requires {} to {} arguments.",
                            valid_arg_range.start, valid_arg_range.end
                        )).unwrap();
                    }
                } else {
                    msg.reply(&format!("Unknown command: {}", command)).unwrap();
                }
            } else {
                msg.reply("No command specified.").unwrap();
            }
        }
    }
}

struct Help;
impl Command for Help {
    fn required_arg_count(&self) -> RangeInclusive<usize> {
        0..=0
    }

    fn exec(&self, _ctx: &Context, msg: &Message, _args: &[&str]) {
        let help_output = COMMAND_MAP
            .keys()
            .intersperse(&", !")
            .fold("Available commands:\n!".to_owned(), |output, command| {
                output + command
            });

        msg.channel_id.say(&help_output).unwrap();
    }
}

struct Flip;
impl Command for Flip {
    fn required_arg_count(&self) -> RangeInclusive<usize> {
        0..=0
    }

    fn exec(&self, _ctx: &Context, msg: &Message, _args: &[&str]) {
        if rand::thread_rng().gen() {
            msg.reply("Heads!").unwrap();
        } else {
            msg.reply("Tails!").unwrap();
        }
    }
}

struct Roll;
impl Command for Roll {
    fn required_arg_count(&self) -> RangeInclusive<usize> {
        0..=1
    }

    fn exec(&self, _ctx: &Context, msg: &Message, args: &[&str]) {
        let upper_bound = if args.len() == 0 {
            6
        } else if args.len() == 1 {
            if let Ok(num) = args[0].parse() {
                num
            } else {
                msg.reply("That is not a number.").unwrap();
                return;
            }
        } else {
            unreachable!();
        };

        if upper_bound <= 0 {
            msg.reply("The upper bound must be a positive number.")
                .unwrap();
        } else {
            let result = rand::thread_rng().gen_range(0, upper_bound) + 1;
            msg.reply(&format!("{}", result)).unwrap();
        }
    }
}
<commit_msg>Switch to collections_range, it's less likely to break in the future.<commit_after>#![feature(collections_range, range_contains)]

extern crate dotenv;
extern crate itertools;
#[macro_use]
extern crate lazy_static;
extern crate rand;
extern crate serenity;

use std::collections::BTreeMap;
use std::collections::range::RangeArgument;
use std::env;
use std::ops::RangeInclusive;

use dotenv::dotenv;
use itertools::Itertools;
use rand::Rng;
use serenity::prelude::*;
use serenity::model::prelude::*;

trait Command {
    fn required_arg_count(&self) -> RangeInclusive<usize>; //impl RangeArgument<usize>;
    fn exec(&self, ctx: &Context, msg: &Message, args: &[&str]);
}
type CommandMap = BTreeMap<&'static str, Box<Command + Sync>>;

lazy_static! {
    static ref COMMAND_MAP: CommandMap = {
        let mut commands = CommandMap::new();
        commands.insert("help", Box::new(Help));
        commands.insert("flip", Box::new(Flip));
        commands.insert("roll", Box::new(Roll));
        commands
    };
}

fn main() {
    let _ = dotenv();

    let creds = env::var("Z_CREDENTIALS")
        .expect("Unspecified credentials: set Z_CREDENTIALS in the environment (or in `.env`).");
    let mut client = Client::new(&creds, Handler).unwrap();
    client.start().unwrap();
}

struct Handler;
impl EventHandler for Handler {
    fn ready(&self, ctx: Context, _: Ready) {
        ctx.set_presence(Some(Game::playing("Rust")), OnlineStatus::Online)
    }

    fn message(&self, ctx: Context, msg: Message) {
        if msg.content.chars().next() == Some('!') {
            let mut tokens = msg.content[1..].split_whitespace();
            let maybe_command = tokens.next();
            let args = tokens.collect::<Vec<_>>();

            if let Some(command) = maybe_command {
                if let Some(command_handler) = COMMAND_MAP.get(command) {
                    let valid_arg_range = command_handler.required_arg_count();
                    if valid_arg_range.contains(args.len()) {
                        command_handler.exec(&ctx, &msg, &*args);
                    } else {
                        msg.reply(&format!(
                            "This command requires {:?} to {:?} arguments.",
                            valid_arg_range.start(),
                            valid_arg_range.end()
                        )).unwrap();
                    }
                } else {
                    msg.reply(&format!("Unknown command: {}", command)).unwrap();
                }
            } else {
                msg.reply("No command specified.").unwrap();
            }
        }
    }
}

struct Help;
impl Command for Help {
    fn required_arg_count(&self) -> RangeInclusive<usize> {
        0..=0
    }

    fn exec(&self, _ctx: &Context, msg: &Message, _args: &[&str]) {
        let help_output = COMMAND_MAP
            .keys()
            .intersperse(&", !")
            .fold("Available commands:\n!".to_owned(), |output, command| {
                output + command
            });

        msg.channel_id.say(&help_output).unwrap();
    }
}

struct Flip;
impl Command for Flip {
    fn required_arg_count(&self) -> RangeInclusive<usize> {
        0..=0
    }

    fn exec(&self, _ctx: &Context, msg: &Message, _args: &[&str]) {
        if rand::thread_rng().gen() {
            msg.reply("Heads!").unwrap();
        } else {
            msg.reply("Tails!").unwrap();
        }
    }
}

struct Roll;
impl Command for Roll {
    fn required_arg_count(&self) -> RangeInclusive<usize> {
        0..=1
    }

    fn exec(&self, _ctx: &Context, msg: &Message, args: &[&str]) {
        let upper_bound = if args.len() == 0 {
            6
        } else if args.len() == 1 {
            if let Ok(num) = args[0].parse() {
                num
            } else {
                msg.reply("That is not a number.").unwrap();
                return;
            }
        } else {
            unreachable!();
        };

        if upper_bound <= 0 {
            msg.reply("The upper bound must be a positive number.")
                .unwrap();
        } else {
            let result = rand::thread_rng().gen_range(0, upper_bound) + 1;
            msg.reply(&format!("{}", result)).unwrap();
        }
    }
}
<|endoftext|>


<commit_before>#[cfg(not(windows))]
compile_error!("This demo only runs on Windows.");

extern crate directcomposition;
extern crate winit;

use winit::os::windows::WindowExt;

fn main() {
    let mut events_loop = winit::EventsLoop::new();
    let window = winit::WindowBuilder::new()
        .with_title("Hello, world!")
        .with_dimensions(1024, 768)
        .build(&events_loop)
        .unwrap();

    let composition = unsafe {
        directcomposition::DirectComposition::new(window.get_hwnd() as _).unwrap()
    };

    let visual = composition.create_d3d_visual(300, 200).unwrap();
    visual.set_offset_x(100.).unwrap();
    visual.set_offset_y(50.).unwrap();
    composition.commit().unwrap();

    let green_rgba = [0., 0.5, 0., 1.];
    visual.render_and_present_solid_frame(&composition, &green_rgba).unwrap();

    if std::env::var_os("INIT_ONLY").is_some() {
        return
    }

    events_loop.run_forever(|event| match event {
        winit::Event::WindowEvent { event: winit::WindowEvent::Closed, .. } => {
            winit::ControlFlow::Break
        }
        _ => winit::ControlFlow::Continue,
    });
}
<commit_msg>Move demo app’s unsafe code into a safe function<commit_after>#[cfg(not(windows))]
compile_error!("This demo only runs on Windows.");

extern crate directcomposition;
extern crate winit;

use directcomposition::DirectComposition;
use winit::os::windows::WindowExt;

fn main() {
    let mut events_loop = winit::EventsLoop::new();
    let window = winit::WindowBuilder::new()
        .with_title("Hello, world!")
        .with_dimensions(1024, 768)
        .build(&events_loop)
        .unwrap();

    let composition = direct_composition_from_window(&window);

    let visual = composition.create_d3d_visual(300, 200).unwrap();
    visual.set_offset_x(100.).unwrap();
    visual.set_offset_y(50.).unwrap();
    composition.commit().unwrap();

    let green_rgba = [0., 0.5, 0., 1.];
    visual.render_and_present_solid_frame(&composition, &green_rgba).unwrap();

    if std::env::var_os("INIT_ONLY").is_some() {
        return
    }

    events_loop.run_forever(|event| match event {
        winit::Event::WindowEvent { event: winit::WindowEvent::Closed, .. } => {
            winit::ControlFlow::Break
        }
        _ => winit::ControlFlow::Continue,
    });
}

fn direct_composition_from_window(window: &winit::Window) -> DirectComposition {
    unsafe {
        DirectComposition::new(window.get_hwnd() as _).unwrap()
    }
}
<|endoftext|>


<commit_before>use std::{io, os, char, result};

fn print_usage(exe_name: &str) {
   println!("Usage: {} <filename>", exe_name);
}

struct Board {
   data: [[u8, ..9], ..9]
}

#[deriving(Show)]
struct Pos {
   i: uint,
   j: uint
}

impl Board {
   fn new() -> Board {
      Board { data: [[0, ..9], ..9] }
   }

   #[inline(always)]
   fn get(&self, i: uint , j: uint) -> u8 {
      self.data[i][j]
   }

   #[inline(always)]
   fn get_pos(&self, pos: &Pos) -> u8 {
      self.data[pos.i][pos.j]
   }

   /* Unused.
   #[inline(always)]
   fn set(&mut self, v: u8, i: uint, j: uint) {
      self.data[i][j] = v;
   }*/

   #[inline(always)]
   fn set_pos(&mut self, v: u8, pos: &Pos) {
      self.data[pos.i][pos.j] = v;
   }

   fn write(&self, output: &mut io::Writer) -> Result<(), io::IoError> {
      for i in range(0, self.data.len()) {
         for j in range(0, self.data[i].len()) {
            try!(output.write_uint(self.data[i][j] as uint));
            if (j + 1) % 3 == 0 && j != self.data[i].len() - 1 {
               try!(output.write_str("|"));
            }
         }

         try!(output.write_str("\n"));

         if (i + 1) % 3 == 0 && i != self.data.len() - 1 {

          try!(output.write_line("-----------"));
         }
      }

      result::Ok(())
   }

   fn read(input: &mut io::Reader) -> Result<Board, io::IoError> {
      let mut board = Board::new();
      {
         let mut pos = Pos { i: 0, j: 0 }; // Current position

         let assign = |v: u8| -> bool {
            board.set_pos(v, &pos);
            if pos.i == 8 && pos.j == 8 {
               true
            } else {
               pos = Board::next(pos);
               false
            }
         };

         loop {
            match input.read_byte() {
               Ok(byte) => {
                  let c = byte as char;
                  if c == ' ' || c == '.' {
                     if assign(0u8) {
                        break;
                     }
                  } else {
                     match char::to_digit(byte as char, 10){
                        Some(v) => {
                           if assign(v as u8) {
                              break;
                           }
                        },
                        None => continue
                     };
                  }
               },
               Err(err) =>
                  return Err(err)
            }
         }
      }

      Ok(board)
   }

   /**
     * Returns the next position. The first position is returned if the given position is the last.
     */
   #[inline(always)]
   fn next(pos: Pos) -> Pos {
      let mut next_pos = pos;
      next_pos.j += 1;
      if next_pos.j >= 9 {
         next_pos.j = 0;
         next_pos.i += 1;
         if next_pos.i >= 9 {
            next_pos.i = 0;
         }
      };
      next_pos
   }

   /**
     * Returns the next free position (containing a 0).
     */
   #[inline(always)]
   fn next_free(&self, pos: Pos) -> Option<Pos> {
      let mut current = pos;

      loop {
         if current.i == 8 && current.j == 8 {
            return None;
         }

         current = Board::next(current);

         if self.get_pos(&current) == 0 {
            return Some(current);
         }
      }
   }

   /**
     * Return 0 if there is some or no valid number else return the number.
     */
   fn the_only_valid_number(&self, pos: &Pos) -> u8 {
      let mut numbers = [false, ..10];
      let mut nb = 0i;

      fn get_empty_number(ns: &[bool, ..10]) -> u8 {
         for n in range(1, 10){
            if !ns[n] {
               return n as u8;
            }
         }
         0
      }

      // First checks if the column of the given position is valid.
      for i in range(0, 9) {
         let p = self.get(i, pos.j);
         if p == 0 {
            continue;
         }
         if !numbers[p as uint] {
            numbers[p as uint] = true;
            nb += 1;
         }
      }

      // First checks if the row of the given position is valid.
      for j in range(0, 9) {
         let p = self.get(pos.i, j);
         if p == 0 {
            continue;
         }
         if !numbers[p as uint] {
            numbers[p as uint] = true;
            nb += 1;
         }
      }

      // Then check if the 3x3 square is valid.
      let i_top = if pos.i <= 2 { 0 } else if pos.i <= 5 { 3 } else { 6 };
      let j_top = if pos.j <= 2 { 0 } else if pos.j <= 5 { 3 } else { 6 };
      for i in range(i_top, i_top + 3) {
         for j in range(j_top, j_top + 3) {
            let p = self.get(i, j);
            if p == 0 {
               continue;
            }
            if !numbers[p as uint] {
               numbers[p as uint] = true;
               nb += 1;
            }
         }
      }

      if nb == 8 {
         return get_empty_number(&numbers);
      }

      if nb == 9 {
         return 0;
      }

      for n in range(0, 9){
         if !numbers[n] {
            // Column.
            let mut valid = false;
            for i in range(0, 9) {
               if i == pos.i || self.get(i, pos.j) != 0 {
                  continue;
               }
               if self.is_position_valid_with(&Pos { i: i, j: pos.j }, n as u8) {
                  valid = true;
                  break;
               }
            }
            if !valid {
               return n as u8;
            }

            // Row.
            let mut valid = false;
            for j in range(0, 9) {
               if j == pos.j || self.get(pos.i, j) != 0 {
                  continue;
               }
               if self.is_position_valid_with(&Pos { i: pos.i, j: j }, n as u8) {
                  valid = true;
                  break;
               }
            }
            if !valid {
               return n as u8;
            }

            // Square.
            let mut valid = false;
            let i_top = if pos.i <= 2 { 0 } else if pos.i <= 5 { 3 } else { 6 };
            let j_top = if pos.j <= 2 { 0 } else if pos.j <= 5 { 3 } else { 6 };
            for i in range(i_top, i_top + 3) {
               for j in range(j_top, j_top + 3) {
                  if i == pos.i && j == pos.j || self.get(i, j) != 0 {
                     continue;
                  }
                  if self.is_position_valid_with(&Pos { i: i, j: j }, n as u8) {
                     valid = true;
                     break;
                  }
               }
            }

            if !valid {
               return n as u8;
            }
         }
      }

      0u8
   }

   fn is_position_valid(&self, pos: &Pos) -> bool {
      self.is_position_valid_with(pos, self.get_pos(pos))
   }

   fn is_position_valid_with(&self, pos: &Pos, n: u8) -> bool {
      // First checks if the column of the given position is valid.
      for i in range(0, 9) {
         if i == pos.i {
            continue;
         }
         let p = self.get(i, pos.j);
         if p != 0 && p == n {
            return false;
         }
      }

      // First checks if the row of the given position is valid.
      for j in range(0, 9) {
         if j == pos.j {
            continue;
         }
         let p = self.get(pos.i, j);
         if p != 0 && p == n {
            return false;
         }
      }

      // Then check if the 3x3 square is valid.
      let i_top = if pos.i <= 2 { 0 } else if pos.i <= 5 { 3 } else { 6 };
      let j_top = if pos.j <= 2 { 0 } else if pos.j <= 5 { 3 } else { 6 };

      for i in range(i_top, i_top + 3) {
         for j in range(j_top, j_top + 3) {
            if i == pos.i && j == pos.j {
               continue;
            }
            let p = self.get(i, j);
            if p != 0 && p == n {
               return false;
            }
         }
      }
      true
   }

   fn pre_solve_with_constraints(&mut self) {
      let mut current_pos = Pos { i: 0, j: -1 };
      let mut number_inserted = false;

      loop {
         match self.next_free(current_pos) {
            Some(p) => current_pos = p,
            None if number_inserted => {
               number_inserted = false;
               current_pos = Pos { i: 0, j: 0 };
               continue
            },
            _ =>
               return
         }

         let v = self.the_only_valid_number(&current_pos);

         if v != 0 {
            self.set_pos(v, &current_pos);
            number_inserted = true;
         }
      }
   }

   fn solve(&mut self)
   {
      self.pre_solve_with_constraints();

      let mut current_pos = Pos { i: 0, j: -1 };
      let mut previous_positions: Vec<Pos> = vec![];

      loop {
         match self.next_free(current_pos) {
            Some(p) => current_pos = p,
            None => return
         }

         loop {
            let n = self.get_pos(&current_pos) + 1;
            self.set_pos(n, &current_pos);
            if self.is_position_valid(&current_pos) {
               previous_positions.push(current_pos);
               break;
            }

            while self.get_pos(&current_pos) == 9 {
               self.set_pos(0, &current_pos);
               match previous_positions.pop() {
                  Some(p) => current_pos = p,
                  None => return
               }
            }
         }
      }
   }
}

fn main() {
   if os::args().len() != 2 {
      return print_usage(os::args()[0].as_slice());
   }

   let mut n = 1i;
   let mut source = io::BufferedReader::new(io::File::open(&Path::new(os::args()[1].as_slice())));

   loop {
      match Board::read(&mut source) {
         Ok(ref mut board) => {
            println!("{}) #############", n);
            n += 1;

            match board.write(&mut io::stdio::stdout()) {
               Ok(_) => (),
               Err(e) => {
                  println!("An error occurs when writing the initial state: {}", e);
               }
            }

            board.solve();

            println!("vvvvvvvvvvv");

            match board.write(&mut io::stdio::stdout()) {
               Ok(_) => (),
               Err(e) => {
                  println!("An error occurs when writing the result: {}", e);
               }
            }
         },
         Err(_) =>
            return
      }
   }
}
<commit_msg>Add comments.<commit_after>use std::{io, os, char, result};

fn print_usage(exe_name: &str) {
   println!("Usage: {} <filename>", exe_name);
}

struct Board {
   data: [[u8, ..9], ..9]
}

#[deriving(Show)]
struct Pos {
   i: uint,
   j: uint
}

impl Board {
   fn new() -> Board {
      Board { data: [[0, ..9], ..9] }
   }

   #[inline(always)]
   fn get(&self, i: uint , j: uint) -> u8 {
      self.data[i][j]
   }

   #[inline(always)]
   fn get_pos(&self, pos: &Pos) -> u8 {
      self.data[pos.i][pos.j]
   }

   /* Unused.
   #[inline(always)]
   fn set(&mut self, v: u8, i: uint, j: uint) {
      self.data[i][j] = v;
   }*/

   #[inline(always)]
   fn set_pos(&mut self, v: u8, pos: &Pos) {
      self.data[pos.i][pos.j] = v;
   }

   fn write(&self, output: &mut io::Writer) -> Result<(), io::IoError> {
      for i in range(0, self.data.len()) {
         for j in range(0, self.data[i].len()) {
            try!(output.write_uint(self.data[i][j] as uint));
            if (j + 1) % 3 == 0 && j != self.data[i].len() - 1 {
               try!(output.write_str("|"));
            }
         }

         try!(output.write_str("\n"));

         if (i + 1) % 3 == 0 && i != self.data.len() - 1 {

          try!(output.write_line("-----------"));
         }
      }

      result::Ok(())
   }

   fn read(input: &mut io::Reader) -> Result<Board, io::IoError> {
      let mut board = Board::new();
      {
         let mut pos = Pos { i: 0, j: 0 }; // Current position

         let assign = |v: u8| -> bool {
            board.set_pos(v, &pos);
            if pos.i == 8 && pos.j == 8 {
               true
            } else {
               pos = Board::next(pos);
               false
            }
         };

         loop {
            match input.read_byte() {
               Ok(byte) => {
                  let c = byte as char;
                  if c == ' ' || c == '.' {
                     if assign(0u8) {
                        break;
                     }
                  } else {
                     match char::to_digit(byte as char, 10){
                        Some(v) => {
                           if assign(v as u8) {
                              break;
                           }
                        },
                        None => continue
                     };
                  }
               },
               Err(err) =>
                  return Err(err)
            }
         }
      }

      Ok(board)
   }

   /**
     * Returns the next position. The first position is returned if the given position is the last.
     */
   #[inline(always)]
   fn next(pos: Pos) -> Pos {
      let mut next_pos = pos;
      next_pos.j += 1;
      if next_pos.j >= 9 {
         next_pos.j = 0;
         next_pos.i += 1;
         if next_pos.i >= 9 {
            next_pos.i = 0;
         }
      };
      next_pos
   }

   /**
     * Returns the next free position (containing a 0).
     */
   #[inline(always)]
   fn next_free(&self, pos: Pos) -> Option<Pos> {
      let mut current = pos;

      loop {
         if current.i == 8 && current.j == 8 {
            return None;
         }

         current = Board::next(current);

         if self.get_pos(&current) == 0 {
            return Some(current);
         }
      }
   }

   /**
     * Returns 0 if there is some or no valid number at the given position else returns the number.
     */
   fn the_only_valid_number(&self, pos: &Pos) -> u8 {
      let mut numbers = [false, ..10];
      let mut nb = 0i;

      fn get_empty_number(ns: &[bool, ..10]) -> u8 {
         for n in range(1, 10){
            if !ns[n] {
               return n as u8;
            }
         }
         0
      }

      // First checks if the column of the given position is valid.
      for i in range(0, 9) {
         let p = self.get(i, pos.j);
         if p == 0 {
            continue;
         }
         if !numbers[p as uint] {
            numbers[p as uint] = true;
            nb += 1;
         }
      }

      // First checks if the row of the given position is valid.
      for j in range(0, 9) {
         let p = self.get(pos.i, j);
         if p == 0 {
            continue;
         }
         if !numbers[p as uint] {
            numbers[p as uint] = true;
            nb += 1;
         }
      }

      // Then check if the 3x3 square is valid.
      let i_top = if pos.i <= 2 { 0 } else if pos.i <= 5 { 3 } else { 6 };
      let j_top = if pos.j <= 2 { 0 } else if pos.j <= 5 { 3 } else { 6 };
      for i in range(i_top, i_top + 3) {
         for j in range(j_top, j_top + 3) {
            let p = self.get(i, j);
            if p == 0 {
               continue;
            }
            if !numbers[p as uint] {
               numbers[p as uint] = true;
               nb += 1;
            }
         }
      }

      // There is eight disctinct numbers, so only one possibility remains.
      if nb == 8 {
         return get_empty_number(&numbers);
      }

      // All numbers are used, no possibility remaining..
      if nb == 9 {
         return 0;
      }

      for n in range(0, 9){
         if !numbers[n] {
            // Column.
            let mut valid = false;
            for i in range(0, 9) {
               if i == pos.i || self.get(i, pos.j) != 0 {
                  continue;
               }
               if self.is_position_valid_with(&Pos { i: i, j: pos.j }, n as u8) {
                  valid = true;
                  break;
               }
            }
            if !valid {
               return n as u8;
            }

            // Row.
            let mut valid = false;
            for j in range(0, 9) {
               if j == pos.j || self.get(pos.i, j) != 0 {
                  continue;
               }
               if self.is_position_valid_with(&Pos { i: pos.i, j: j }, n as u8) {
                  valid = true;
                  break;
               }
            }
            if !valid {
               return n as u8;
            }

            // Square.
            let mut valid = false;
            let i_top = if pos.i <= 2 { 0 } else if pos.i <= 5 { 3 } else { 6 };
            let j_top = if pos.j <= 2 { 0 } else if pos.j <= 5 { 3 } else { 6 };
            for i in range(i_top, i_top + 3) {
               for j in range(j_top, j_top + 3) {
                  if i == pos.i && j == pos.j || self.get(i, j) != 0 {
                     continue;
                  }
                  if self.is_position_valid_with(&Pos { i: i, j: j }, n as u8) {
                     valid = true;
                     break;
                  }
               }
            }

            if !valid {
               return n as u8;
            }
         }
      }

      0u8
   }

   /**
     * Is the current state of the given position valid?
     */
   fn is_position_valid(&self, pos: &Pos) -> bool {
      self.is_position_valid_with(pos, self.get_pos(pos))
   }

   /**
     * Is the given number can be put in the given position?
     */
   fn is_position_valid_with(&self, pos: &Pos, n: u8) -> bool {
      // First checks if the column of the given position is valid.
      for i in range(0, 9) {
         if i == pos.i {
            continue;
         }
         let p = self.get(i, pos.j);
         if p != 0 && p == n {
            return false;
         }
      }

      // First checks if the row of the given position is valid.
      for j in range(0, 9) {
         if j == pos.j {
            continue;
         }
         let p = self.get(pos.i, j);
         if p != 0 && p == n {
            return false;
         }
      }

      // Then check if the 3x3 square is valid.
      let i_top = if pos.i <= 2 { 0 } else if pos.i <= 5 { 3 } else { 6 };
      let j_top = if pos.j <= 2 { 0 } else if pos.j <= 5 { 3 } else { 6 };

      for i in range(i_top, i_top + 3) {
         for j in range(j_top, j_top + 3) {
            if i == pos.i && j == pos.j {
               continue;
            }
            let p = self.get(i, j);
            if p != 0 && p == n {
               return false;
            }
         }
      }
      true
   }

   /**
     * Partially solve the board by using a very simple set of constraint rules.
     */
   fn pre_solve_with_constraints(&mut self) {
      let mut current_pos = Pos { i: 0, j: -1 };
      let mut number_inserted = false;

      loop {
         match self.next_free(current_pos) {
            Some(p) => current_pos = p,
            None if number_inserted => {
               number_inserted = false;
               current_pos = Pos { i: 0, j: 0 };
               continue
            },
            _ =>
               return
         }

         let v = self.the_only_valid_number(&current_pos);

         if v != 0 {
            self.set_pos(v, &current_pos);
            number_inserted = true;
         }
      }
   }

   fn solve(&mut self)
   {
      self.pre_solve_with_constraints();

      let mut current_pos = Pos { i: 0, j: -1 };
      let mut previous_positions: Vec<Pos> = vec![];

      loop {
         match self.next_free(current_pos) {
            Some(p) => current_pos = p,
            None => return
         }

         loop {
            let n = self.get_pos(&current_pos) + 1;
            self.set_pos(n, &current_pos);
            if self.is_position_valid(&current_pos) {
               previous_positions.push(current_pos);
               break;
            }

            while self.get_pos(&current_pos) == 9 {
               self.set_pos(0, &current_pos);
               match previous_positions.pop() {
                  Some(p) => current_pos = p,
                  None => return
               }
            }
         }
      }
   }
}

fn main() {
   if os::args().len() != 2 {
      return print_usage(os::args()[0].as_slice());
   }

   let mut n = 1i;
   let mut source = io::BufferedReader::new(io::File::open(&Path::new(os::args()[1].as_slice())));

   loop {
      match Board::read(&mut source) {
         Ok(ref mut board) => {
            println!("{}) #############", n);
            n += 1;

            match board.write(&mut io::stdio::stdout()) {
               Ok(_) => (),
               Err(e) => {
                  println!("An error occurs when writing the initial state: {}", e);
               }
            }

            board.solve();

            println!("vvvvvvvvvvv");

            match board.write(&mut io::stdio::stdout()) {
               Ok(_) => (),
               Err(e) => {
                  println!("An error occurs when writing the result: {}", e);
               }
            }
         },
         Err(_) =>
            return
      }
   }
}
<|endoftext|>


<commit_before>extern crate rustc_serialize;
extern crate docopt;
extern crate hyper;

use std::io::Read;
use docopt::Docopt;
use hyper::Client;
use hyper::header::Connection;

const USAGE: &'static str = "
rustOver.

Pushover client in rust.
Create a pushover application in your Pushover Dashboard, grab the token and user token and send a message.
Take a look at -h for extra options

Usage:
    rustOver <token> <user-token> <message> [options]
    rustOver (-h | --help)

Options
  --title=<title>          Title of the message, otherwise the App name is used.
  --devices=<devices>      List of devices to send the message to, seperated by comma.
  --url=<url>              Supplementary url to show with your message.
  --url-title=<url_title>  A title for your supplementary URL, otherwise just the url is shown.
  --priority=<n>           Priority of the message -2..2 (low..high).
  --timestamp=<unix_t>     Unix timestamp to be added to the message.
  --sound=<sound>	   Sound to be played on receiving the message.
  --use-html               Enable the usage of HTML in Message.
  -h --help     Show this screen.
  -v            Verbose mode
";

#[derive(Debug, RustcDecodable)]
struct Args {
    flag_title: Vec<String>,
    flag_devices: Vec<String>,
    flag_url: Vec<String>,
    flag_url_title: Vec<String>,
    flag_priority: Vec<String>,
    flag_timestamp: Option<i64>,
    flag_sound: Vec<String>,
    flag_use_html: bool,
    flag_v: bool,
    arg_token: String,
    arg_user_token: String,
    arg_message: String
}

fn main() {
    let args: Args = Docopt::new(USAGE)
                            .and_then(|d| d.decode())
                            .unwrap_or_else(|e| e.exit());
    if args.flag_v
    {
	println!("{:?}", args);
    }

    let mut pushMsg = String::from("token=");
    pushMsg.push_str(&args.arg_token);
    pushMsg.push_str("&user=");
    pushMsg.push_str(&args.arg_user_token);
    pushMsg.push_str("&message=");
    pushMsg.push_str(&args.arg_message);

    println!("pushMsg:str {}",pushMsg);

    let mut client = Client::new();

    let mut resp = client.post("https://api.pushover.net/1/messages.json")
	.body(&pushMsg)
	.send().unwrap();

    let mut body = String::new();
    resp.read_to_string(&mut body).unwrap();

    println!("Response: {}", body);

}

<commit_msg>Added the --use-html option<commit_after>extern crate rustc_serialize;
extern crate docopt;
extern crate hyper;

use std::io::Read;
use docopt::Docopt;
use hyper::Client;
use hyper::header::Connection;

const USAGE: &'static str = "
rustOver.

Pushover client in rust.
Create a pushover application in your Pushover Dashboard, grab the token and user token and send a message.
Take a look at -h for extra options

Usage:
    rustOver <token> <user-token> <message> [options]
    rustOver (-h | --help)

Options
  --title=<title>          Title of the message, otherwise the App name is used.
  --devices=<devices>      List of devices to send the message to, seperated by comma.
  --url=<url>              Supplementary url to show with your message.
  --url-title=<url_title>  A title for your supplementary URL, otherwise just the url is shown.
  --priority=<n>           Priority of the message -2..2 (low..high).
  --timestamp=<unix_t>     Unix timestamp to be added to the message.
  --sound=<sound>	   Sound to be played on receiving the message.
  --use-html               Enable the usage of HTML in Message.
  -h --help     Show this screen.
  -v            Verbose mode
";

#[derive(Debug, RustcDecodable)]
struct Args {
    flag_title: Vec<String>,
    flag_devices: Vec<String>,
    flag_url: Vec<String>,
    flag_url_title: Vec<String>,
    flag_priority: Vec<String>,
    flag_timestamp: Option<i64>,
    flag_sound: Vec<String>,
    flag_use_html: bool,
    flag_v: bool,
    arg_token: String,
    arg_user_token: String,
    arg_message: String
}

fn main() {
    let args: Args = Docopt::new(USAGE)
                            .and_then(|d| d.decode())
                            .unwrap_or_else(|e| e.exit());
    if args.flag_v
    {
	println!("{:?}", args);
    }

    let mut pushMsg = String::from("token=");
    pushMsg.push_str(&args.arg_token);
    pushMsg.push_str("&user=");
    pushMsg.push_str(&args.arg_user_token);
    pushMsg.push_str("&message=");
    pushMsg.push_str(&args.arg_message);

    if args.flag_use_html
    {
        pushMsg.push_str("&html=1");
    }

    println!("pushMsg:str {}",pushMsg);

    let mut client = Client::new();

    let mut resp = client.post("https://api.pushover.net/1/messages.json")
	.body(&pushMsg)
	.send().unwrap();

    let mut body = String::new();
    resp.read_to_string(&mut body).unwrap();

    println!("Response: {}", body);

}

<|endoftext|>


<commit_before>use std::fmt;
use std::str::FromStr;

use util::OptionBorrowExt;

/// Represents a qualified XML name.
///
/// A qualified name always consists at least of a local name. It can optionally contain
/// a prefix; if it contains a prefix, it must also contain a namespace URI, but this is not
/// enforced statically; see below. The name can contain a namespace without a prefix; in
/// that case a default, empty prefix is assumed.
///
/// # Prefixes and URIs
///
/// A qualified name with a prefix must always contain a proper namespace URI --- names with
/// a prefix but without a namespace associated with that prefix are meaningless. However,
/// it is impossible to obtain proper namespace URI by a prefix without a context, and such
/// context is only available when parsing a document (or it can be constructed manually
/// when writing a document). Tying a name to a context statically seems impractical. This
/// may change in future, though.
#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
pub struct Name<'a> {
    /// A local name, e.g. `string` in `xsi:string`.
    pub local_name: &'a str,

    /// A namespace URI, e.g. `http://www.w3.org/2000/xmlns/`.
    pub namespace: Option<&'a str>,

    /// A name prefix, e.g. `xsi` in `xsi:string`.
    pub prefix: Option<&'a str>
}

impl<'a> fmt::Display for Name<'a> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        if let Some(namespace) = self.namespace {
            try! { write!(f, "{{{}}}", namespace) }
        }

        if let Some(prefix) = self.prefix {
            try! { write!(f, "{}:", prefix) }
        }

        write!(f, "{}", self.local_name)
    }
}

impl<'a> Name<'a> {
    /// Returns an owned variant of the qualified name.
    pub fn to_owned(&self) -> OwnedName {
        OwnedName {
            local_name: self.local_name.into(),
            namespace: self.namespace.map(|s| s.into()),
            prefix: self.prefix.map(|s| s.into())
        }
    }

    /// Returns a new `Name` instance representing plain local name.
    #[inline]
    pub fn local(local_name: &str) -> Name {
        Name {
            local_name: local_name,
            prefix: None,
            namespace: None
        }
    }

    /// Returns a new `Name` instance representing a qualified name with or without a prefix and
    /// with a namespace URI.
    #[inline]
    pub fn qualified(local_name: &'a str, namespace: &'a str, prefix: Option<&'a str>) -> Name<'a> {
        Name {
            local_name: local_name,
            namespace: Some(namespace),
            prefix: prefix,
        }
    }

    /// Returns correct XML representation of this local name and prefix.
    ///
    /// This method is different from the autoimplemented `to_string()` because it does not
    /// include namespace URI in the result.
    pub fn to_repr(&self) -> String {
        match self.prefix {
            Some(prefix) => format!("{}:{}", prefix, self.local_name),
            None => self.local_name.into()
        }
    }
}

/// An owned variant of `Name`.
///
/// Everything about `Name` applies to this structure as well.
#[derive(Clone, PartialEq, Eq, Hash, Debug)]
pub struct OwnedName {
    /// A local name, e.g. `string` in `xsi:string`.
    pub local_name: String,

    /// A namespace URI, e.g. `http://www.w3.org/2000/xmlns/`.
    pub namespace: Option<String>,

    /// A name prefix, e.g. `xsi` in `xsi:string`.
    pub prefix: Option<String>,
}

impl fmt::Display for OwnedName {
    #[inline]
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        fmt::Display::fmt(&self.borrow(), f)
    }
}

impl OwnedName {
    /// Constructs a borrowed `Name` based on this owned name.
    pub fn borrow(&self) -> Name {
        Name {
            local_name: &*self.local_name,
            namespace: self.namespace.as_ref().map(|s| &**s),
            prefix: self.prefix.as_ref().map(|s| &**s),
        }
    }

    /// Returns a new `OwnedName` instance representing a plain local name.
    #[inline]
    pub fn local<S>(local_name: S) -> OwnedName where S: Into<String> {
        OwnedName {
            local_name: local_name.into(),
            namespace: None,
            prefix: None,
        }
    }

    /// Returns a new `OwnedName` instance representing a qualified name with or without
    /// a prefix and with a namespace URI.
    #[inline]
    pub fn qualified<S1, S2, S3>(local_name: S1, namespace: S2, prefix: Option<S3>) -> OwnedName
        where S1: Into<String>, S2: Into<String>, S3: Into<String>
    {
        OwnedName {
            local_name: local_name.into(),
            namespace: Some(namespace.into()),
            prefix: prefix.map(|v| v.into())
        }
    }

    /// Returns an optional prefix by reference, equivalent to `self.borrow().prefix`
    /// but avoids extra work.
    #[inline]
    pub fn prefix_as_ref(&self) -> Option<&str> {
        self.prefix.borrow_internals()
    }

    /// Returns an optional namespace by reference, equivalen to `self.borrow().namespace`
    /// but avoids extra work.
    #[inline]
    pub fn namespace_as_ref(&self) -> Option<&str> {
        self.namespace.borrow_internals()
    }

    /// See `Name::to_repr()` for details.
    #[inline]
    pub fn to_repr(&self) -> String {
        self.borrow().to_repr()
    }
}

impl<'a> From<Name<'a>> for OwnedName {
    #[inline]
    fn from(n: Name<'a>) -> OwnedName {
        n.to_owned()
    }
}

impl FromStr for OwnedName {
    type Err = ();

    /// Parses the given string slice into a qualified name.
    ///
    /// This function, when finishes sucessfully, always return a qualified
    /// name without a namespace (`name.namespace == None`). It should be filled later
    /// using proper `NamespaceStack`.
    ///
    /// It is supposed that all characters in the argument string are correct
    /// as defined by the XML specification. No additional checks except a check
    /// for emptiness are done.
    fn from_str(s: &str) -> Result<OwnedName, ()> {
        let mut it = s.split(':');

        let r = match (it.next(), it.next(), it.next()) {
            (Some(prefix), Some(local_name), None) if !prefix.is_empty() &&
                                                      !local_name.is_empty() =>
                Some((local_name.into(), Some(prefix.into()))),
            (Some(local_name), None, None) if !local_name.is_empty() =>
                Some((local_name.into(), None)),
            (_, _, _) => None
        };
        r.map(|(local_name, prefix)| OwnedName {
            local_name: local_name,
            namespace: None,
            prefix: prefix
        }).ok_or(())
    }
}

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

    #[test]
    fn test_owned_name_from_str() {
        assert_eq!("prefix:name".parse(), Ok(OwnedName {
            local_name: "name".into(),
            namespace: None,
            prefix: Some("prefix".into())
        }));

        assert_eq!("name".parse(), Ok(OwnedName {
            local_name: "name".into(),
            namespace: None,
            prefix: None
        }));

        assert_eq!("".parse(), Err::<OwnedName, ()>(()));
        assert_eq!(":".parse(), Err::<OwnedName, ()>(()));
        assert_eq!(":a".parse(), Err::<OwnedName, ()>(()));
        assert_eq!("a:".parse(), Err::<OwnedName, ()>(()));
        assert_eq!("a:b:c".parse(), Err::<OwnedName, ()>(()));
    }
}
<commit_msg>Added more borrow_internals() usage<commit_after>use std::fmt;
use std::str::FromStr;

use util::OptionBorrowExt;

/// Represents a qualified XML name.
///
/// A qualified name always consists at least of a local name. It can optionally contain
/// a prefix; if it contains a prefix, it must also contain a namespace URI, but this is not
/// enforced statically; see below. The name can contain a namespace without a prefix; in
/// that case a default, empty prefix is assumed.
///
/// # Prefixes and URIs
///
/// A qualified name with a prefix must always contain a proper namespace URI --- names with
/// a prefix but without a namespace associated with that prefix are meaningless. However,
/// it is impossible to obtain proper namespace URI by a prefix without a context, and such
/// context is only available when parsing a document (or it can be constructed manually
/// when writing a document). Tying a name to a context statically seems impractical. This
/// may change in future, though.
#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
pub struct Name<'a> {
    /// A local name, e.g. `string` in `xsi:string`.
    pub local_name: &'a str,

    /// A namespace URI, e.g. `http://www.w3.org/2000/xmlns/`.
    pub namespace: Option<&'a str>,

    /// A name prefix, e.g. `xsi` in `xsi:string`.
    pub prefix: Option<&'a str>
}

impl<'a> fmt::Display for Name<'a> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        if let Some(namespace) = self.namespace {
            try! { write!(f, "{{{}}}", namespace) }
        }

        if let Some(prefix) = self.prefix {
            try! { write!(f, "{}:", prefix) }
        }

        write!(f, "{}", self.local_name)
    }
}

impl<'a> Name<'a> {
    /// Returns an owned variant of the qualified name.
    pub fn to_owned(&self) -> OwnedName {
        OwnedName {
            local_name: self.local_name.into(),
            namespace: self.namespace.map(|s| s.into()),
            prefix: self.prefix.map(|s| s.into())
        }
    }

    /// Returns a new `Name` instance representing plain local name.
    #[inline]
    pub fn local(local_name: &str) -> Name {
        Name {
            local_name: local_name,
            prefix: None,
            namespace: None
        }
    }

    /// Returns a new `Name` instance representing a qualified name with or without a prefix and
    /// with a namespace URI.
    #[inline]
    pub fn qualified(local_name: &'a str, namespace: &'a str, prefix: Option<&'a str>) -> Name<'a> {
        Name {
            local_name: local_name,
            namespace: Some(namespace),
            prefix: prefix,
        }
    }

    /// Returns correct XML representation of this local name and prefix.
    ///
    /// This method is different from the autoimplemented `to_string()` because it does not
    /// include namespace URI in the result.
    pub fn to_repr(&self) -> String {
        match self.prefix {
            Some(prefix) => format!("{}:{}", prefix, self.local_name),
            None => self.local_name.into()
        }
    }
}

/// An owned variant of `Name`.
///
/// Everything about `Name` applies to this structure as well.
#[derive(Clone, PartialEq, Eq, Hash, Debug)]
pub struct OwnedName {
    /// A local name, e.g. `string` in `xsi:string`.
    pub local_name: String,

    /// A namespace URI, e.g. `http://www.w3.org/2000/xmlns/`.
    pub namespace: Option<String>,

    /// A name prefix, e.g. `xsi` in `xsi:string`.
    pub prefix: Option<String>,
}

impl fmt::Display for OwnedName {
    #[inline]
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        fmt::Display::fmt(&self.borrow(), f)
    }
}

impl OwnedName {
    /// Constructs a borrowed `Name` based on this owned name.
    pub fn borrow(&self) -> Name {
        Name {
            local_name: &*self.local_name,
            namespace: self.namespace.borrow_internals(),
            prefix: self.prefix.borrow_internals(),
        }
    }

    /// Returns a new `OwnedName` instance representing a plain local name.
    #[inline]
    pub fn local<S>(local_name: S) -> OwnedName where S: Into<String> {
        OwnedName {
            local_name: local_name.into(),
            namespace: None,
            prefix: None,
        }
    }

    /// Returns a new `OwnedName` instance representing a qualified name with or without
    /// a prefix and with a namespace URI.
    #[inline]
    pub fn qualified<S1, S2, S3>(local_name: S1, namespace: S2, prefix: Option<S3>) -> OwnedName
        where S1: Into<String>, S2: Into<String>, S3: Into<String>
    {
        OwnedName {
            local_name: local_name.into(),
            namespace: Some(namespace.into()),
            prefix: prefix.map(|v| v.into())
        }
    }

    /// Returns an optional prefix by reference, equivalent to `self.borrow().prefix`
    /// but avoids extra work.
    #[inline]
    pub fn prefix_as_ref(&self) -> Option<&str> {
        self.prefix.borrow_internals()
    }

    /// Returns an optional namespace by reference, equivalen to `self.borrow().namespace`
    /// but avoids extra work.
    #[inline]
    pub fn namespace_as_ref(&self) -> Option<&str> {
        self.namespace.borrow_internals()
    }

    /// See `Name::to_repr()` for details.
    #[inline]
    pub fn to_repr(&self) -> String {
        self.borrow().to_repr()
    }
}

impl<'a> From<Name<'a>> for OwnedName {
    #[inline]
    fn from(n: Name<'a>) -> OwnedName {
        n.to_owned()
    }
}

impl FromStr for OwnedName {
    type Err = ();

    /// Parses the given string slice into a qualified name.
    ///
    /// This function, when finishes sucessfully, always return a qualified
    /// name without a namespace (`name.namespace == None`). It should be filled later
    /// using proper `NamespaceStack`.
    ///
    /// It is supposed that all characters in the argument string are correct
    /// as defined by the XML specification. No additional checks except a check
    /// for emptiness are done.
    fn from_str(s: &str) -> Result<OwnedName, ()> {
        let mut it = s.split(':');

        let r = match (it.next(), it.next(), it.next()) {
            (Some(prefix), Some(local_name), None) if !prefix.is_empty() &&
                                                      !local_name.is_empty() =>
                Some((local_name.into(), Some(prefix.into()))),
            (Some(local_name), None, None) if !local_name.is_empty() =>
                Some((local_name.into(), None)),
            (_, _, _) => None
        };
        r.map(|(local_name, prefix)| OwnedName {
            local_name: local_name,
            namespace: None,
            prefix: prefix
        }).ok_or(())
    }
}

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

    #[test]
    fn test_owned_name_from_str() {
        assert_eq!("prefix:name".parse(), Ok(OwnedName {
            local_name: "name".into(),
            namespace: None,
            prefix: Some("prefix".into())
        }));

        assert_eq!("name".parse(), Ok(OwnedName {
            local_name: "name".into(),
            namespace: None,
            prefix: None
        }));

        assert_eq!("".parse(), Err::<OwnedName, ()>(()));
        assert_eq!(":".parse(), Err::<OwnedName, ()>(()));
        assert_eq!(":a".parse(), Err::<OwnedName, ()>(()));
        assert_eq!("a:".parse(), Err::<OwnedName, ()>(()));
        assert_eq!("a:b:c".parse(), Err::<OwnedName, ()>(()));
    }
}
<|endoftext|>


<commit_before>use error::Error;
use num_traits::NumCast;
use serde::de::{self, Visitor};
use serde::{Serialize, Serializer, Deserialize, Deserializer};
use std::{fmt, i64};

/// Represents a JSON number, whether integer or floating point.
#[derive(Clone, PartialEq)]
pub struct Number(N);

// "N" is a prefix of "NegInt"... this is a false positive.
// https://github.com/Manishearth/rust-clippy/issues/1241
#[cfg_attr(feature = "clippy", allow(pub_enum_variant_names))]
#[derive(Copy, Clone, Debug, PartialEq)]
enum N {
    PosInt(u64),
    /// Always less than zero.
    NegInt(i64),
    /// Always finite.
    Float(f64),
}

impl Number {
    /// Returns true if the number can be represented by i64.
    #[inline]
    pub fn is_i64(&self) -> bool {
        match self.0 {
            N::PosInt(v) => v <= i64::MAX as u64,
            N::NegInt(_) => true,
            N::Float(_) => false,
        }
    }

    /// Returns true if the number can be represented as u64.
    #[inline]
    pub fn is_u64(&self) -> bool {
        match self.0 {
            N::PosInt(_) => true,
            N::NegInt(_) | N::Float(_) => false,
        }
    }

    /// Returns true if the number can be represented as f64.
    #[inline]
    pub fn is_f64(&self) -> bool {
        match self.0 {
            N::Float(_) => true,
            N::PosInt(_) | N::NegInt(_) => false,
        }
    }

    /// Returns the number represented as i64 if possible, or else None.
    #[inline]
    pub fn as_i64(&self) -> Option<i64> {
        match self.0 {
            N::PosInt(n) => NumCast::from(n),
            N::NegInt(n) => Some(n),
            N::Float(_) => None,
        }
    }

    /// Returns the number represented as u64 if possible, or else None.
    #[inline]
    pub fn as_u64(&self) -> Option<u64> {
        match self.0 {
            N::PosInt(n) => Some(n),
            N::NegInt(n) => NumCast::from(n),
            N::Float(_) => None,
        }
    }

    /// Returns the number represented as f64 if possible, or else None.
    #[inline]
    pub fn as_f64(&self) -> Option<f64> {
        match self.0 {
            N::PosInt(n) => NumCast::from(n),
            N::NegInt(n) => NumCast::from(n),
            N::Float(n) => Some(n),
        }
    }

    /// Converts a finite f64 to a Number. Infinite or NaN values are not JSON
    /// numbers.
    #[inline]
    pub fn from_f64(f: f64) -> Option<Number> {
        if f.is_finite() {
            Some(Number(N::Float(f)))
        } else {
            None
        }
    }
}

impl fmt::Display for Number {
    fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
        match self.0 {
            N::PosInt(i) => i.fmt(formatter),
            N::NegInt(i) => i.fmt(formatter),
            N::Float(f) => f.fmt(formatter),
        }
    }
}

impl Serialize for Number {
    #[inline]
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
        where S: Serializer
    {
        match self.0 {
            N::PosInt(i) => serializer.serialize_u64(i),
            N::NegInt(i) => serializer.serialize_i64(i),
            N::Float(f) => serializer.serialize_f64(f),
        }
    }
}

impl Deserialize for Number {
    #[inline]
    fn deserialize<D>(deserializer: D) -> Result<Number, D::Error>
        where D: Deserializer
    {
        struct NumberVisitor;

        impl Visitor for NumberVisitor {
            type Value = Number;

            #[inline]
            fn visit_i64<E>(self, value: i64) -> Result<Number, E> {
                Ok(value.into())
            }

            #[inline]
            fn visit_u64<E>(self, value: u64) -> Result<Number, E> {
                Ok(value.into())
            }

            #[inline]
            fn visit_f64<E>(self, value: f64) -> Result<Number, E>
                where E: de::Error
            {
                Number::from_f64(value).ok_or_else(|| de::Error::custom("not a JSON number"))
            }
        }

        deserializer.deserialize(NumberVisitor)
    }
}

impl Deserializer for Number {
    type Error = Error;

    #[inline]
    fn deserialize<V>(self, visitor: V) -> Result<V::Value, Error>
        where V: Visitor
    {
        match self.0 {
            N::PosInt(i) => visitor.visit_u64(i),
            N::NegInt(i) => visitor.visit_i64(i),
            N::Float(f) => visitor.visit_f64(f),
        }
    }

    forward_to_deserialize! {
        bool usize u8 u16 u32 u64 isize i8 i16 i32 i64 f32 f64 char str string
        unit option seq seq_fixed_size bytes map unit_struct newtype_struct
        tuple_struct struct struct_field tuple enum ignored_any
    }
}

macro_rules! from_signed {
    ($($signed_ty:ident)*) => {
        $(
            impl From<$signed_ty> for Number {
                #[inline]
                fn from(i: $signed_ty) -> Self {
                    if i < 0 {
                        Number(N::NegInt(i as i64))
                    } else {
                        Number(N::PosInt(i as u64))
                    }
                }
            }
        )*
    };
}

macro_rules! from_unsigned {
    ($($unsigned_ty:ident)*) => {
        $(
            impl From<$unsigned_ty> for Number {
                #[inline]
                fn from(u: $unsigned_ty) -> Self {
                    Number(N::PosInt(u as u64))
                }
            }
        )*
    };
}

from_signed!(i8 i16 i32 i64 isize);
from_unsigned!(u8 u16 u32 u64 usize);
<commit_msg>Update lint name to reflect private N<commit_after>use error::Error;
use num_traits::NumCast;
use serde::de::{self, Visitor};
use serde::{Serialize, Serializer, Deserialize, Deserializer};
use std::{fmt, i64};

/// Represents a JSON number, whether integer or floating point.
#[derive(Clone, PartialEq)]
pub struct Number(N);

// "N" is a prefix of "NegInt"... this is a false positive.
// https://github.com/Manishearth/rust-clippy/issues/1241
#[cfg_attr(feature = "clippy", allow(enum_variant_names))]
#[derive(Copy, Clone, Debug, PartialEq)]
enum N {
    PosInt(u64),
    /// Always less than zero.
    NegInt(i64),
    /// Always finite.
    Float(f64),
}

impl Number {
    /// Returns true if the number can be represented by i64.
    #[inline]
    pub fn is_i64(&self) -> bool {
        match self.0 {
            N::PosInt(v) => v <= i64::MAX as u64,
            N::NegInt(_) => true,
            N::Float(_) => false,
        }
    }

    /// Returns true if the number can be represented as u64.
    #[inline]
    pub fn is_u64(&self) -> bool {
        match self.0 {
            N::PosInt(_) => true,
            N::NegInt(_) | N::Float(_) => false,
        }
    }

    /// Returns true if the number can be represented as f64.
    #[inline]
    pub fn is_f64(&self) -> bool {
        match self.0 {
            N::Float(_) => true,
            N::PosInt(_) | N::NegInt(_) => false,
        }
    }

    /// Returns the number represented as i64 if possible, or else None.
    #[inline]
    pub fn as_i64(&self) -> Option<i64> {
        match self.0 {
            N::PosInt(n) => NumCast::from(n),
            N::NegInt(n) => Some(n),
            N::Float(_) => None,
        }
    }

    /// Returns the number represented as u64 if possible, or else None.
    #[inline]
    pub fn as_u64(&self) -> Option<u64> {
        match self.0 {
            N::PosInt(n) => Some(n),
            N::NegInt(n) => NumCast::from(n),
            N::Float(_) => None,
        }
    }

    /// Returns the number represented as f64 if possible, or else None.
    #[inline]
    pub fn as_f64(&self) -> Option<f64> {
        match self.0 {
            N::PosInt(n) => NumCast::from(n),
            N::NegInt(n) => NumCast::from(n),
            N::Float(n) => Some(n),
        }
    }

    /// Converts a finite f64 to a Number. Infinite or NaN values are not JSON
    /// numbers.
    #[inline]
    pub fn from_f64(f: f64) -> Option<Number> {
        if f.is_finite() {
            Some(Number(N::Float(f)))
        } else {
            None
        }
    }
}

impl fmt::Display for Number {
    fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
        match self.0 {
            N::PosInt(i) => i.fmt(formatter),
            N::NegInt(i) => i.fmt(formatter),
            N::Float(f) => f.fmt(formatter),
        }
    }
}

impl Serialize for Number {
    #[inline]
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
        where S: Serializer
    {
        match self.0 {
            N::PosInt(i) => serializer.serialize_u64(i),
            N::NegInt(i) => serializer.serialize_i64(i),
            N::Float(f) => serializer.serialize_f64(f),
        }
    }
}

impl Deserialize for Number {
    #[inline]
    fn deserialize<D>(deserializer: D) -> Result<Number, D::Error>
        where D: Deserializer
    {
        struct NumberVisitor;

        impl Visitor for NumberVisitor {
            type Value = Number;

            #[inline]
            fn visit_i64<E>(self, value: i64) -> Result<Number, E> {
                Ok(value.into())
            }

            #[inline]
            fn visit_u64<E>(self, value: u64) -> Result<Number, E> {
                Ok(value.into())
            }

            #[inline]
            fn visit_f64<E>(self, value: f64) -> Result<Number, E>
                where E: de::Error
            {
                Number::from_f64(value).ok_or_else(|| de::Error::custom("not a JSON number"))
            }
        }

        deserializer.deserialize(NumberVisitor)
    }
}

impl Deserializer for Number {
    type Error = Error;

    #[inline]
    fn deserialize<V>(self, visitor: V) -> Result<V::Value, Error>
        where V: Visitor
    {
        match self.0 {
            N::PosInt(i) => visitor.visit_u64(i),
            N::NegInt(i) => visitor.visit_i64(i),
            N::Float(f) => visitor.visit_f64(f),
        }
    }

    forward_to_deserialize! {
        bool usize u8 u16 u32 u64 isize i8 i16 i32 i64 f32 f64 char str string
        unit option seq seq_fixed_size bytes map unit_struct newtype_struct
        tuple_struct struct struct_field tuple enum ignored_any
    }
}

macro_rules! from_signed {
    ($($signed_ty:ident)*) => {
        $(
            impl From<$signed_ty> for Number {
                #[inline]
                fn from(i: $signed_ty) -> Self {
                    if i < 0 {
                        Number(N::NegInt(i as i64))
                    } else {
                        Number(N::PosInt(i as u64))
                    }
                }
            }
        )*
    };
}

macro_rules! from_unsigned {
    ($($unsigned_ty:ident)*) => {
        $(
            impl From<$unsigned_ty> for Number {
                #[inline]
                fn from(u: $unsigned_ty) -> Self {
                    Number(N::PosInt(u as u64))
                }
            }
        )*
    };
}

from_signed!(i8 i16 i32 i64 isize);
from_unsigned!(u8 u16 u32 u64 usize);
<|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.

use std::env::*;

fn main() {
    for (k, v) in vars_os() {
        let v2 = var_os(&k);
        assert!(v2.as_ref().map(|s| &**s) == Some(&*v),
                "bad vars->var transition: {:?} {:?} {:?}", k, v, v2);
    }
}
<commit_msg>Auto merge of #29910 - tbu-:pr_env_revert_mingw_weirdness, r=alexcrichton<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.

use std::env::*;

fn main() {
    for (k, v) in vars_os() {
        let v2 = var_os(&k);
        // MingW seems to set some funky environment variables like
        // "=C:=C:\MinGW\msys\1.0\bin" and "!::=::\" that are returned
        // from vars() but not visible from var().
        assert!(v2.is_none() || v2.as_ref().map(|s| &**s) == Some(&*v),
                "bad vars->var transition: {:?} {:?} {:?}", k, v, v2);
    }
}
<|endoftext|>


<commit_before>use derivative::Derivative;
use ref_cast::RefCast;
use serde::{Serialize, Serializer};

use std::borrow::{Borrow, Cow};
use std::ffi::{OsStr, OsString};
use std::ops::Deref;
use std::path::{Component, Path, PathBuf};
use std::{env, io};

#[derive(PartialEq, Derivative, RefCast)]
#[derivative(Debug = "transparent")]
#[repr(transparent)]
pub struct AbsPath {
    inner: Path,
}

impl AbsPath {
    fn unchecked(path: &Path) -> &Self {
        Self::ref_cast(path)
    }

    pub(crate) fn parent(&self) -> Option<&Self> {
        self.inner.parent().map(Self::unchecked)
    }

    pub(crate) fn join(&self, path: impl AsRef<Path>) -> AbsPathBuf {
        AbsPathBuf {
            inner: self.inner.join(path),
        }
    }

    pub(crate) fn with_extension(&self, extension: impl AsRef<OsStr>) -> AbsPathBuf {
        AbsPathBuf {
            inner: self.inner.with_extension(extension),
        }
    }

    pub(crate) fn join_canonicalizing_lossy(&self, path: impl AsRef<Path>) -> AbsPathBuf {
        let r = AbsPathBuf {
            inner: self.inner.join(path),
        };
        match r.canonicalize_lossy() {
            Cow::Borrowed(_) => r,
            Cow::Owned(r) => r,
        }
    }

    pub(crate) fn join_expanding_user(&self, path: impl AsRef<OsStr>) -> io::Result<AbsPathBuf> {
        let path = Path::new(path.as_ref());
        let inner = if path.is_absolute() {
            path.to_owned()
        } else if let Some(Component::Normal(first)) = path.components().next() {
            if first == "~" {
                let home = dirs::home_dir().ok_or_else(|| {
                    io::Error::new(io::ErrorKind::NotFound, "Home directory not found")
                })?;
                path.components().skip(1).fold(home, |mut r, c| {
                    r.push(c);
                    r
                })
            } else if first.to_string_lossy().starts_with('~') {
                return Err(io::Error::new(
                    io::ErrorKind::InvalidData,
                    format!("Unsupported use of '~': {}", path.display()),
                ));
            } else {
                self.inner.join(path)
            }
        } else {
            self.inner.join(path)
        };
        Ok(AbsPathBuf { inner }.canonicalize_lossy().into_owned())
    }

    #[cfg(not(windows))]
    fn canonicalize_lossy(&self) -> Cow<Self> {
        match self.inner.canonicalize() {
            Ok(inner) => AbsPathBuf { inner }.into(),
            Err(_) => self.remove_single_dots(),
        }
    }

    #[cfg(windows)]
    fn canonicalize_lossy(&self) -> Cow<Self> {
        use if_chain::if_chain;

        use std::path::Prefix;

        // `dunce` does not strip a UNC prefix when:
        // - the prefix is not `VerbatimDisk`
        // - the whole path is not a valid Unicode
        let inner = if_chain! {
            if let Ok(inner) = dunce::canonicalize(&self.inner);
            if let Some(Component::Prefix(prefix)) = inner.components().next();
            if let Prefix::Disk(_) = prefix.kind();
            then {
                inner
            } else {
                let mut inner = PathBuf::new();
                for component in self.inner.components() {
                    if component == Component::ParentDir {
                        inner.pop();
                    } else if component != Component::CurDir {
                        inner.push(component);
                    }
                    if let Ok(link) = inner.read_link() {
                        inner = link;
                    }
                    if inner.metadata().is_err() {
                        return self.remove_single_dots();
                    }
                }
                inner
            }
        };
        AbsPathBuf { inner }.into()
    }

    fn remove_single_dots(&self) -> Cow<Self> {
        if self.inner.components().any(|c| c == Component::CurDir) {
            let inner = self
                .inner
                .components()
                .filter(|&c| c != Component::CurDir)
                .fold(PathBuf::new(), |mut r, c| {
                    r.push(c);
                    r
                });
            AbsPathBuf { inner }.into()
        } else {
            self.into()
        }
    }
}

impl ToOwned for AbsPath {
    type Owned = AbsPathBuf;

    fn to_owned(&self) -> AbsPathBuf {
        AbsPathBuf {
            inner: self.inner.to_owned(),
        }
    }
}

impl Deref for AbsPath {
    type Target = Path;

    fn deref(&self) -> &Path {
        &self.inner
    }
}

impl AsRef<Path> for AbsPath {
    fn as_ref(&self) -> &Path {
        &self.inner
    }
}

impl AsRef<OsStr> for AbsPath {
    fn as_ref(&self) -> &OsStr {
        self.inner.as_ref()
    }
}

impl<'a> Into<Cow<'a, AbsPath>> for &'a AbsPath {
    fn into(self) -> Cow<'a, AbsPath> {
        Cow::Borrowed(self)
    }
}

impl Serialize for AbsPath {
    fn serialize<S: Serializer>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error> {
        self.deref().serialize(serializer)
    }
}

#[derive(Clone, PartialEq, Eq, Hash, Derivative)]
#[derivative(Debug = "transparent")]
pub struct AbsPathBuf {
    inner: PathBuf,
}

impl AbsPathBuf {
    pub fn cwd() -> io::Result<Self> {
        #[derive(derive_more::Display, Debug)]
        #[display(fmt = "Failed to get the current directory")]
        struct GetcwdError(io::Error);

        impl std::error::Error for GetcwdError {
            fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
                Some(&self.0)
            }
        }

        env::current_dir()
            .and_then(|inner| {
                if inner.is_absolute() {
                    Ok(Self { inner })
                } else {
                    Err(io::ErrorKind::Other.into())
                }
            })
            .map_err(|e| io::Error::new(e.kind(), GetcwdError(e)))
    }

    pub fn try_new(path: impl Into<PathBuf>) -> Option<Self> {
        let inner = path.into();
        guard!(inner.is_absolute());
        Some(Self { inner })
    }

    pub(crate) fn pop(&mut self) -> bool {
        self.inner.pop()
    }
}

impl Borrow<AbsPath> for AbsPathBuf {
    fn borrow(&self) -> &AbsPath {
        AbsPath::unchecked(&self.inner)
    }
}

impl Deref for AbsPathBuf {
    type Target = AbsPath;

    fn deref(&self) -> &AbsPath {
        AbsPath::unchecked(&self.inner)
    }
}

impl AsRef<OsStr> for AbsPathBuf {
    fn as_ref(&self) -> &OsStr {
        self.inner.as_ref()
    }
}

impl AsRef<Path> for AbsPathBuf {
    fn as_ref(&self) -> &Path {
        &self.inner
    }
}

impl<'a> Into<Cow<'a, AbsPath>> for AbsPathBuf {
    fn into(self) -> Cow<'a, AbsPath> {
        Cow::Owned(self)
    }
}

impl Into<OsString> for AbsPathBuf {
    fn into(self) -> OsString {
        self.inner.into()
    }
}

impl Into<PathBuf> for AbsPathBuf {
    fn into(self) -> PathBuf {
        self.inner
    }
}

#[cfg(test)]
impl PartialEq<PathBuf> for AbsPathBuf {
    fn eq(&self, other: &PathBuf) -> bool {
        self.inner == *other
    }
}

impl Serialize for AbsPathBuf {
    fn serialize<S: Serializer>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error> {
        AsRef::<Path>::as_ref(self).serialize(serializer)
    }
}

#[cfg(test)]
mod tests {
    use super::{AbsPath, AbsPathBuf};

    use dirs;
    use pretty_assertions::assert_eq;

    use std::io;
    use std::path::Path;

    #[cfg(not(windows))]
    #[test]
    fn it_removes_dots() {
        let base = AbsPath::unchecked(Path::new("/foo"));
        assert_eq!(Path::new("/foo"), base.join("").inner);
        assert_eq!(Path::new("/foo"), base.join(".").inner);
        assert_eq!(Path::new("/foo/bar"), base.join("bar").inner);
        assert_eq!(Path::new("/foo/bar"), base.join("./bar").inner);
        assert_eq!(Path::new("/foo/../bar"), base.join("../bar").inner);
    }

    #[cfg(windows)]
    #[test]
    fn it_removes_dots() {
        let base = AbsPath::unchecked(Path::new(r"C:\foo"));
        assert_eq!(Path::new(r"C:\foo"), base.join("").inner);
        assert_eq!(Path::new(r"C:\foo"), base.join(".").inner);
        assert_eq!(Path::new(r"C:\foo\bar"), base.join("bar").inner);
        assert_eq!(Path::new(r"C:\foo\bar"), base.join(r".\bar").inner);
        assert_eq!(Path::new(r"C:\foo\..\bar"), base.join(r"..\bar").inner);
    }

    #[test]
    fn it_expands_user() -> io::Result<()> {
        let home = dirs::home_dir().unwrap();
        assert_eq!(
            if cfg!(windows) {
                AbsPathBuf::try_new("C:\\")
            } else {
                AbsPathBuf::try_new("/")
            }
            .unwrap()
            .join_expanding_user("~/foo")?
            .inner,
            home.join("foo"),
        );
        Ok(())
    }
}
<commit_msg>Fix Clippy lints<commit_after>use derivative::Derivative;
use ref_cast::RefCast;
use serde::{Serialize, Serializer};

use std::borrow::{Borrow, Cow};
use std::ffi::{OsStr, OsString};
use std::ops::Deref;
use std::path::{Component, Path, PathBuf};
use std::{env, io};

#[derive(PartialEq, Derivative, RefCast)]
#[derivative(Debug = "transparent")]
#[repr(transparent)]
pub struct AbsPath {
    inner: Path,
}

impl AbsPath {
    fn unchecked(path: &Path) -> &Self {
        Self::ref_cast(path)
    }

    pub(crate) fn parent(&self) -> Option<&Self> {
        self.inner.parent().map(Self::unchecked)
    }

    pub(crate) fn join(&self, path: impl AsRef<Path>) -> AbsPathBuf {
        AbsPathBuf {
            inner: self.inner.join(path),
        }
    }

    pub(crate) fn with_extension(&self, extension: impl AsRef<OsStr>) -> AbsPathBuf {
        AbsPathBuf {
            inner: self.inner.with_extension(extension),
        }
    }

    pub(crate) fn join_canonicalizing_lossy(&self, path: impl AsRef<Path>) -> AbsPathBuf {
        let r = AbsPathBuf {
            inner: self.inner.join(path),
        };
        match r.canonicalize_lossy() {
            Cow::Borrowed(_) => r,
            Cow::Owned(r) => r,
        }
    }

    pub(crate) fn join_expanding_user(&self, path: impl AsRef<OsStr>) -> io::Result<AbsPathBuf> {
        let path = Path::new(path.as_ref());
        let inner = if path.is_absolute() {
            path.to_owned()
        } else if let Some(Component::Normal(first)) = path.components().next() {
            if first == "~" {
                let home = dirs::home_dir().ok_or_else(|| {
                    io::Error::new(io::ErrorKind::NotFound, "Home directory not found")
                })?;
                path.components().skip(1).fold(home, |mut r, c| {
                    r.push(c);
                    r
                })
            } else if first.to_string_lossy().starts_with('~') {
                return Err(io::Error::new(
                    io::ErrorKind::InvalidData,
                    format!("Unsupported use of '~': {}", path.display()),
                ));
            } else {
                self.inner.join(path)
            }
        } else {
            self.inner.join(path)
        };
        Ok(AbsPathBuf { inner }.canonicalize_lossy().into_owned())
    }

    #[cfg(not(windows))]
    fn canonicalize_lossy(&self) -> Cow<Self> {
        match self.inner.canonicalize() {
            Ok(inner) => AbsPathBuf { inner }.into(),
            Err(_) => self.remove_single_dots(),
        }
    }

    #[cfg(windows)]
    fn canonicalize_lossy(&self) -> Cow<Self> {
        use if_chain::if_chain;

        use std::path::Prefix;

        // `dunce` does not strip a UNC prefix when:
        // - the prefix is not `VerbatimDisk`
        // - the whole path is not a valid Unicode
        let inner = if_chain! {
            if let Ok(inner) = dunce::canonicalize(&self.inner);
            if let Some(Component::Prefix(prefix)) = inner.components().next();
            if let Prefix::Disk(_) = prefix.kind();
            then {
                inner
            } else {
                let mut inner = PathBuf::new();
                for component in self.inner.components() {
                    if component == Component::ParentDir {
                        inner.pop();
                    } else if component != Component::CurDir {
                        inner.push(component);
                    }
                    if let Ok(link) = inner.read_link() {
                        inner = link;
                    }
                    if inner.metadata().is_err() {
                        return self.remove_single_dots();
                    }
                }
                inner
            }
        };
        AbsPathBuf { inner }.into()
    }

    fn remove_single_dots(&self) -> Cow<Self> {
        if self.inner.components().any(|c| c == Component::CurDir) {
            let inner = self
                .inner
                .components()
                .filter(|&c| c != Component::CurDir)
                .fold(PathBuf::new(), |mut r, c| {
                    r.push(c);
                    r
                });
            AbsPathBuf { inner }.into()
        } else {
            self.into()
        }
    }
}

impl ToOwned for AbsPath {
    type Owned = AbsPathBuf;

    fn to_owned(&self) -> AbsPathBuf {
        AbsPathBuf {
            inner: self.inner.to_owned(),
        }
    }
}

impl Deref for AbsPath {
    type Target = Path;

    fn deref(&self) -> &Path {
        &self.inner
    }
}

impl AsRef<Path> for AbsPath {
    fn as_ref(&self) -> &Path {
        &self.inner
    }
}

impl AsRef<OsStr> for AbsPath {
    fn as_ref(&self) -> &OsStr {
        self.inner.as_ref()
    }
}

impl<'a> Into<Cow<'a, AbsPath>> for &'a AbsPath {
    fn into(self) -> Cow<'a, AbsPath> {
        Cow::Borrowed(self)
    }
}

impl Serialize for AbsPath {
    fn serialize<S: Serializer>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error> {
        self.deref().serialize(serializer)
    }
}

#[derive(Clone, PartialEq, Eq, Hash, Derivative)]
#[derivative(Debug = "transparent")]
pub struct AbsPathBuf {
    inner: PathBuf,
}

impl AbsPathBuf {
    pub fn cwd() -> io::Result<Self> {
        #[derive(derive_more::Display, Debug)]
        #[display(fmt = "Failed to get the current directory")]
        struct GetcwdError(io::Error);

        impl std::error::Error for GetcwdError {
            fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
                Some(&self.0)
            }
        }

        env::current_dir()
            .and_then(|inner| {
                if inner.is_absolute() {
                    Ok(Self { inner })
                } else {
                    Err(io::ErrorKind::Other.into())
                }
            })
            .map_err(|e| io::Error::new(e.kind(), GetcwdError(e)))
    }

    pub fn try_new(path: impl Into<PathBuf>) -> Option<Self> {
        let inner = path.into();
        guard!(inner.is_absolute());
        Some(Self { inner })
    }

    pub(crate) fn pop(&mut self) -> bool {
        self.inner.pop()
    }
}

impl Borrow<AbsPath> for AbsPathBuf {
    fn borrow(&self) -> &AbsPath {
        AbsPath::unchecked(&self.inner)
    }
}

impl Deref for AbsPathBuf {
    type Target = AbsPath;

    fn deref(&self) -> &AbsPath {
        AbsPath::unchecked(&self.inner)
    }
}

impl AsRef<OsStr> for AbsPathBuf {
    fn as_ref(&self) -> &OsStr {
        self.inner.as_ref()
    }
}

impl AsRef<Path> for AbsPathBuf {
    fn as_ref(&self) -> &Path {
        &self.inner
    }
}

impl<'a> Into<Cow<'a, AbsPath>> for AbsPathBuf {
    fn into(self) -> Cow<'a, AbsPath> {
        Cow::Owned(self)
    }
}

impl Into<OsString> for AbsPathBuf {
    fn into(self) -> OsString {
        self.inner.into()
    }
}

impl Into<PathBuf> for AbsPathBuf {
    fn into(self) -> PathBuf {
        self.inner
    }
}

#[cfg(test)]
impl PartialEq<PathBuf> for AbsPathBuf {
    fn eq(&self, other: &PathBuf) -> bool {
        self.inner == *other
    }
}

impl Serialize for AbsPathBuf {
    fn serialize<S: Serializer>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error> {
        AsRef::<Path>::as_ref(self).serialize(serializer)
    }
}

#[cfg(test)]
mod tests {
    use super::{AbsPath, AbsPathBuf};

    use pretty_assertions::assert_eq;

    use std::io;
    use std::path::Path;

    #[cfg(not(windows))]
    #[test]
    fn it_removes_dots() {
        let base = AbsPath::unchecked(Path::new("/foo"));
        assert_eq!(Path::new("/foo"), base.join("").inner);
        assert_eq!(Path::new("/foo"), base.join(".").inner);
        assert_eq!(Path::new("/foo/bar"), base.join("bar").inner);
        assert_eq!(Path::new("/foo/bar"), base.join("./bar").inner);
        assert_eq!(Path::new("/foo/../bar"), base.join("../bar").inner);
    }

    #[cfg(windows)]
    #[test]
    fn it_removes_dots() {
        let base = AbsPath::unchecked(Path::new(r"C:\foo"));
        assert_eq!(Path::new(r"C:\foo"), base.join("").inner);
        assert_eq!(Path::new(r"C:\foo"), base.join(".").inner);
        assert_eq!(Path::new(r"C:\foo\bar"), base.join("bar").inner);
        assert_eq!(Path::new(r"C:\foo\bar"), base.join(r".\bar").inner);
        assert_eq!(Path::new(r"C:\foo\..\bar"), base.join(r"..\bar").inner);
    }

    #[test]
    fn it_expands_user() -> io::Result<()> {
        let home = dirs::home_dir().unwrap();
        assert_eq!(
            if cfg!(windows) {
                AbsPathBuf::try_new("C:\\")
            } else {
                AbsPathBuf::try_new("/")
            }
            .unwrap()
            .join_expanding_user("~/foo")?
            .inner,
            home.join("foo"),
        );
        Ok(())
    }
}
<|endoftext|>