file_name
large_stringlengths 4
69
| prefix
large_stringlengths 0
26.7k
| suffix
large_stringlengths 0
24.8k
| middle
large_stringlengths 0
2.12k
| fim_type
large_stringclasses 4
values |
---|---|---|---|---|
main.rs
|
extern crate clap;
extern crate rusty_post_lib;
use clap::App;
use clap::Arg;
use rusty_post_lib::request::request::{Request, RequestConfig, HttpMethod};
fn main() {
let matches = App::new("rusty-post")
.version("0.1.0")
.about("Make HTTP requests")
.author("Jonathan Rothberg")
.arg(Arg::with_name("request")
.short("X")
.long("request")
.default_value("GET")
.takes_value(true))
.arg(Arg::with_name("url")
.long("url")
.required(true)
.takes_value(true))
.arg(Arg::with_name("H")
.short("H")
.long("header")
.multiple(true)
.takes_value(true)
.default_value(""))
.arg(Arg::with_name("data")
.short("d")
.long("data")
.takes_value(true)
.default_value("")
).get_matches();
match matches.value_of("url") {
Some(u) =>
|
println!("Headers: {:?}", headers);
let config = RequestConfig::new(method, &headers, data);
let request = Request::new_with_config(u.into(), &config);
let resp = request.request();
println!("{}", resp);
}
,
None => {}
}
println!("Hello, world!");
}
|
{
let headers = match matches.values_of("H") {
Some(h) => {
h.collect()
},
None => Vec::new()
};
let data = match matches.value_of("data") {
Some(d) => {
d
},
None => ""
};
let method = match matches.value_of("request") {
Some(m) if m == "" || m == "GET" || m == "get" || m == "Get" => HttpMethod::Get,
Some(m) if m == "POST" || m == "post" || m == "Post" => HttpMethod::Post,
_ => HttpMethod::Get
};
|
conditional_block
|
main.rs
|
extern crate clap;
extern crate rusty_post_lib;
use clap::App;
use clap::Arg;
use rusty_post_lib::request::request::{Request, RequestConfig, HttpMethod};
fn main()
|
.arg(Arg::with_name("data")
.short("d")
.long("data")
.takes_value(true)
.default_value("")
).get_matches();
match matches.value_of("url") {
Some(u) => {
let headers = match matches.values_of("H") {
Some(h) => {
h.collect()
},
None => Vec::new()
};
let data = match matches.value_of("data") {
Some(d) => {
d
},
None => ""
};
let method = match matches.value_of("request") {
Some(m) if m == "" || m == "GET" || m == "get" || m == "Get" => HttpMethod::Get,
Some(m) if m == "POST" || m == "post" || m == "Post" => HttpMethod::Post,
_ => HttpMethod::Get
};
println!("Headers: {:?}", headers);
let config = RequestConfig::new(method, &headers, data);
let request = Request::new_with_config(u.into(), &config);
let resp = request.request();
println!("{}", resp);
},
None => {}
}
println!("Hello, world!");
}
|
{
let matches = App::new("rusty-post")
.version("0.1.0")
.about("Make HTTP requests")
.author("Jonathan Rothberg")
.arg(Arg::with_name("request")
.short("X")
.long("request")
.default_value("GET")
.takes_value(true))
.arg(Arg::with_name("url")
.long("url")
.required(true)
.takes_value(true))
.arg(Arg::with_name("H")
.short("H")
.long("header")
.multiple(true)
.takes_value(true)
.default_value(""))
|
identifier_body
|
ai.rs
|
use ball::Ball;
use player::Player;
use settings;
pub struct AI {
sleep_time: f64,
awake_time: f64,
}
impl AI {
pub fn new() -> AI {
AI {
sleep_time: 0.0,
awake_time: settings::AI_AWAKE_TIME,
}
}
pub fn update(&mut self, dt: f64, player: &mut Player, ball: &mut Ball) {
let d = ball.position()[1] - player.position()[1];
let size = ball.aabb().size;
if self.awake_time > 0.0 {
self.awake_time -= dt;
if d < -size[1] / 4.0 {
player.start_moving_up();
} else if d > size[1] / 4.0 {
player.start_moving_down();
} else {
player.stop_move();
}
} else {
self.sleep_time -= dt;
if d.abs() < size[1] / 2.0 {
player.stop_move();
}
if self.sleep_time < 0.0
|
}
}
}
|
{
self.awake_time = settings::AI_AWAKE_TIME;
self.sleep_time = settings::AI_SLEEP_TIME;
}
|
conditional_block
|
ai.rs
|
use ball::Ball;
use player::Player;
use settings;
pub struct AI {
sleep_time: f64,
awake_time: f64,
}
impl AI {
pub fn new() -> AI {
AI {
sleep_time: 0.0,
|
}
pub fn update(&mut self, dt: f64, player: &mut Player, ball: &mut Ball) {
let d = ball.position()[1] - player.position()[1];
let size = ball.aabb().size;
if self.awake_time > 0.0 {
self.awake_time -= dt;
if d < -size[1] / 4.0 {
player.start_moving_up();
} else if d > size[1] / 4.0 {
player.start_moving_down();
} else {
player.stop_move();
}
} else {
self.sleep_time -= dt;
if d.abs() < size[1] / 2.0 {
player.stop_move();
}
if self.sleep_time < 0.0 {
self.awake_time = settings::AI_AWAKE_TIME;
self.sleep_time = settings::AI_SLEEP_TIME;
}
}
}
}
|
awake_time: settings::AI_AWAKE_TIME,
}
|
random_line_split
|
ai.rs
|
use ball::Ball;
use player::Player;
use settings;
pub struct AI {
sleep_time: f64,
awake_time: f64,
}
impl AI {
pub fn
|
() -> AI {
AI {
sleep_time: 0.0,
awake_time: settings::AI_AWAKE_TIME,
}
}
pub fn update(&mut self, dt: f64, player: &mut Player, ball: &mut Ball) {
let d = ball.position()[1] - player.position()[1];
let size = ball.aabb().size;
if self.awake_time > 0.0 {
self.awake_time -= dt;
if d < -size[1] / 4.0 {
player.start_moving_up();
} else if d > size[1] / 4.0 {
player.start_moving_down();
} else {
player.stop_move();
}
} else {
self.sleep_time -= dt;
if d.abs() < size[1] / 2.0 {
player.stop_move();
}
if self.sleep_time < 0.0 {
self.awake_time = settings::AI_AWAKE_TIME;
self.sleep_time = settings::AI_SLEEP_TIME;
}
}
}
}
|
new
|
identifier_name
|
complex_inner_join.rs
|
extern crate rustorm;
extern crate uuid;
extern crate chrono;
extern crate rustc_serialize;
use uuid::Uuid;
use rustorm::query::Query;
use rustorm::query::Equality;
use rustorm::dao::{Dao, IsDao};
use rustorm::pool::ManagedPool;
#[derive(Debug, Clone)]
pub struct Photo {
pub photo_id: Uuid,
pub url: Option<String>,
}
impl IsDao for Photo{
fn
|
(dao: &Dao) -> Self {
Photo {
photo_id: dao.get("photo_id"),
url: dao.get_opt("url"),
}
}
fn to_dao(&self) -> Dao {
let mut dao = Dao::new();
dao.set("photo_id", &self.photo_id);
match self.url {
Some(ref _value) => dao.set("url", _value),
None => dao.set_null("url"),
}
dao
}
}
fn main() {
let url = "postgres://postgres:p0stgr3s@localhost/bazaar_v6";
let pool = ManagedPool::init(&url, 1).unwrap();
let db = pool.connect().unwrap();
let mut query = Query::select_all();
query.from_table("bazaar.product")
.inner_join_table("bazaar.product_category",
"product_category.product_id",
"product.product_id")
.inner_join_table("bazaar.category",
"category.category_id",
"product_category.category_id")
.inner_join_table("product_photo",
"product.product_id",
"product_photo.product_id")
.inner_join_table("bazaar.photo", "product_photo.photo_id", "photo.photo_id")
.filter("product.name", Equality::EQ, &"GTX660 Ti videocard")
.filter("category.name", Equality::EQ, &"Electronic")
.group_by(vec!["category.name"])
.having("count(*)", Equality::GT, &1)
.asc("product.name")
.desc("product.created");
let frag = query.build(db.as_ref());
let expected = "
SELECT *
FROM bazaar.product
INNER JOIN bazaar.product_category\x20
ON product_category.product_id = product.product_id\x20
INNER JOIN bazaar.category\x20
ON category.category_id = product_category.category_id\x20
INNER JOIN product_photo\x20
ON product.product_id = product_photo.product_id\x20
INNER JOIN bazaar.photo\x20
ON product_photo.photo_id = photo.photo_id\x20
WHERE product.name = $1\x20
AND category.name = $2\x20
GROUP BY category.name\x20
HAVING count(*) > $3\x20
ORDER BY product.name ASC, product.created DESC".to_string();
println!("actual: {{\n{}}} [{}]", frag.sql, frag.sql.len());
println!("expected: {{{}}} [{}]", expected, expected.len());
assert!(frag.sql.trim() == expected.trim());
}
|
from_dao
|
identifier_name
|
complex_inner_join.rs
|
extern crate rustorm;
extern crate uuid;
extern crate chrono;
extern crate rustc_serialize;
use uuid::Uuid;
use rustorm::query::Query;
use rustorm::query::Equality;
use rustorm::dao::{Dao, IsDao};
use rustorm::pool::ManagedPool;
#[derive(Debug, Clone)]
pub struct Photo {
pub photo_id: Uuid,
pub url: Option<String>,
}
impl IsDao for Photo{
fn from_dao(dao: &Dao) -> Self {
Photo {
photo_id: dao.get("photo_id"),
url: dao.get_opt("url"),
}
}
fn to_dao(&self) -> Dao {
let mut dao = Dao::new();
dao.set("photo_id", &self.photo_id);
match self.url {
Some(ref _value) => dao.set("url", _value),
None => dao.set_null("url"),
}
dao
}
}
fn main() {
let url = "postgres://postgres:p0stgr3s@localhost/bazaar_v6";
let pool = ManagedPool::init(&url, 1).unwrap();
let db = pool.connect().unwrap();
let mut query = Query::select_all();
query.from_table("bazaar.product")
.inner_join_table("bazaar.product_category",
"product_category.product_id",
"product.product_id")
.inner_join_table("bazaar.category",
"category.category_id",
"product_category.category_id")
.inner_join_table("product_photo",
"product.product_id",
"product_photo.product_id")
.inner_join_table("bazaar.photo", "product_photo.photo_id", "photo.photo_id")
.filter("product.name", Equality::EQ, &"GTX660 Ti videocard")
.filter("category.name", Equality::EQ, &"Electronic")
|
let frag = query.build(db.as_ref());
let expected = "
SELECT *
FROM bazaar.product
INNER JOIN bazaar.product_category\x20
ON product_category.product_id = product.product_id\x20
INNER JOIN bazaar.category\x20
ON category.category_id = product_category.category_id\x20
INNER JOIN product_photo\x20
ON product.product_id = product_photo.product_id\x20
INNER JOIN bazaar.photo\x20
ON product_photo.photo_id = photo.photo_id\x20
WHERE product.name = $1\x20
AND category.name = $2\x20
GROUP BY category.name\x20
HAVING count(*) > $3\x20
ORDER BY product.name ASC, product.created DESC".to_string();
println!("actual: {{\n{}}} [{}]", frag.sql, frag.sql.len());
println!("expected: {{{}}} [{}]", expected, expected.len());
assert!(frag.sql.trim() == expected.trim());
}
|
.group_by(vec!["category.name"])
.having("count(*)", Equality::GT, &1)
.asc("product.name")
.desc("product.created");
|
random_line_split
|
timer.rs
|
// Zinc, the bare metal stack for rust.
// Copyright 2014 Lionel Flandrin <[email protected]>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#![allow(missing_docs)]
//! Timer configuration
//! This code should support both standand and wide timers
use hal::tiva_c::sysctl;
use hal::timer;
use util::support::get_reg_ref;
/// There are 6 standard 16/32bit timers and 6 "wide" 32/64bit timers
#[allow(missing_docs)]
#[derive(Clone, Copy)]
pub enum TimerId {
Timer0,
Timer1,
Timer2,
Timer3,
Timer4,
Timer5,
TimerW0,
TimerW1,
TimerW2,
TimerW3,
TimerW4,
TimerW5,
}
/// Timer modes
#[derive(Clone, Copy)]
pub enum Mode {
/// Periodic timer loops and restarts once the timeout is reached.
Periodic,
/// One shot timer is disabled once the timeout is reached.
OneShot,
/// RTC timer is based on the 32.768KHz clock and ticks at 1Hz
RTC,
/// EdgeCount timer counts rising/falling/both edge events on an
/// external pin.
EdgeCount,
/// EdgeTime timer measures the time it takes for a rising/falling/both edge
/// event to occur.
EdgeTime,
/// PWM mode can be used to generate a configurable square wave (frequence and
/// duty cycle)
PWM,
}
/// Structure describing a single timer counter (both 16/32bit and 32/64bit)
#[derive(Clone, Copy)]
pub struct Timer {
/// Timer register interface
regs : &'static reg::Timer,
/// True if the counter is wide 32/64bit
wide : bool,
/// Current timer mode
mode : Mode,
}
impl Timer {
/// Create and configure a Timer
pub fn new(id: TimerId,
mode: Mode,
prescale: u32) -> Timer {
let (periph, regs, wide) = match id {
TimerId::Timer0 =>
(sysctl::periph::timer::TIMER_0, reg::TIMER_0, false),
TimerId::Timer1 =>
(sysctl::periph::timer::TIMER_1, reg::TIMER_1, false),
TimerId::Timer2 =>
(sysctl::periph::timer::TIMER_2, reg::TIMER_2, false),
TimerId::Timer3 =>
(sysctl::periph::timer::TIMER_3, reg::TIMER_3, false),
TimerId::Timer4 =>
(sysctl::periph::timer::TIMER_4, reg::TIMER_4, false),
TimerId::Timer5 =>
(sysctl::periph::timer::TIMER_5, reg::TIMER_5, false),
TimerId::TimerW0 =>
(sysctl::periph::timer::TIMER_W_0, reg::TIMER_W_0, true),
TimerId::TimerW1 =>
(sysctl::periph::timer::TIMER_W_1, reg::TIMER_W_1, true),
TimerId::TimerW2 =>
(sysctl::periph::timer::TIMER_W_2, reg::TIMER_W_2, true),
TimerId::TimerW3 =>
(sysctl::periph::timer::TIMER_W_3, reg::TIMER_W_3, true),
TimerId::TimerW4 =>
(sysctl::periph::timer::TIMER_W_4, reg::TIMER_W_4, true),
TimerId::TimerW5 =>
(sysctl::periph::timer::TIMER_W_5, reg::TIMER_W_5, true),
};
periph.ensure_enabled();
|
timer.configure(prescale);
timer
}
/// Configure timer registers
/// TODO(simias): Only Periodic and OneShot modes are implemented so far
pub fn configure(&self, prescale: u32) {
// Make sure the timer is disabled before making changes.
self.regs.ctl.set_taen(false);
// Configure the timer as half-width so that we can use the prescaler
self.regs.cfg.set_cfg(reg::Timer_cfg_cfg::HalfWidth);
self.regs.amr
.set_mr(match self.mode {
Mode::OneShot => reg::Timer_amr_mr::OneShot,
Mode::Periodic => reg::Timer_amr_mr::Periodic,
_ => panic!("Unimplemented timer mode"),
})
// We need to count down in order for the prescaler to work as a
// prescaler. If we count up it becomes a timer extension (i.e. it becomes
// the MSBs of the counter).
.set_cdir(reg::Timer_amr_cdir::Down);
// Set maximum timeout value to overflow as late as possible
self.regs.tailr.set_tailr(0xffffffff);
// Set prescale value
if!self.wide && prescale > 0xffff {
panic!("prescale is too wide for this timer");
}
self.regs.apr.set_psr(prescale as u32);
// Timer is now configured, we can enable it
self.regs.ctl.set_taen(true);
}
}
impl timer::Timer for Timer {
/// Retrieve the current timer value
#[inline(always)]
fn get_counter(&self) -> u32 {
// We count down, however the trait code expects that the counter increases,
// so we just complement the value to get an increasing counter.
!self.regs.tav.v()
}
}
pub mod reg {
//! Timer registers definition
use volatile_cell::VolatileCell;
use core::ops::Drop;
ioregs!(Timer = {
0x00 => reg32 cfg {
//! Timer configuration
0..2 => cfg {
0 => FullWidth,
1 => Rtc,
4 => HalfWidth,
},
}
0x04 => reg32 amr {
//! Timer A mode
0..1 => mr { //! mode
1 => OneShot,
2 => Periodic,
3 => Capture,
},
2 => cmr, //= capture mode
3 => ams, //= alternate mode select
4 => cdir { //! Count direction
0 => Down,
1 => Up,
},
5 => mie, //= match interrupt enable
6 => wot, //= wait on trigger
7 => snaps, //= snap-shot mode
8 => ild, //= interval load write
9 => pwmie, //= PWM interrupt enable
10 => rsu, //= match register update
11 => plo, //= PWM legacy operation
}
0x0C => reg32 ctl {
0 => taen, //= Timer A enable
1 => tastall, //= Timer A stall enable
2..3 => taevent { //! Timer A event mode
0 => PosEdge,
1 => NegEdge,
3 => AnyEdge,
},
4 => rtcen, //= RTC stall enable
5 => taote, //= Timer B output trigger enable
6 => tapwml, //= Timer B PWM output level
8 => tben, //= Timer B enable
9 => tbstall, //= Timer B stall enable
10..11 => tbevent, //= Timer B event mode
13 => tbote, //= Timer B output trigger enable
14 => tbpwml, //= Timer B PWM output level
}
0x28 => reg32 tailr {
0..31 => tailr, //= Timer A interval load
}
0x38 => reg32 apr {
0..15 => psr, //= Timer A prescale value
//= Only 8bit for 16/32bit timers
}
0x50 => reg32 tav {
0..31 => v, // Timer A counter value
}
});
pub const TIMER_0: *const Timer = 0x40030000 as *const Timer;
pub const TIMER_1: *const Timer = 0x40031000 as *const Timer;
pub const TIMER_2: *const Timer = 0x40032000 as *const Timer;
pub const TIMER_3: *const Timer = 0x40033000 as *const Timer;
pub const TIMER_4: *const Timer = 0x40034000 as *const Timer;
pub const TIMER_5: *const Timer = 0x40035000 as *const Timer;
pub const TIMER_W_0: *const Timer = 0x40036000 as *const Timer;
pub const TIMER_W_1: *const Timer = 0x40037000 as *const Timer;
pub const TIMER_W_2: *const Timer = 0x4003C000 as *const Timer;
pub const TIMER_W_3: *const Timer = 0x4003D000 as *const Timer;
pub const TIMER_W_4: *const Timer = 0x4003E000 as *const Timer;
pub const TIMER_W_5: *const Timer = 0x4003F000 as *const Timer;
}
|
let timer = Timer { regs: get_reg_ref(regs), wide: wide, mode: mode};
|
random_line_split
|
timer.rs
|
// Zinc, the bare metal stack for rust.
// Copyright 2014 Lionel Flandrin <[email protected]>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#![allow(missing_docs)]
//! Timer configuration
//! This code should support both standand and wide timers
use hal::tiva_c::sysctl;
use hal::timer;
use util::support::get_reg_ref;
/// There are 6 standard 16/32bit timers and 6 "wide" 32/64bit timers
#[allow(missing_docs)]
#[derive(Clone, Copy)]
pub enum TimerId {
Timer0,
Timer1,
Timer2,
Timer3,
Timer4,
Timer5,
TimerW0,
TimerW1,
TimerW2,
TimerW3,
TimerW4,
TimerW5,
}
/// Timer modes
#[derive(Clone, Copy)]
pub enum Mode {
/// Periodic timer loops and restarts once the timeout is reached.
Periodic,
/// One shot timer is disabled once the timeout is reached.
OneShot,
/// RTC timer is based on the 32.768KHz clock and ticks at 1Hz
RTC,
/// EdgeCount timer counts rising/falling/both edge events on an
/// external pin.
EdgeCount,
/// EdgeTime timer measures the time it takes for a rising/falling/both edge
/// event to occur.
EdgeTime,
/// PWM mode can be used to generate a configurable square wave (frequence and
/// duty cycle)
PWM,
}
/// Structure describing a single timer counter (both 16/32bit and 32/64bit)
#[derive(Clone, Copy)]
pub struct Timer {
/// Timer register interface
regs : &'static reg::Timer,
/// True if the counter is wide 32/64bit
wide : bool,
/// Current timer mode
mode : Mode,
}
impl Timer {
/// Create and configure a Timer
pub fn new(id: TimerId,
mode: Mode,
prescale: u32) -> Timer {
let (periph, regs, wide) = match id {
TimerId::Timer0 =>
(sysctl::periph::timer::TIMER_0, reg::TIMER_0, false),
TimerId::Timer1 =>
(sysctl::periph::timer::TIMER_1, reg::TIMER_1, false),
TimerId::Timer2 =>
(sysctl::periph::timer::TIMER_2, reg::TIMER_2, false),
TimerId::Timer3 =>
(sysctl::periph::timer::TIMER_3, reg::TIMER_3, false),
TimerId::Timer4 =>
(sysctl::periph::timer::TIMER_4, reg::TIMER_4, false),
TimerId::Timer5 =>
(sysctl::periph::timer::TIMER_5, reg::TIMER_5, false),
TimerId::TimerW0 =>
(sysctl::periph::timer::TIMER_W_0, reg::TIMER_W_0, true),
TimerId::TimerW1 =>
(sysctl::periph::timer::TIMER_W_1, reg::TIMER_W_1, true),
TimerId::TimerW2 =>
(sysctl::periph::timer::TIMER_W_2, reg::TIMER_W_2, true),
TimerId::TimerW3 =>
(sysctl::periph::timer::TIMER_W_3, reg::TIMER_W_3, true),
TimerId::TimerW4 =>
(sysctl::periph::timer::TIMER_W_4, reg::TIMER_W_4, true),
TimerId::TimerW5 =>
(sysctl::periph::timer::TIMER_W_5, reg::TIMER_W_5, true),
};
periph.ensure_enabled();
let timer = Timer { regs: get_reg_ref(regs), wide: wide, mode: mode};
timer.configure(prescale);
timer
}
/// Configure timer registers
/// TODO(simias): Only Periodic and OneShot modes are implemented so far
pub fn configure(&self, prescale: u32)
|
self.regs.tailr.set_tailr(0xffffffff);
// Set prescale value
if!self.wide && prescale > 0xffff {
panic!("prescale is too wide for this timer");
}
self.regs.apr.set_psr(prescale as u32);
// Timer is now configured, we can enable it
self.regs.ctl.set_taen(true);
}
}
impl timer::Timer for Timer {
/// Retrieve the current timer value
#[inline(always)]
fn get_counter(&self) -> u32 {
// We count down, however the trait code expects that the counter increases,
// so we just complement the value to get an increasing counter.
!self.regs.tav.v()
}
}
pub mod reg {
//! Timer registers definition
use volatile_cell::VolatileCell;
use core::ops::Drop;
ioregs!(Timer = {
0x00 => reg32 cfg {
//! Timer configuration
0..2 => cfg {
0 => FullWidth,
1 => Rtc,
4 => HalfWidth,
},
}
0x04 => reg32 amr {
//! Timer A mode
0..1 => mr { //! mode
1 => OneShot,
2 => Periodic,
3 => Capture,
},
2 => cmr, //= capture mode
3 => ams, //= alternate mode select
4 => cdir { //! Count direction
0 => Down,
1 => Up,
},
5 => mie, //= match interrupt enable
6 => wot, //= wait on trigger
7 => snaps, //= snap-shot mode
8 => ild, //= interval load write
9 => pwmie, //= PWM interrupt enable
10 => rsu, //= match register update
11 => plo, //= PWM legacy operation
}
0x0C => reg32 ctl {
0 => taen, //= Timer A enable
1 => tastall, //= Timer A stall enable
2..3 => taevent { //! Timer A event mode
0 => PosEdge,
1 => NegEdge,
3 => AnyEdge,
},
4 => rtcen, //= RTC stall enable
5 => taote, //= Timer B output trigger enable
6 => tapwml, //= Timer B PWM output level
8 => tben, //= Timer B enable
9 => tbstall, //= Timer B stall enable
10..11 => tbevent, //= Timer B event mode
13 => tbote, //= Timer B output trigger enable
14 => tbpwml, //= Timer B PWM output level
}
0x28 => reg32 tailr {
0..31 => tailr, //= Timer A interval load
}
0x38 => reg32 apr {
0..15 => psr, //= Timer A prescale value
//= Only 8bit for 16/32bit timers
}
0x50 => reg32 tav {
0..31 => v, // Timer A counter value
}
});
pub const TIMER_0: *const Timer = 0x40030000 as *const Timer;
pub const TIMER_1: *const Timer = 0x40031000 as *const Timer;
pub const TIMER_2: *const Timer = 0x40032000 as *const Timer;
pub const TIMER_3: *const Timer = 0x40033000 as *const Timer;
pub const TIMER_4: *const Timer = 0x40034000 as *const Timer;
pub const TIMER_5: *const Timer = 0x40035000 as *const Timer;
pub const TIMER_W_0: *const Timer = 0x40036000 as *const Timer;
pub const TIMER_W_1: *const Timer = 0x40037000 as *const Timer;
pub const TIMER_W_2: *const Timer = 0x4003C000 as *const Timer;
pub const TIMER_W_3: *const Timer = 0x4003D000 as *const Timer;
pub const TIMER_W_4: *const Timer = 0x4003E000 as *const Timer;
pub const TIMER_W_5: *const Timer = 0x4003F000 as *const Timer;
}
|
{
// Make sure the timer is disabled before making changes.
self.regs.ctl.set_taen(false);
// Configure the timer as half-width so that we can use the prescaler
self.regs.cfg.set_cfg(reg::Timer_cfg_cfg::HalfWidth);
self.regs.amr
.set_mr(match self.mode {
Mode::OneShot => reg::Timer_amr_mr::OneShot,
Mode::Periodic => reg::Timer_amr_mr::Periodic,
_ => panic!("Unimplemented timer mode"),
})
// We need to count down in order for the prescaler to work as a
// prescaler. If we count up it becomes a timer extension (i.e. it becomes
// the MSBs of the counter).
.set_cdir(reg::Timer_amr_cdir::Down);
// Set maximum timeout value to overflow as late as possible
|
identifier_body
|
timer.rs
|
// Zinc, the bare metal stack for rust.
// Copyright 2014 Lionel Flandrin <[email protected]>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#![allow(missing_docs)]
//! Timer configuration
//! This code should support both standand and wide timers
use hal::tiva_c::sysctl;
use hal::timer;
use util::support::get_reg_ref;
/// There are 6 standard 16/32bit timers and 6 "wide" 32/64bit timers
#[allow(missing_docs)]
#[derive(Clone, Copy)]
pub enum
|
{
Timer0,
Timer1,
Timer2,
Timer3,
Timer4,
Timer5,
TimerW0,
TimerW1,
TimerW2,
TimerW3,
TimerW4,
TimerW5,
}
/// Timer modes
#[derive(Clone, Copy)]
pub enum Mode {
/// Periodic timer loops and restarts once the timeout is reached.
Periodic,
/// One shot timer is disabled once the timeout is reached.
OneShot,
/// RTC timer is based on the 32.768KHz clock and ticks at 1Hz
RTC,
/// EdgeCount timer counts rising/falling/both edge events on an
/// external pin.
EdgeCount,
/// EdgeTime timer measures the time it takes for a rising/falling/both edge
/// event to occur.
EdgeTime,
/// PWM mode can be used to generate a configurable square wave (frequence and
/// duty cycle)
PWM,
}
/// Structure describing a single timer counter (both 16/32bit and 32/64bit)
#[derive(Clone, Copy)]
pub struct Timer {
/// Timer register interface
regs : &'static reg::Timer,
/// True if the counter is wide 32/64bit
wide : bool,
/// Current timer mode
mode : Mode,
}
impl Timer {
/// Create and configure a Timer
pub fn new(id: TimerId,
mode: Mode,
prescale: u32) -> Timer {
let (periph, regs, wide) = match id {
TimerId::Timer0 =>
(sysctl::periph::timer::TIMER_0, reg::TIMER_0, false),
TimerId::Timer1 =>
(sysctl::periph::timer::TIMER_1, reg::TIMER_1, false),
TimerId::Timer2 =>
(sysctl::periph::timer::TIMER_2, reg::TIMER_2, false),
TimerId::Timer3 =>
(sysctl::periph::timer::TIMER_3, reg::TIMER_3, false),
TimerId::Timer4 =>
(sysctl::periph::timer::TIMER_4, reg::TIMER_4, false),
TimerId::Timer5 =>
(sysctl::periph::timer::TIMER_5, reg::TIMER_5, false),
TimerId::TimerW0 =>
(sysctl::periph::timer::TIMER_W_0, reg::TIMER_W_0, true),
TimerId::TimerW1 =>
(sysctl::periph::timer::TIMER_W_1, reg::TIMER_W_1, true),
TimerId::TimerW2 =>
(sysctl::periph::timer::TIMER_W_2, reg::TIMER_W_2, true),
TimerId::TimerW3 =>
(sysctl::periph::timer::TIMER_W_3, reg::TIMER_W_3, true),
TimerId::TimerW4 =>
(sysctl::periph::timer::TIMER_W_4, reg::TIMER_W_4, true),
TimerId::TimerW5 =>
(sysctl::periph::timer::TIMER_W_5, reg::TIMER_W_5, true),
};
periph.ensure_enabled();
let timer = Timer { regs: get_reg_ref(regs), wide: wide, mode: mode};
timer.configure(prescale);
timer
}
/// Configure timer registers
/// TODO(simias): Only Periodic and OneShot modes are implemented so far
pub fn configure(&self, prescale: u32) {
// Make sure the timer is disabled before making changes.
self.regs.ctl.set_taen(false);
// Configure the timer as half-width so that we can use the prescaler
self.regs.cfg.set_cfg(reg::Timer_cfg_cfg::HalfWidth);
self.regs.amr
.set_mr(match self.mode {
Mode::OneShot => reg::Timer_amr_mr::OneShot,
Mode::Periodic => reg::Timer_amr_mr::Periodic,
_ => panic!("Unimplemented timer mode"),
})
// We need to count down in order for the prescaler to work as a
// prescaler. If we count up it becomes a timer extension (i.e. it becomes
// the MSBs of the counter).
.set_cdir(reg::Timer_amr_cdir::Down);
// Set maximum timeout value to overflow as late as possible
self.regs.tailr.set_tailr(0xffffffff);
// Set prescale value
if!self.wide && prescale > 0xffff {
panic!("prescale is too wide for this timer");
}
self.regs.apr.set_psr(prescale as u32);
// Timer is now configured, we can enable it
self.regs.ctl.set_taen(true);
}
}
impl timer::Timer for Timer {
/// Retrieve the current timer value
#[inline(always)]
fn get_counter(&self) -> u32 {
// We count down, however the trait code expects that the counter increases,
// so we just complement the value to get an increasing counter.
!self.regs.tav.v()
}
}
pub mod reg {
//! Timer registers definition
use volatile_cell::VolatileCell;
use core::ops::Drop;
ioregs!(Timer = {
0x00 => reg32 cfg {
//! Timer configuration
0..2 => cfg {
0 => FullWidth,
1 => Rtc,
4 => HalfWidth,
},
}
0x04 => reg32 amr {
//! Timer A mode
0..1 => mr { //! mode
1 => OneShot,
2 => Periodic,
3 => Capture,
},
2 => cmr, //= capture mode
3 => ams, //= alternate mode select
4 => cdir { //! Count direction
0 => Down,
1 => Up,
},
5 => mie, //= match interrupt enable
6 => wot, //= wait on trigger
7 => snaps, //= snap-shot mode
8 => ild, //= interval load write
9 => pwmie, //= PWM interrupt enable
10 => rsu, //= match register update
11 => plo, //= PWM legacy operation
}
0x0C => reg32 ctl {
0 => taen, //= Timer A enable
1 => tastall, //= Timer A stall enable
2..3 => taevent { //! Timer A event mode
0 => PosEdge,
1 => NegEdge,
3 => AnyEdge,
},
4 => rtcen, //= RTC stall enable
5 => taote, //= Timer B output trigger enable
6 => tapwml, //= Timer B PWM output level
8 => tben, //= Timer B enable
9 => tbstall, //= Timer B stall enable
10..11 => tbevent, //= Timer B event mode
13 => tbote, //= Timer B output trigger enable
14 => tbpwml, //= Timer B PWM output level
}
0x28 => reg32 tailr {
0..31 => tailr, //= Timer A interval load
}
0x38 => reg32 apr {
0..15 => psr, //= Timer A prescale value
//= Only 8bit for 16/32bit timers
}
0x50 => reg32 tav {
0..31 => v, // Timer A counter value
}
});
pub const TIMER_0: *const Timer = 0x40030000 as *const Timer;
pub const TIMER_1: *const Timer = 0x40031000 as *const Timer;
pub const TIMER_2: *const Timer = 0x40032000 as *const Timer;
pub const TIMER_3: *const Timer = 0x40033000 as *const Timer;
pub const TIMER_4: *const Timer = 0x40034000 as *const Timer;
pub const TIMER_5: *const Timer = 0x40035000 as *const Timer;
pub const TIMER_W_0: *const Timer = 0x40036000 as *const Timer;
pub const TIMER_W_1: *const Timer = 0x40037000 as *const Timer;
pub const TIMER_W_2: *const Timer = 0x4003C000 as *const Timer;
pub const TIMER_W_3: *const Timer = 0x4003D000 as *const Timer;
pub const TIMER_W_4: *const Timer = 0x4003E000 as *const Timer;
pub const TIMER_W_5: *const Timer = 0x4003F000 as *const Timer;
}
|
TimerId
|
identifier_name
|
headless.rs
|
use BuilderAttribs;
use CreationError;
use CreationError::OsError;
use libc;
use std::{mem, ptr};
use super::ffi;
fn with_c_str<F, T>(s: &str, f: F) -> T where F: FnOnce(*const libc::c_char) -> T {
use std::ffi::CString;
let c_str = CString::from_slice(s.as_bytes());
f(c_str.as_slice_with_nul().as_ptr())
}
pub struct HeadlessContext {
context: ffi::OSMesaContext,
buffer: Vec<u32>,
width: u32,
height: u32,
}
impl HeadlessContext {
pub fn new(builder: BuilderAttribs) -> Result<HeadlessContext, CreationError> {
let dimensions = builder.dimensions.unwrap();
Ok(HeadlessContext {
width: dimensions.0,
height: dimensions.1,
buffer: ::std::iter::repeat(unsafe { mem::uninitialized() })
.take((dimensions.0 * dimensions.1) as usize).collect(),
context: unsafe {
let ctxt = ffi::OSMesaCreateContext(0x1908, ptr::null());
if ctxt.is_null() {
return Err(OsError("OSMesaCreateContext failed".to_string()));
}
ctxt
}
})
}
pub unsafe fn make_current(&self) {
let ret = ffi::OSMesaMakeCurrent(self.context,
self.buffer.as_ptr() as *mut libc::c_void,
0x1401, self.width as libc::c_int, self.height as libc::c_int);
if ret == 0 {
panic!("OSMesaMakeCurrent failed")
}
}
pub fn get_proc_address(&self, addr: &str) -> *const () {
unsafe {
with_c_str(addr, |s| {
ffi::OSMesaGetProcAddress(mem::transmute(s)) as *const ()
})
}
}
/// See the docs in the crate root file.
pub fn get_api(&self) -> ::Api {
::Api::OpenGl
}
pub fn set_window_resize_callback(&mut self, _: Option<fn(u32, u32)>)
|
}
impl Drop for HeadlessContext {
fn drop(&mut self) {
unsafe { ffi::OSMesaDestroyContext(self.context) }
}
}
unsafe impl Send for HeadlessContext {}
unsafe impl Sync for HeadlessContext {}
|
{
}
|
identifier_body
|
headless.rs
|
use BuilderAttribs;
use CreationError;
use CreationError::OsError;
use libc;
use std::{mem, ptr};
use super::ffi;
fn with_c_str<F, T>(s: &str, f: F) -> T where F: FnOnce(*const libc::c_char) -> T {
use std::ffi::CString;
let c_str = CString::from_slice(s.as_bytes());
f(c_str.as_slice_with_nul().as_ptr())
}
pub struct HeadlessContext {
context: ffi::OSMesaContext,
buffer: Vec<u32>,
width: u32,
height: u32,
}
impl HeadlessContext {
pub fn new(builder: BuilderAttribs) -> Result<HeadlessContext, CreationError> {
let dimensions = builder.dimensions.unwrap();
Ok(HeadlessContext {
width: dimensions.0,
height: dimensions.1,
buffer: ::std::iter::repeat(unsafe { mem::uninitialized() })
.take((dimensions.0 * dimensions.1) as usize).collect(),
context: unsafe {
let ctxt = ffi::OSMesaCreateContext(0x1908, ptr::null());
if ctxt.is_null()
|
ctxt
}
})
}
pub unsafe fn make_current(&self) {
let ret = ffi::OSMesaMakeCurrent(self.context,
self.buffer.as_ptr() as *mut libc::c_void,
0x1401, self.width as libc::c_int, self.height as libc::c_int);
if ret == 0 {
panic!("OSMesaMakeCurrent failed")
}
}
pub fn get_proc_address(&self, addr: &str) -> *const () {
unsafe {
with_c_str(addr, |s| {
ffi::OSMesaGetProcAddress(mem::transmute(s)) as *const ()
})
}
}
/// See the docs in the crate root file.
pub fn get_api(&self) -> ::Api {
::Api::OpenGl
}
pub fn set_window_resize_callback(&mut self, _: Option<fn(u32, u32)>) {
}
}
impl Drop for HeadlessContext {
fn drop(&mut self) {
unsafe { ffi::OSMesaDestroyContext(self.context) }
}
}
unsafe impl Send for HeadlessContext {}
unsafe impl Sync for HeadlessContext {}
|
{
return Err(OsError("OSMesaCreateContext failed".to_string()));
}
|
conditional_block
|
headless.rs
|
use BuilderAttribs;
use CreationError;
use CreationError::OsError;
use libc;
use std::{mem, ptr};
use super::ffi;
fn with_c_str<F, T>(s: &str, f: F) -> T where F: FnOnce(*const libc::c_char) -> T {
use std::ffi::CString;
let c_str = CString::from_slice(s.as_bytes());
f(c_str.as_slice_with_nul().as_ptr())
}
pub struct HeadlessContext {
context: ffi::OSMesaContext,
buffer: Vec<u32>,
width: u32,
height: u32,
}
|
pub fn new(builder: BuilderAttribs) -> Result<HeadlessContext, CreationError> {
let dimensions = builder.dimensions.unwrap();
Ok(HeadlessContext {
width: dimensions.0,
height: dimensions.1,
buffer: ::std::iter::repeat(unsafe { mem::uninitialized() })
.take((dimensions.0 * dimensions.1) as usize).collect(),
context: unsafe {
let ctxt = ffi::OSMesaCreateContext(0x1908, ptr::null());
if ctxt.is_null() {
return Err(OsError("OSMesaCreateContext failed".to_string()));
}
ctxt
}
})
}
pub unsafe fn make_current(&self) {
let ret = ffi::OSMesaMakeCurrent(self.context,
self.buffer.as_ptr() as *mut libc::c_void,
0x1401, self.width as libc::c_int, self.height as libc::c_int);
if ret == 0 {
panic!("OSMesaMakeCurrent failed")
}
}
pub fn get_proc_address(&self, addr: &str) -> *const () {
unsafe {
with_c_str(addr, |s| {
ffi::OSMesaGetProcAddress(mem::transmute(s)) as *const ()
})
}
}
/// See the docs in the crate root file.
pub fn get_api(&self) -> ::Api {
::Api::OpenGl
}
pub fn set_window_resize_callback(&mut self, _: Option<fn(u32, u32)>) {
}
}
impl Drop for HeadlessContext {
fn drop(&mut self) {
unsafe { ffi::OSMesaDestroyContext(self.context) }
}
}
unsafe impl Send for HeadlessContext {}
unsafe impl Sync for HeadlessContext {}
|
impl HeadlessContext {
|
random_line_split
|
headless.rs
|
use BuilderAttribs;
use CreationError;
use CreationError::OsError;
use libc;
use std::{mem, ptr};
use super::ffi;
fn with_c_str<F, T>(s: &str, f: F) -> T where F: FnOnce(*const libc::c_char) -> T {
use std::ffi::CString;
let c_str = CString::from_slice(s.as_bytes());
f(c_str.as_slice_with_nul().as_ptr())
}
pub struct HeadlessContext {
context: ffi::OSMesaContext,
buffer: Vec<u32>,
width: u32,
height: u32,
}
impl HeadlessContext {
pub fn new(builder: BuilderAttribs) -> Result<HeadlessContext, CreationError> {
let dimensions = builder.dimensions.unwrap();
Ok(HeadlessContext {
width: dimensions.0,
height: dimensions.1,
buffer: ::std::iter::repeat(unsafe { mem::uninitialized() })
.take((dimensions.0 * dimensions.1) as usize).collect(),
context: unsafe {
let ctxt = ffi::OSMesaCreateContext(0x1908, ptr::null());
if ctxt.is_null() {
return Err(OsError("OSMesaCreateContext failed".to_string()));
}
ctxt
}
})
}
pub unsafe fn make_current(&self) {
let ret = ffi::OSMesaMakeCurrent(self.context,
self.buffer.as_ptr() as *mut libc::c_void,
0x1401, self.width as libc::c_int, self.height as libc::c_int);
if ret == 0 {
panic!("OSMesaMakeCurrent failed")
}
}
pub fn get_proc_address(&self, addr: &str) -> *const () {
unsafe {
with_c_str(addr, |s| {
ffi::OSMesaGetProcAddress(mem::transmute(s)) as *const ()
})
}
}
/// See the docs in the crate root file.
pub fn get_api(&self) -> ::Api {
::Api::OpenGl
}
pub fn set_window_resize_callback(&mut self, _: Option<fn(u32, u32)>) {
}
}
impl Drop for HeadlessContext {
fn
|
(&mut self) {
unsafe { ffi::OSMesaDestroyContext(self.context) }
}
}
unsafe impl Send for HeadlessContext {}
unsafe impl Sync for HeadlessContext {}
|
drop
|
identifier_name
|
main.rs
|
// Copyright 2013-2014 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.
#![feature(dynamic_lib)]
use std::dynamic_lib::DynamicLibrary;
use std::path::Path;
pub fn main()
|
{
unsafe {
let path = Path::new("libdylib.so");
let a = DynamicLibrary::open(Some(&path)).unwrap();
assert!(a.symbol::<isize>("fun1").is_ok());
assert!(a.symbol::<isize>("fun2").is_err());
assert!(a.symbol::<isize>("fun3").is_err());
assert!(a.symbol::<isize>("fun4").is_ok());
assert!(a.symbol::<isize>("fun5").is_ok());
}
}
|
identifier_body
|
|
main.rs
|
// Copyright 2013-2014 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.
#![feature(dynamic_lib)]
use std::dynamic_lib::DynamicLibrary;
|
let a = DynamicLibrary::open(Some(&path)).unwrap();
assert!(a.symbol::<isize>("fun1").is_ok());
assert!(a.symbol::<isize>("fun2").is_err());
assert!(a.symbol::<isize>("fun3").is_err());
assert!(a.symbol::<isize>("fun4").is_ok());
assert!(a.symbol::<isize>("fun5").is_ok());
}
}
|
use std::path::Path;
pub fn main() {
unsafe {
let path = Path::new("libdylib.so");
|
random_line_split
|
main.rs
|
// Copyright 2013-2014 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.
#![feature(dynamic_lib)]
use std::dynamic_lib::DynamicLibrary;
use std::path::Path;
pub fn
|
() {
unsafe {
let path = Path::new("libdylib.so");
let a = DynamicLibrary::open(Some(&path)).unwrap();
assert!(a.symbol::<isize>("fun1").is_ok());
assert!(a.symbol::<isize>("fun2").is_err());
assert!(a.symbol::<isize>("fun3").is_err());
assert!(a.symbol::<isize>("fun4").is_ok());
assert!(a.symbol::<isize>("fun5").is_ok());
}
}
|
main
|
identifier_name
|
implicit.rs
|
// This example shows how to extract out details on implicit registers
// being read by instructions.
extern crate capstone_rust;
use capstone_rust::capstone as cs;
fn
|
() {
// Buffer of code.
let code = vec![0x01, 0xc0, 0xe8, 0x06, 0x00, 0x00, 0x00];
let dec = cs::Capstone::new(cs::cs_arch::CS_ARCH_X86, cs::cs_mode::CS_MODE_32).unwrap();
// Enable detail mode. This is needed if you want to get instruction details.
dec.option(cs::cs_opt_type::CS_OPT_DETAIL, cs::cs_opt_value::CS_OPT_ON).unwrap();
let buf = dec.disasm(code.as_slice(), 0x100, 0).unwrap();
for instr in buf.iter() {
println!("0x{:x}:\t{}\t{}", instr.address, instr.mnemonic, instr.op_str);
let details = instr.detail.unwrap();
if details.regs_read.len()!= 0 {
print!(" Implicit registers read:");
for read in details.regs_read.iter() {
// `read` is an int that correspond to an arch-specific register. In order to
// get its human readable name use `reg_name`.
print!(" {}", dec.reg_name(*read).unwrap());
}
print!("\n");
}
if details.regs_write.len()!= 0 {
print!(" Implicit registers written:");
for write in details.regs_write.iter() {
print!(" {}", dec.reg_name(*write).unwrap());
}
print!("\n");
}
}
}
|
main
|
identifier_name
|
implicit.rs
|
// This example shows how to extract out details on implicit registers
// being read by instructions.
extern crate capstone_rust;
use capstone_rust::capstone as cs;
fn main() {
// Buffer of code.
let code = vec![0x01, 0xc0, 0xe8, 0x06, 0x00, 0x00, 0x00];
let dec = cs::Capstone::new(cs::cs_arch::CS_ARCH_X86, cs::cs_mode::CS_MODE_32).unwrap();
// Enable detail mode. This is needed if you want to get instruction details.
dec.option(cs::cs_opt_type::CS_OPT_DETAIL, cs::cs_opt_value::CS_OPT_ON).unwrap();
let buf = dec.disasm(code.as_slice(), 0x100, 0).unwrap();
for instr in buf.iter() {
println!("0x{:x}:\t{}\t{}", instr.address, instr.mnemonic, instr.op_str);
let details = instr.detail.unwrap();
if details.regs_read.len()!= 0
|
if details.regs_write.len()!= 0 {
print!(" Implicit registers written:");
for write in details.regs_write.iter() {
print!(" {}", dec.reg_name(*write).unwrap());
}
print!("\n");
}
}
}
|
{
print!(" Implicit registers read:");
for read in details.regs_read.iter() {
// `read` is an int that correspond to an arch-specific register. In order to
// get its human readable name use `reg_name`.
print!(" {}", dec.reg_name(*read).unwrap());
}
print!("\n");
}
|
conditional_block
|
implicit.rs
|
// This example shows how to extract out details on implicit registers
// being read by instructions.
extern crate capstone_rust;
use capstone_rust::capstone as cs;
fn main()
|
print!(" {}", dec.reg_name(*read).unwrap());
}
print!("\n");
}
if details.regs_write.len()!= 0 {
print!(" Implicit registers written:");
for write in details.regs_write.iter() {
print!(" {}", dec.reg_name(*write).unwrap());
}
print!("\n");
}
}
}
|
{
// Buffer of code.
let code = vec![0x01, 0xc0, 0xe8, 0x06, 0x00, 0x00, 0x00];
let dec = cs::Capstone::new(cs::cs_arch::CS_ARCH_X86, cs::cs_mode::CS_MODE_32).unwrap();
// Enable detail mode. This is needed if you want to get instruction details.
dec.option(cs::cs_opt_type::CS_OPT_DETAIL, cs::cs_opt_value::CS_OPT_ON).unwrap();
let buf = dec.disasm(code.as_slice(), 0x100, 0).unwrap();
for instr in buf.iter() {
println!("0x{:x}:\t{}\t{}", instr.address, instr.mnemonic, instr.op_str);
let details = instr.detail.unwrap();
if details.regs_read.len() != 0 {
print!(" Implicit registers read:");
for read in details.regs_read.iter() {
// `read` is an int that correspond to an arch-specific register. In order to
// get its human readable name use `reg_name`.
|
identifier_body
|
implicit.rs
|
// This example shows how to extract out details on implicit registers
// being read by instructions.
extern crate capstone_rust;
use capstone_rust::capstone as cs;
fn main() {
// Buffer of code.
let code = vec![0x01, 0xc0, 0xe8, 0x06, 0x00, 0x00, 0x00];
let dec = cs::Capstone::new(cs::cs_arch::CS_ARCH_X86, cs::cs_mode::CS_MODE_32).unwrap();
// Enable detail mode. This is needed if you want to get instruction details.
dec.option(cs::cs_opt_type::CS_OPT_DETAIL, cs::cs_opt_value::CS_OPT_ON).unwrap();
let buf = dec.disasm(code.as_slice(), 0x100, 0).unwrap();
for instr in buf.iter() {
println!("0x{:x}:\t{}\t{}", instr.address, instr.mnemonic, instr.op_str);
let details = instr.detail.unwrap();
if details.regs_read.len()!= 0 {
print!(" Implicit registers read:");
for read in details.regs_read.iter() {
// `read` is an int that correspond to an arch-specific register. In order to
// get its human readable name use `reg_name`.
print!(" {}", dec.reg_name(*read).unwrap());
}
print!("\n");
}
if details.regs_write.len()!= 0 {
print!(" Implicit registers written:");
for write in details.regs_write.iter() {
print!(" {}", dec.reg_name(*write).unwrap());
}
print!("\n");
}
|
}
}
|
random_line_split
|
|
surface.rs
|
// Copyright 2013 The Servo Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution.
//
// 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.
//! Implementation of cross-process surfaces. This delegates to the platform-specific
//! implementation.
use texturegl::Texture;
use geom::size::Size2D;
#[cfg(target_os="macos")]
pub use platform::macos::surface::NativePaintingGraphicsContext;
#[cfg(target_os="macos")]
pub use platform::macos::surface::NativeCompositingGraphicsContext;
#[cfg(target_os="macos")]
pub use platform::macos::surface::NativeGraphicsMetadata;
#[cfg(target_os="macos")]
pub use platform::macos::surface::NativeGraphicsMetadataDescriptor;
#[cfg(target_os="macos")]
pub use platform::macos::surface::NativeSurface;
#[cfg(target_os="linux")]
pub use platform::linux::surface::NativePaintingGraphicsContext;
|
#[cfg(target_os="linux")]
pub use platform::linux::surface::NativeCompositingGraphicsContext;
#[cfg(target_os="linux")]
pub use platform::linux::surface::NativeGraphicsMetadata;
#[cfg(target_os="linux")]
pub use platform::linux::surface::NativeGraphicsMetadataDescriptor;
#[cfg(target_os="linux")]
pub use platform::linux::surface::NativeSurface;
pub trait NativeSurfaceMethods {
/// Creates a new native surface with uninitialized data.
fn new(native_context: &NativePaintingGraphicsContext, size: Size2D<i32>, stride: i32) -> Self;
/// Binds the surface to a GPU texture. Compositing task only.
fn bind_to_texture(&self,
native_context: &NativeCompositingGraphicsContext,
texture: &Texture,
size: Size2D<int>);
/// Uploads pixel data to the surface. Painting task only.
fn upload(&self, native_context: &NativePaintingGraphicsContext, data: &[u8]);
/// Returns an opaque ID identifying the surface for debugging.
fn get_id(&self) -> int;
/// Destroys the surface. After this, it is an error to use the surface. Painting task only.
fn destroy(&mut self, graphics_context: &NativePaintingGraphicsContext);
/// Records that the surface will leak if destroyed. This is done by the compositor immediately
/// after receiving the surface.
fn mark_will_leak(&mut self);
/// Marks the surface as not leaking. The painting task and the compositing task call this when
/// they are certain that the surface will not leak. For example:
///
/// 1. When sending buffers back to the render task, either the render task will receive them
/// or the render task has crashed. In the former case, they're the render task's
/// responsibility, so this is OK. In the latter case, the kernel or window server is going
/// to clean up the layer buffers. Either way, no leaks.
///
/// 2. If the compositor is shutting down, the render task is also shutting down. In that case
/// it will destroy all its pixmaps, so no leak.
///
/// 3. If the painting task is sending buffers to the compositor, then they are marked as not
/// leaking, because of the possibility that the compositor will die before the buffers are
/// destroyed.
///
/// This helps debug leaks. For performance this may want to become a no-op in the future.
fn mark_wont_leak(&mut self);
}
|
random_line_split
|
|
range_arg.rs
|
use std::ops::{Range, RangeFrom, RangeTo, RangeFull};
pub struct RangeArg {
pub start: usize,
pub end: Option<usize>,
}
impl RangeArg {
pub fn len(&self, len: usize) -> usize {
self.end.unwrap_or(len) - self.start
}
}
impl From<Range<usize>> for RangeArg {
#[inline]
fn from(r: Range<usize>) -> RangeArg {
RangeArg {
start: r.start,
end: Some(r.end),
}
}
}
impl From<RangeFrom<usize>> for RangeArg {
#[inline]
fn from(r: RangeFrom<usize>) -> RangeArg {
RangeArg {
start: r.start,
end: None,
}
}
}
impl From<RangeTo<usize>> for RangeArg {
#[inline]
fn from(r: RangeTo<usize>) -> RangeArg {
RangeArg {
start: 0,
end: Some(r.end),
}
}
}
impl From<RangeFull> for RangeArg {
#[inline]
fn from(_: RangeFull) -> RangeArg {
RangeArg {
start: 0,
end: None,
}
}
}
impl From<usize> for RangeArg {
#[inline]
fn from(i: usize) -> RangeArg {
RangeArg {
start: i,
end: Some(i+1),
}
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////
#[macro_export]
macro_rules! s(
(@as_expr $e:expr) => ($e);
(@parse [$($stack:tt)*] $r:expr) => {
s![@as_expr [$($stack)* s!(@step $r)]]
};
(@parse [$($stack:tt)*] $r:expr, $($t:tt)*) => {
s![@parse [$($stack)* s!(@step $r),] $($t)*]
};
(@step $r:expr) => {
<$crate::RangeArg as ::std::convert::From<_>>::from($r)
};
($($t:tt)*) => {
s![@parse [] $($t)*]
};
|
#[test]
fn test_s_macro() {
let s: [RangeArg; 2] = s![1..3, 1];
assert!(s[0].start == 1);
assert!(s[1].start == 1);
assert!(s[0].end == Some(3));
assert!(s[1].end == Some(2));
assert!(s[0].len(5) == 2);
assert!(s[1].len(5) == 1);
}
|
);
|
random_line_split
|
range_arg.rs
|
use std::ops::{Range, RangeFrom, RangeTo, RangeFull};
pub struct RangeArg {
pub start: usize,
pub end: Option<usize>,
}
impl RangeArg {
pub fn len(&self, len: usize) -> usize
|
}
impl From<Range<usize>> for RangeArg {
#[inline]
fn from(r: Range<usize>) -> RangeArg {
RangeArg {
start: r.start,
end: Some(r.end),
}
}
}
impl From<RangeFrom<usize>> for RangeArg {
#[inline]
fn from(r: RangeFrom<usize>) -> RangeArg {
RangeArg {
start: r.start,
end: None,
}
}
}
impl From<RangeTo<usize>> for RangeArg {
#[inline]
fn from(r: RangeTo<usize>) -> RangeArg {
RangeArg {
start: 0,
end: Some(r.end),
}
}
}
impl From<RangeFull> for RangeArg {
#[inline]
fn from(_: RangeFull) -> RangeArg {
RangeArg {
start: 0,
end: None,
}
}
}
impl From<usize> for RangeArg {
#[inline]
fn from(i: usize) -> RangeArg {
RangeArg {
start: i,
end: Some(i+1),
}
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////
#[macro_export]
macro_rules! s(
(@as_expr $e:expr) => ($e);
(@parse [$($stack:tt)*] $r:expr) => {
s![@as_expr [$($stack)* s!(@step $r)]]
};
(@parse [$($stack:tt)*] $r:expr, $($t:tt)*) => {
s![@parse [$($stack)* s!(@step $r),] $($t)*]
};
(@step $r:expr) => {
<$crate::RangeArg as ::std::convert::From<_>>::from($r)
};
($($t:tt)*) => {
s![@parse [] $($t)*]
};
);
#[test]
fn test_s_macro() {
let s: [RangeArg; 2] = s![1..3, 1];
assert!(s[0].start == 1);
assert!(s[1].start == 1);
assert!(s[0].end == Some(3));
assert!(s[1].end == Some(2));
assert!(s[0].len(5) == 2);
assert!(s[1].len(5) == 1);
}
|
{
self.end.unwrap_or(len) - self.start
}
|
identifier_body
|
range_arg.rs
|
use std::ops::{Range, RangeFrom, RangeTo, RangeFull};
pub struct RangeArg {
pub start: usize,
pub end: Option<usize>,
}
impl RangeArg {
pub fn len(&self, len: usize) -> usize {
self.end.unwrap_or(len) - self.start
}
}
impl From<Range<usize>> for RangeArg {
#[inline]
fn from(r: Range<usize>) -> RangeArg {
RangeArg {
start: r.start,
end: Some(r.end),
}
}
}
impl From<RangeFrom<usize>> for RangeArg {
#[inline]
fn from(r: RangeFrom<usize>) -> RangeArg {
RangeArg {
start: r.start,
end: None,
}
}
}
impl From<RangeTo<usize>> for RangeArg {
#[inline]
fn from(r: RangeTo<usize>) -> RangeArg {
RangeArg {
start: 0,
end: Some(r.end),
}
}
}
impl From<RangeFull> for RangeArg {
#[inline]
fn from(_: RangeFull) -> RangeArg {
RangeArg {
start: 0,
end: None,
}
}
}
impl From<usize> for RangeArg {
#[inline]
fn
|
(i: usize) -> RangeArg {
RangeArg {
start: i,
end: Some(i+1),
}
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////
#[macro_export]
macro_rules! s(
(@as_expr $e:expr) => ($e);
(@parse [$($stack:tt)*] $r:expr) => {
s![@as_expr [$($stack)* s!(@step $r)]]
};
(@parse [$($stack:tt)*] $r:expr, $($t:tt)*) => {
s![@parse [$($stack)* s!(@step $r),] $($t)*]
};
(@step $r:expr) => {
<$crate::RangeArg as ::std::convert::From<_>>::from($r)
};
($($t:tt)*) => {
s![@parse [] $($t)*]
};
);
#[test]
fn test_s_macro() {
let s: [RangeArg; 2] = s![1..3, 1];
assert!(s[0].start == 1);
assert!(s[1].start == 1);
assert!(s[0].end == Some(3));
assert!(s[1].end == Some(2));
assert!(s[0].len(5) == 2);
assert!(s[1].len(5) == 1);
}
|
from
|
identifier_name
|
root.rs
|
use std::ffi::CString;
use std::io::Error as IoError;
use std::path::Path;
use libc::chdir;
use libc::{c_int, c_char};
use crate::path_util::ToCString;
extern {
fn chroot(dir: *const c_char) -> c_int;
fn pivot_root(new_root: *const c_char, put_old: *const c_char) -> c_int;
}
#[cfg(not(feature="containers"))]
pub fn temporary_change_root<P, T, F, E>(path: P, mut fun: F) -> Result<T, E>
where F: FnMut() -> Result<T, E>,
E: From<String>,
P: AsRef<Path>,
{
unimplemented!();
}
#[cfg(feature="containers")]
pub fn temporary_change_root<P, T, F, E>(path: P, mut fun: F) -> Result<T, E>
where F: FnMut() -> Result<T, E>,
E: From<String>,
P: AsRef<Path>,
{
let path = path.as_ref();
let c_root = CString::new("/").unwrap();
if unsafe { chdir(c_root.as_ptr()) }!= 0 {
return Err(format!("Error chdir to root: {}",
IoError::last_os_error()).into());
}
if unsafe { chroot(path.to_cstring().as_ptr()) }!= 0 {
return Err(format!("Error chroot to {:?}: {}",
path, IoError::last_os_error()).into());
}
let res = fun();
let c_pwd = CString::new(".").unwrap();
if unsafe { chroot(c_pwd.as_ptr()) }!= 0 {
return Err(format!("Error chroot back: {}",
IoError::last_os_error()).into());
}
return res;
}
#[cfg(not(feature="containers"))]
pub fn change_root(new_root: &Path, put_old: &Path) -> Result<(), String>
{
unimplemented!();
}
#[cfg(feature="containers")]
pub fn change_root(new_root: &Path, put_old: &Path) -> Result<(), String>
|
{
let c_new_root = new_root.to_cstring();
let c_put_old = put_old.to_cstring();
if unsafe { pivot_root(c_new_root.as_ptr(), c_put_old.as_ptr()) } != 0 {
return Err(format!("Error pivot_root to {:?}: {}", new_root,
IoError::last_os_error()));
}
let c_root = CString::new("/").unwrap();
if unsafe { chdir(c_root.as_ptr()) } != 0 {
return Err(format!("Error chdir to root: {}",
IoError::last_os_error()));
}
return Ok(());
}
|
identifier_body
|
|
root.rs
|
use std::ffi::CString;
use std::io::Error as IoError;
use std::path::Path;
use libc::chdir;
use libc::{c_int, c_char};
use crate::path_util::ToCString;
|
extern {
fn chroot(dir: *const c_char) -> c_int;
fn pivot_root(new_root: *const c_char, put_old: *const c_char) -> c_int;
}
#[cfg(not(feature="containers"))]
pub fn temporary_change_root<P, T, F, E>(path: P, mut fun: F) -> Result<T, E>
where F: FnMut() -> Result<T, E>,
E: From<String>,
P: AsRef<Path>,
{
unimplemented!();
}
#[cfg(feature="containers")]
pub fn temporary_change_root<P, T, F, E>(path: P, mut fun: F) -> Result<T, E>
where F: FnMut() -> Result<T, E>,
E: From<String>,
P: AsRef<Path>,
{
let path = path.as_ref();
let c_root = CString::new("/").unwrap();
if unsafe { chdir(c_root.as_ptr()) }!= 0 {
return Err(format!("Error chdir to root: {}",
IoError::last_os_error()).into());
}
if unsafe { chroot(path.to_cstring().as_ptr()) }!= 0 {
return Err(format!("Error chroot to {:?}: {}",
path, IoError::last_os_error()).into());
}
let res = fun();
let c_pwd = CString::new(".").unwrap();
if unsafe { chroot(c_pwd.as_ptr()) }!= 0 {
return Err(format!("Error chroot back: {}",
IoError::last_os_error()).into());
}
return res;
}
#[cfg(not(feature="containers"))]
pub fn change_root(new_root: &Path, put_old: &Path) -> Result<(), String>
{
unimplemented!();
}
#[cfg(feature="containers")]
pub fn change_root(new_root: &Path, put_old: &Path) -> Result<(), String>
{
let c_new_root = new_root.to_cstring();
let c_put_old = put_old.to_cstring();
if unsafe { pivot_root(c_new_root.as_ptr(), c_put_old.as_ptr()) }!= 0 {
return Err(format!("Error pivot_root to {:?}: {}", new_root,
IoError::last_os_error()));
}
let c_root = CString::new("/").unwrap();
if unsafe { chdir(c_root.as_ptr()) }!= 0 {
return Err(format!("Error chdir to root: {}",
IoError::last_os_error()));
}
return Ok(());
}
|
random_line_split
|
|
root.rs
|
use std::ffi::CString;
use std::io::Error as IoError;
use std::path::Path;
use libc::chdir;
use libc::{c_int, c_char};
use crate::path_util::ToCString;
extern {
fn chroot(dir: *const c_char) -> c_int;
fn pivot_root(new_root: *const c_char, put_old: *const c_char) -> c_int;
}
#[cfg(not(feature="containers"))]
pub fn temporary_change_root<P, T, F, E>(path: P, mut fun: F) -> Result<T, E>
where F: FnMut() -> Result<T, E>,
E: From<String>,
P: AsRef<Path>,
{
unimplemented!();
}
#[cfg(feature="containers")]
pub fn temporary_change_root<P, T, F, E>(path: P, mut fun: F) -> Result<T, E>
where F: FnMut() -> Result<T, E>,
E: From<String>,
P: AsRef<Path>,
{
let path = path.as_ref();
let c_root = CString::new("/").unwrap();
if unsafe { chdir(c_root.as_ptr()) }!= 0
|
if unsafe { chroot(path.to_cstring().as_ptr()) }!= 0 {
return Err(format!("Error chroot to {:?}: {}",
path, IoError::last_os_error()).into());
}
let res = fun();
let c_pwd = CString::new(".").unwrap();
if unsafe { chroot(c_pwd.as_ptr()) }!= 0 {
return Err(format!("Error chroot back: {}",
IoError::last_os_error()).into());
}
return res;
}
#[cfg(not(feature="containers"))]
pub fn change_root(new_root: &Path, put_old: &Path) -> Result<(), String>
{
unimplemented!();
}
#[cfg(feature="containers")]
pub fn change_root(new_root: &Path, put_old: &Path) -> Result<(), String>
{
let c_new_root = new_root.to_cstring();
let c_put_old = put_old.to_cstring();
if unsafe { pivot_root(c_new_root.as_ptr(), c_put_old.as_ptr()) }!= 0 {
return Err(format!("Error pivot_root to {:?}: {}", new_root,
IoError::last_os_error()));
}
let c_root = CString::new("/").unwrap();
if unsafe { chdir(c_root.as_ptr()) }!= 0 {
return Err(format!("Error chdir to root: {}",
IoError::last_os_error()));
}
return Ok(());
}
|
{
return Err(format!("Error chdir to root: {}",
IoError::last_os_error()).into());
}
|
conditional_block
|
root.rs
|
use std::ffi::CString;
use std::io::Error as IoError;
use std::path::Path;
use libc::chdir;
use libc::{c_int, c_char};
use crate::path_util::ToCString;
extern {
fn chroot(dir: *const c_char) -> c_int;
fn pivot_root(new_root: *const c_char, put_old: *const c_char) -> c_int;
}
#[cfg(not(feature="containers"))]
pub fn temporary_change_root<P, T, F, E>(path: P, mut fun: F) -> Result<T, E>
where F: FnMut() -> Result<T, E>,
E: From<String>,
P: AsRef<Path>,
{
unimplemented!();
}
#[cfg(feature="containers")]
pub fn temporary_change_root<P, T, F, E>(path: P, mut fun: F) -> Result<T, E>
where F: FnMut() -> Result<T, E>,
E: From<String>,
P: AsRef<Path>,
{
let path = path.as_ref();
let c_root = CString::new("/").unwrap();
if unsafe { chdir(c_root.as_ptr()) }!= 0 {
return Err(format!("Error chdir to root: {}",
IoError::last_os_error()).into());
}
if unsafe { chroot(path.to_cstring().as_ptr()) }!= 0 {
return Err(format!("Error chroot to {:?}: {}",
path, IoError::last_os_error()).into());
}
let res = fun();
let c_pwd = CString::new(".").unwrap();
if unsafe { chroot(c_pwd.as_ptr()) }!= 0 {
return Err(format!("Error chroot back: {}",
IoError::last_os_error()).into());
}
return res;
}
#[cfg(not(feature="containers"))]
pub fn change_root(new_root: &Path, put_old: &Path) -> Result<(), String>
{
unimplemented!();
}
#[cfg(feature="containers")]
pub fn
|
(new_root: &Path, put_old: &Path) -> Result<(), String>
{
let c_new_root = new_root.to_cstring();
let c_put_old = put_old.to_cstring();
if unsafe { pivot_root(c_new_root.as_ptr(), c_put_old.as_ptr()) }!= 0 {
return Err(format!("Error pivot_root to {:?}: {}", new_root,
IoError::last_os_error()));
}
let c_root = CString::new("/").unwrap();
if unsafe { chdir(c_root.as_ptr()) }!= 0 {
return Err(format!("Error chdir to root: {}",
IoError::last_os_error()));
}
return Ok(());
}
|
change_root
|
identifier_name
|
runner.rs
|
// Copyright 2020 TiKV Project Authors. Licensed under Apache-2.0.
//! Useful functions for custom test framework.
//!
//! See https://doc.rust-lang.org/unstable-book/language-features/custom-test-frameworks.html.
use crate::test::*;
use std::cell::RefCell;
use std::env;
/// A runner function for running general tests.
pub fn run_tests(cases: &[&TestDescAndFn]) {
run_test_with_hook(cases, Nope)
}
/// Hooks for customize tests procedure.
pub trait TestHook {
/// Called before running every case.
fn setup(&mut self);
/// Called after every case.
fn teardown(&mut self);
}
/// A special TestHook that does nothing.
#[derive(Clone)]
struct Nope;
impl TestHook for Nope {
fn setup(&mut self) {}
fn teardown(&mut self) {}
}
struct CaseLifeWatcher<H: TestHook> {
name: String,
hook: H,
}
impl<H: TestHook + Send +'static> CaseLifeWatcher<H> {
fn new(name: String, mut hook: H) -> CaseLifeWatcher<H> {
debug!("case start"; "name" => &name);
hook.setup();
CaseLifeWatcher { name, hook }
}
}
impl<H: TestHook> Drop for CaseLifeWatcher<H> {
fn drop(&mut self) {
self.hook.teardown();
debug!("case end"; "name" => &self.name);
}
}
/// Connects std tests and custom test framework.
pub fn run_test_with_hook(cases: &[&TestDescAndFn], hook: impl TestHook + Send + Clone +'static) {
crate::setup_for_ci();
let cases: Vec<_> = cases
.iter()
.map(|case| {
let name = case.desc.name.as_slice().to_owned();
let h = hook.clone();
let f = match case.testfn {
TestFn::StaticTestFn(f) => TestFn::DynTestFn(Box::new(move || {
let _watcher = CaseLifeWatcher::new(name, h);
f();
})),
TestFn::StaticBenchFn(f) => TestFn::DynTestFn(Box::new(move || {
let _watcher = CaseLifeWatcher::new(name, h);
bench::run_once(move |b| f(b));
|
};
TestDescAndFn {
desc: case.desc.clone(),
testfn: f,
}
})
.collect();
let args = env::args().collect::<Vec<_>>();
test_main(&args, cases, None)
}
thread_local!(static FS: RefCell<Option<fail::FailScenario<'static>>> = RefCell::new(None));
#[derive(Clone)]
struct FailpointHook;
impl TestHook for FailpointHook {
fn setup(&mut self) {
FS.with(|s| {
s.borrow_mut().take();
*s.borrow_mut() = Some(fail::FailScenario::setup());
})
}
fn teardown(&mut self) {
FS.with(|s| {
s.borrow_mut().take();
})
}
}
/// During panic, due to drop order, failpoints will not be cleared before tests exit.
/// If tests wait for a sleep failpoint, the whole tests will hang. So we need a method
/// to clear failpoints explicitly besides teardown.
pub fn clear_failpoints() {
FS.with(|s| s.borrow_mut().take());
}
/// A runner function for running failpoint tests.
pub fn run_failpoint_tests(cases: &[&TestDescAndFn]) {
run_test_with_hook(cases, FailpointHook)
}
|
})),
ref f => panic!("unexpected testfn {:?}", f),
|
random_line_split
|
runner.rs
|
// Copyright 2020 TiKV Project Authors. Licensed under Apache-2.0.
//! Useful functions for custom test framework.
//!
//! See https://doc.rust-lang.org/unstable-book/language-features/custom-test-frameworks.html.
use crate::test::*;
use std::cell::RefCell;
use std::env;
/// A runner function for running general tests.
pub fn run_tests(cases: &[&TestDescAndFn]) {
run_test_with_hook(cases, Nope)
}
/// Hooks for customize tests procedure.
pub trait TestHook {
/// Called before running every case.
fn setup(&mut self);
/// Called after every case.
fn teardown(&mut self);
}
/// A special TestHook that does nothing.
#[derive(Clone)]
struct
|
;
impl TestHook for Nope {
fn setup(&mut self) {}
fn teardown(&mut self) {}
}
struct CaseLifeWatcher<H: TestHook> {
name: String,
hook: H,
}
impl<H: TestHook + Send +'static> CaseLifeWatcher<H> {
fn new(name: String, mut hook: H) -> CaseLifeWatcher<H> {
debug!("case start"; "name" => &name);
hook.setup();
CaseLifeWatcher { name, hook }
}
}
impl<H: TestHook> Drop for CaseLifeWatcher<H> {
fn drop(&mut self) {
self.hook.teardown();
debug!("case end"; "name" => &self.name);
}
}
/// Connects std tests and custom test framework.
pub fn run_test_with_hook(cases: &[&TestDescAndFn], hook: impl TestHook + Send + Clone +'static) {
crate::setup_for_ci();
let cases: Vec<_> = cases
.iter()
.map(|case| {
let name = case.desc.name.as_slice().to_owned();
let h = hook.clone();
let f = match case.testfn {
TestFn::StaticTestFn(f) => TestFn::DynTestFn(Box::new(move || {
let _watcher = CaseLifeWatcher::new(name, h);
f();
})),
TestFn::StaticBenchFn(f) => TestFn::DynTestFn(Box::new(move || {
let _watcher = CaseLifeWatcher::new(name, h);
bench::run_once(move |b| f(b));
})),
ref f => panic!("unexpected testfn {:?}", f),
};
TestDescAndFn {
desc: case.desc.clone(),
testfn: f,
}
})
.collect();
let args = env::args().collect::<Vec<_>>();
test_main(&args, cases, None)
}
thread_local!(static FS: RefCell<Option<fail::FailScenario<'static>>> = RefCell::new(None));
#[derive(Clone)]
struct FailpointHook;
impl TestHook for FailpointHook {
fn setup(&mut self) {
FS.with(|s| {
s.borrow_mut().take();
*s.borrow_mut() = Some(fail::FailScenario::setup());
})
}
fn teardown(&mut self) {
FS.with(|s| {
s.borrow_mut().take();
})
}
}
/// During panic, due to drop order, failpoints will not be cleared before tests exit.
/// If tests wait for a sleep failpoint, the whole tests will hang. So we need a method
/// to clear failpoints explicitly besides teardown.
pub fn clear_failpoints() {
FS.with(|s| s.borrow_mut().take());
}
/// A runner function for running failpoint tests.
pub fn run_failpoint_tests(cases: &[&TestDescAndFn]) {
run_test_with_hook(cases, FailpointHook)
}
|
Nope
|
identifier_name
|
runner.rs
|
// Copyright 2020 TiKV Project Authors. Licensed under Apache-2.0.
//! Useful functions for custom test framework.
//!
//! See https://doc.rust-lang.org/unstable-book/language-features/custom-test-frameworks.html.
use crate::test::*;
use std::cell::RefCell;
use std::env;
/// A runner function for running general tests.
pub fn run_tests(cases: &[&TestDescAndFn]) {
run_test_with_hook(cases, Nope)
}
/// Hooks for customize tests procedure.
pub trait TestHook {
/// Called before running every case.
fn setup(&mut self);
/// Called after every case.
fn teardown(&mut self);
}
/// A special TestHook that does nothing.
#[derive(Clone)]
struct Nope;
impl TestHook for Nope {
fn setup(&mut self) {}
fn teardown(&mut self)
|
}
struct CaseLifeWatcher<H: TestHook> {
name: String,
hook: H,
}
impl<H: TestHook + Send +'static> CaseLifeWatcher<H> {
fn new(name: String, mut hook: H) -> CaseLifeWatcher<H> {
debug!("case start"; "name" => &name);
hook.setup();
CaseLifeWatcher { name, hook }
}
}
impl<H: TestHook> Drop for CaseLifeWatcher<H> {
fn drop(&mut self) {
self.hook.teardown();
debug!("case end"; "name" => &self.name);
}
}
/// Connects std tests and custom test framework.
pub fn run_test_with_hook(cases: &[&TestDescAndFn], hook: impl TestHook + Send + Clone +'static) {
crate::setup_for_ci();
let cases: Vec<_> = cases
.iter()
.map(|case| {
let name = case.desc.name.as_slice().to_owned();
let h = hook.clone();
let f = match case.testfn {
TestFn::StaticTestFn(f) => TestFn::DynTestFn(Box::new(move || {
let _watcher = CaseLifeWatcher::new(name, h);
f();
})),
TestFn::StaticBenchFn(f) => TestFn::DynTestFn(Box::new(move || {
let _watcher = CaseLifeWatcher::new(name, h);
bench::run_once(move |b| f(b));
})),
ref f => panic!("unexpected testfn {:?}", f),
};
TestDescAndFn {
desc: case.desc.clone(),
testfn: f,
}
})
.collect();
let args = env::args().collect::<Vec<_>>();
test_main(&args, cases, None)
}
thread_local!(static FS: RefCell<Option<fail::FailScenario<'static>>> = RefCell::new(None));
#[derive(Clone)]
struct FailpointHook;
impl TestHook for FailpointHook {
fn setup(&mut self) {
FS.with(|s| {
s.borrow_mut().take();
*s.borrow_mut() = Some(fail::FailScenario::setup());
})
}
fn teardown(&mut self) {
FS.with(|s| {
s.borrow_mut().take();
})
}
}
/// During panic, due to drop order, failpoints will not be cleared before tests exit.
/// If tests wait for a sleep failpoint, the whole tests will hang. So we need a method
/// to clear failpoints explicitly besides teardown.
pub fn clear_failpoints() {
FS.with(|s| s.borrow_mut().take());
}
/// A runner function for running failpoint tests.
pub fn run_failpoint_tests(cases: &[&TestDescAndFn]) {
run_test_with_hook(cases, FailpointHook)
}
|
{}
|
identifier_body
|
styled.rs
|
use ascii_canvas::AsciiView;
use std::fmt::{Debug, Formatter, Error};
use style::Style;
use super::*;
pub struct Styled {
style: Style,
content: Box<Content>
}
impl Styled {
pub fn new(style: Style, content: Box<Content>) -> Self {
Styled {
style: style,
content: content,
}
}
}
impl Content for Styled {
fn
|
(&self) -> usize {
self.content.min_width()
}
fn emit(&self, view: &mut AsciiView) {
self.content.emit(&mut view.styled(self.style))
}
fn into_wrap_items(self: Box<Self>, wrap_items: &mut Vec<Box<Content>>) {
let style = self.style;
super::into_wrap_items_map(self.content,
wrap_items,
|item| Styled::new(style, item))
}
}
impl Debug for Styled {
fn fmt(&self, fmt: &mut Formatter) -> Result<(), Error> {
fmt.debug_struct("Styled")
.field("content", &self.content)
.finish()
}
}
|
min_width
|
identifier_name
|
styled.rs
|
use ascii_canvas::AsciiView;
use std::fmt::{Debug, Formatter, Error};
use style::Style;
use super::*;
pub struct Styled {
style: Style,
content: Box<Content>
}
impl Styled {
pub fn new(style: Style, content: Box<Content>) -> Self {
Styled {
style: style,
content: content,
}
}
}
impl Content for Styled {
fn min_width(&self) -> usize {
self.content.min_width()
}
fn emit(&self, view: &mut AsciiView) {
self.content.emit(&mut view.styled(self.style))
}
fn into_wrap_items(self: Box<Self>, wrap_items: &mut Vec<Box<Content>>) {
let style = self.style;
super::into_wrap_items_map(self.content,
wrap_items,
|item| Styled::new(style, item))
}
}
impl Debug for Styled {
|
}
|
fn fmt(&self, fmt: &mut Formatter) -> Result<(), Error> {
fmt.debug_struct("Styled")
.field("content", &self.content)
.finish()
}
|
random_line_split
|
styled.rs
|
use ascii_canvas::AsciiView;
use std::fmt::{Debug, Formatter, Error};
use style::Style;
use super::*;
pub struct Styled {
style: Style,
content: Box<Content>
}
impl Styled {
pub fn new(style: Style, content: Box<Content>) -> Self {
Styled {
style: style,
content: content,
}
}
}
impl Content for Styled {
fn min_width(&self) -> usize {
self.content.min_width()
}
fn emit(&self, view: &mut AsciiView) {
self.content.emit(&mut view.styled(self.style))
}
fn into_wrap_items(self: Box<Self>, wrap_items: &mut Vec<Box<Content>>)
|
}
impl Debug for Styled {
fn fmt(&self, fmt: &mut Formatter) -> Result<(), Error> {
fmt.debug_struct("Styled")
.field("content", &self.content)
.finish()
}
}
|
{
let style = self.style;
super::into_wrap_items_map(self.content,
wrap_items,
|item| Styled::new(style, item))
}
|
identifier_body
|
main.rs
|
// Copyright 2016 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.
// This tests rustc performance when a large amount variables are created which all have equality
// relations between them. With #32062 merged there should no longer be an exponentationl time
// complexity for this test.
fn main() {
let _ = test(Some(0).into_iter());
}
trait Parser {
type Input: Iterator;
type Output;
fn parse(self, input: Self::Input) -> Result<(Self::Output, Self::Input), ()>;
fn chain<P>(self, p: P) -> Chain<Self, P> where Self: Sized {
Chain(self, p)
}
}
struct Token<T>(T::Item) where T: Iterator;
impl<T> Parser for Token<T> where T: Iterator {
type Input = T;
type Output = T::Item;
fn parse(self, _input: Self::Input) -> Result<(Self::Output, Self::Input), ()> {
Err(())
}
}
struct Chain<L, R>(L, R);
impl<L, R> Parser for Chain<L, R> where L: Parser, R: Parser<Input = L::Input> {
type Input = L::Input;
type Output = (L::Output, R::Output);
fn parse(self, _input: Self::Input) -> Result<(Self::Output, Self::Input), ()> {
Err(())
}
}
|
.chain(Chain(Token(0), Token(1)))
.chain(Chain(Token(0), Token(1)))
.chain(Chain(Token(0), Token(1)))
.chain(Chain(Token(0), Token(1)))
.chain(Chain(Token(0), Token(1)))
.chain(Chain(Token(0), Token(1)))
.parse(i)
.map(|(_, i)| ((), i))
}
|
fn test<I>(i: I) -> Result<((), I), ()> where I: Iterator<Item = i32> {
Chain(Token(0), Token(1))
.chain(Chain(Token(0), Token(1)))
.chain(Chain(Token(0), Token(1)))
|
random_line_split
|
main.rs
|
// Copyright 2016 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.
// This tests rustc performance when a large amount variables are created which all have equality
// relations between them. With #32062 merged there should no longer be an exponentationl time
// complexity for this test.
fn main() {
let _ = test(Some(0).into_iter());
}
trait Parser {
type Input: Iterator;
type Output;
fn parse(self, input: Self::Input) -> Result<(Self::Output, Self::Input), ()>;
fn chain<P>(self, p: P) -> Chain<Self, P> where Self: Sized {
Chain(self, p)
}
}
struct Token<T>(T::Item) where T: Iterator;
impl<T> Parser for Token<T> where T: Iterator {
type Input = T;
type Output = T::Item;
fn parse(self, _input: Self::Input) -> Result<(Self::Output, Self::Input), ()> {
Err(())
}
}
struct Chain<L, R>(L, R);
impl<L, R> Parser for Chain<L, R> where L: Parser, R: Parser<Input = L::Input> {
type Input = L::Input;
type Output = (L::Output, R::Output);
fn parse(self, _input: Self::Input) -> Result<(Self::Output, Self::Input), ()> {
Err(())
}
}
fn
|
<I>(i: I) -> Result<((), I), ()> where I: Iterator<Item = i32> {
Chain(Token(0), Token(1))
.chain(Chain(Token(0), Token(1)))
.chain(Chain(Token(0), Token(1)))
.chain(Chain(Token(0), Token(1)))
.chain(Chain(Token(0), Token(1)))
.chain(Chain(Token(0), Token(1)))
.chain(Chain(Token(0), Token(1)))
.chain(Chain(Token(0), Token(1)))
.chain(Chain(Token(0), Token(1)))
.parse(i)
.map(|(_, i)| ((), i))
}
|
test
|
identifier_name
|
main.rs
|
// Copyright 2016 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.
// This tests rustc performance when a large amount variables are created which all have equality
// relations between them. With #32062 merged there should no longer be an exponentationl time
// complexity for this test.
fn main() {
let _ = test(Some(0).into_iter());
}
trait Parser {
type Input: Iterator;
type Output;
fn parse(self, input: Self::Input) -> Result<(Self::Output, Self::Input), ()>;
fn chain<P>(self, p: P) -> Chain<Self, P> where Self: Sized {
Chain(self, p)
}
}
struct Token<T>(T::Item) where T: Iterator;
impl<T> Parser for Token<T> where T: Iterator {
type Input = T;
type Output = T::Item;
fn parse(self, _input: Self::Input) -> Result<(Self::Output, Self::Input), ()> {
Err(())
}
}
struct Chain<L, R>(L, R);
impl<L, R> Parser for Chain<L, R> where L: Parser, R: Parser<Input = L::Input> {
type Input = L::Input;
type Output = (L::Output, R::Output);
fn parse(self, _input: Self::Input) -> Result<(Self::Output, Self::Input), ()> {
Err(())
}
}
fn test<I>(i: I) -> Result<((), I), ()> where I: Iterator<Item = i32>
|
{
Chain(Token(0), Token(1))
.chain(Chain(Token(0), Token(1)))
.chain(Chain(Token(0), Token(1)))
.chain(Chain(Token(0), Token(1)))
.chain(Chain(Token(0), Token(1)))
.chain(Chain(Token(0), Token(1)))
.chain(Chain(Token(0), Token(1)))
.chain(Chain(Token(0), Token(1)))
.chain(Chain(Token(0), Token(1)))
.parse(i)
.map(|(_, i)| ((), i))
}
|
identifier_body
|
|
isaac.rs
|
// http://rosettacode.org/wiki/The_ISAAC_Cipher
// includes the XOR version of the encryption scheme
#![feature(step_by)]
use std::num::Wrapping as w;
const MSG :&'static str = "a Top Secret secret";
const KEY: &'static str = "this is my secret key";
#[cfg(not(test))]
fn main () {
let mut isaac = Isaac::new();
isaac.seed(KEY, true);
let encr = isaac.vernam(MSG.as_bytes());
println!("msg: {}", MSG);
println!("key: {}", KEY);
print!("XOR: ");
for a in &encr {
print!("{:02X}", *a);
}
let mut isaac = Isaac::new();
isaac.seed(KEY, true);
let decr = isaac.vernam(&encr[..]);
print!("\nXOR dcr: ");
println!("{}", String::from_utf8(decr).unwrap())
}
macro_rules! mix_v(
($a:expr) => (
{
$a[0] = $a[0] ^ $a[1] << 11; $a[3] = $a[3] + $a[0]; $a[1] = $a[1] + $a[2];
$a[1] = $a[1] ^ $a[2] >> 2; $a[4] = $a[4] + $a[1]; $a[2] = $a[2] + $a[3];
$a[2] = $a[2] ^ $a[3] << 8; $a[5] = $a[5] + $a[2]; $a[3] = $a[3] + $a[4];
$a[3] = $a[3] ^ $a[4] >> 16; $a[6] = $a[6] + $a[3]; $a[4] = $a[4] + $a[5];
$a[4] = $a[4] ^ $a[5] << 10; $a[7] = $a[7] + $a[4]; $a[5] = $a[5] + $a[6];
$a[5] = $a[5] ^ $a[6] >> 4; $a[0] = $a[0] + $a[5]; $a[6] = $a[6] + $a[7];
$a[6] = $a[6] ^ $a[7] << 8; $a[1] = $a[1] + $a[6]; $a[7] = $a[7] + $a[0];
$a[7] = $a[7] ^ $a[0] >> 9; $a[2] = $a[2] + $a[7]; $a[0] = $a[0] + $a[1];
} );
);
struct Isaac {
mm: [w<u32>; 256],
aa: w<u32>,
bb: w<u32>,
cc: w<u32>,
rand_rsl: [w<u32>; 256],
rand_cnt: u32
}
impl Isaac {
fn new() -> Isaac {
Isaac {
mm: [w(0u32); 256],
aa: w(0),
bb: w(0),
cc: w(0),
rand_rsl: [w(0u32); 256],
rand_cnt: 0
}
}
fn isaac(&mut self) {
self.cc = self.cc + w(1);
self.bb = self.bb + self.cc;
for i in 0..256 {
let w(x) = self.mm[i];
match i%4 {
0 => self.aa = self.aa ^ self.aa << 13,
1 => self.aa = self.aa ^ self.aa >> 6,
2 => self.aa = self.aa ^ self.aa << 2,
3 => self.aa = self.aa ^ self.aa >> 16,
_ => unreachable!()
}
self.aa = self.mm[((i + 128) % 256) as usize] + self.aa;
let w(y) = self.mm[((x >> 2) % 256) as usize] + self.aa + self.bb;
self.bb = self.mm[((y >> 10) % 256) as usize] + w(x);
self.rand_rsl[i] = self.bb;
}
self.rand_cnt = 0;
}
fn rand_init(&mut self, flag: bool)
{
let mut a_v = [w(0x9e3779b9u32); 8];
for _ in 0..4 {
// scramble it
mix_v!(a_v);
}
for i in (0..256).step_by(8) {
// fill in mm[] with messy stuff
if flag {
// use all the information in the seed
for j in 0..8 { a_v[j] = a_v[j] + self.rand_rsl[i+j]; }
}
mix_v!(a_v);
for j in 0..8 { self.mm[i+j] = a_v[j]; }
}
if flag {
// do a second pass to make all of the seed affect all of mm
for i in (0..256).step_by(8) {
for j in 0..8 { a_v[j] = a_v[j] + self.mm[i+j]; }
mix_v!(a_v);
for j in 0..8 { self.mm[i+j] = a_v[j]; }
}
}
self.isaac(); // fill in the first set of results
self.rand_cnt = 0; // prepare to use the first set of results
}
// Get a random 32-bit value
fn i_random(&mut self) -> u32 {
let r = self.rand_rsl[self.rand_cnt as usize];
self.rand_cnt += 1;
if self.rand_cnt >255 {
self.isaac();
self.rand_cnt = 0;
}
r.0
}
// Seed ISAAC with a string
fn seed(&mut self, seed: &str, flag: bool) {
for i in 0..256 { self.mm[i] = w(0); }
for i in 0..256 { self.rand_rsl[i] = w(0); }
for i in 0..seed.len() {
self.rand_rsl[i] = w(seed.as_bytes()[i] as u32);
}
// initialize ISAAC with seed
self.rand_init(flag);
}
// Get a random character in printable ASCII range
fn i_rand_ascii(&mut self) -> u8
|
/// XOR message
fn vernam(&mut self, msg :&[u8]) -> Vec<u8> {
msg.iter().map(|&b| (self.i_rand_ascii() ^ b))
.collect::<Vec<u8>>()
}
}
#[cfg(test)]
mod test {
use super::{Isaac, MSG, KEY};
const ENCRIPTED: [u8; 19] = [0x1C, 0x06, 0x36, 0x19, 0x0B, 0x12,
0x60, 0x23, 0x3B, 0x35, 0x12, 0x5F, 0x1E, 0x1D, 0x0E, 0x2F,
0x4C, 0x54, 0x22];
#[test]
fn encrypt() {
let mut isaac = Isaac::new();
isaac.seed(KEY, true);
let encr = isaac.vernam(MSG.as_bytes());
for (a, b) in encr.iter().zip(ENCRIPTED.iter()) {
assert_eq!(a, b);
}
}
#[test]
fn decrypt() {
let expected = MSG;
let mut isaac = Isaac::new();
isaac.seed(KEY, true);
let decr = isaac.vernam(&ENCRIPTED[..]);
for (&a, b) in decr.iter().zip(expected.bytes()) {
assert_eq!(a, b);
}
}
}
|
{
(self.i_random() % 95 + 32) as u8
}
|
identifier_body
|
isaac.rs
|
// http://rosettacode.org/wiki/The_ISAAC_Cipher
// includes the XOR version of the encryption scheme
#![feature(step_by)]
use std::num::Wrapping as w;
const MSG :&'static str = "a Top Secret secret";
const KEY: &'static str = "this is my secret key";
#[cfg(not(test))]
fn main () {
let mut isaac = Isaac::new();
isaac.seed(KEY, true);
let encr = isaac.vernam(MSG.as_bytes());
println!("msg: {}", MSG);
println!("key: {}", KEY);
print!("XOR: ");
for a in &encr {
print!("{:02X}", *a);
}
let mut isaac = Isaac::new();
isaac.seed(KEY, true);
let decr = isaac.vernam(&encr[..]);
print!("\nXOR dcr: ");
println!("{}", String::from_utf8(decr).unwrap())
}
macro_rules! mix_v(
($a:expr) => (
{
$a[0] = $a[0] ^ $a[1] << 11; $a[3] = $a[3] + $a[0]; $a[1] = $a[1] + $a[2];
$a[1] = $a[1] ^ $a[2] >> 2; $a[4] = $a[4] + $a[1]; $a[2] = $a[2] + $a[3];
$a[2] = $a[2] ^ $a[3] << 8; $a[5] = $a[5] + $a[2]; $a[3] = $a[3] + $a[4];
$a[3] = $a[3] ^ $a[4] >> 16; $a[6] = $a[6] + $a[3]; $a[4] = $a[4] + $a[5];
$a[4] = $a[4] ^ $a[5] << 10; $a[7] = $a[7] + $a[4]; $a[5] = $a[5] + $a[6];
$a[5] = $a[5] ^ $a[6] >> 4; $a[0] = $a[0] + $a[5]; $a[6] = $a[6] + $a[7];
$a[6] = $a[6] ^ $a[7] << 8; $a[1] = $a[1] + $a[6]; $a[7] = $a[7] + $a[0];
$a[7] = $a[7] ^ $a[0] >> 9; $a[2] = $a[2] + $a[7]; $a[0] = $a[0] + $a[1];
} );
);
struct Isaac {
mm: [w<u32>; 256],
aa: w<u32>,
bb: w<u32>,
cc: w<u32>,
rand_rsl: [w<u32>; 256],
rand_cnt: u32
}
impl Isaac {
fn new() -> Isaac {
Isaac {
mm: [w(0u32); 256],
aa: w(0),
bb: w(0),
cc: w(0),
rand_rsl: [w(0u32); 256],
rand_cnt: 0
}
}
fn isaac(&mut self) {
self.cc = self.cc + w(1);
self.bb = self.bb + self.cc;
for i in 0..256 {
let w(x) = self.mm[i];
match i%4 {
0 => self.aa = self.aa ^ self.aa << 13,
1 => self.aa = self.aa ^ self.aa >> 6,
2 => self.aa = self.aa ^ self.aa << 2,
3 => self.aa = self.aa ^ self.aa >> 16,
_ => unreachable!()
}
self.aa = self.mm[((i + 128) % 256) as usize] + self.aa;
let w(y) = self.mm[((x >> 2) % 256) as usize] + self.aa + self.bb;
self.bb = self.mm[((y >> 10) % 256) as usize] + w(x);
self.rand_rsl[i] = self.bb;
}
self.rand_cnt = 0;
}
fn rand_init(&mut self, flag: bool)
{
let mut a_v = [w(0x9e3779b9u32); 8];
for _ in 0..4 {
// scramble it
mix_v!(a_v);
}
for i in (0..256).step_by(8) {
// fill in mm[] with messy stuff
if flag
|
mix_v!(a_v);
for j in 0..8 { self.mm[i+j] = a_v[j]; }
}
if flag {
// do a second pass to make all of the seed affect all of mm
for i in (0..256).step_by(8) {
for j in 0..8 { a_v[j] = a_v[j] + self.mm[i+j]; }
mix_v!(a_v);
for j in 0..8 { self.mm[i+j] = a_v[j]; }
}
}
self.isaac(); // fill in the first set of results
self.rand_cnt = 0; // prepare to use the first set of results
}
// Get a random 32-bit value
fn i_random(&mut self) -> u32 {
let r = self.rand_rsl[self.rand_cnt as usize];
self.rand_cnt += 1;
if self.rand_cnt >255 {
self.isaac();
self.rand_cnt = 0;
}
r.0
}
// Seed ISAAC with a string
fn seed(&mut self, seed: &str, flag: bool) {
for i in 0..256 { self.mm[i] = w(0); }
for i in 0..256 { self.rand_rsl[i] = w(0); }
for i in 0..seed.len() {
self.rand_rsl[i] = w(seed.as_bytes()[i] as u32);
}
// initialize ISAAC with seed
self.rand_init(flag);
}
// Get a random character in printable ASCII range
fn i_rand_ascii(&mut self) -> u8 {
(self.i_random() % 95 + 32) as u8
}
/// XOR message
fn vernam(&mut self, msg :&[u8]) -> Vec<u8> {
msg.iter().map(|&b| (self.i_rand_ascii() ^ b))
.collect::<Vec<u8>>()
}
}
#[cfg(test)]
mod test {
use super::{Isaac, MSG, KEY};
const ENCRIPTED: [u8; 19] = [0x1C, 0x06, 0x36, 0x19, 0x0B, 0x12,
0x60, 0x23, 0x3B, 0x35, 0x12, 0x5F, 0x1E, 0x1D, 0x0E, 0x2F,
0x4C, 0x54, 0x22];
#[test]
fn encrypt() {
let mut isaac = Isaac::new();
isaac.seed(KEY, true);
let encr = isaac.vernam(MSG.as_bytes());
for (a, b) in encr.iter().zip(ENCRIPTED.iter()) {
assert_eq!(a, b);
}
}
#[test]
fn decrypt() {
let expected = MSG;
let mut isaac = Isaac::new();
isaac.seed(KEY, true);
let decr = isaac.vernam(&ENCRIPTED[..]);
for (&a, b) in decr.iter().zip(expected.bytes()) {
assert_eq!(a, b);
}
}
}
|
{
// use all the information in the seed
for j in 0..8 { a_v[j] = a_v[j] + self.rand_rsl[i+j]; }
}
|
conditional_block
|
isaac.rs
|
// http://rosettacode.org/wiki/The_ISAAC_Cipher
// includes the XOR version of the encryption scheme
#![feature(step_by)]
use std::num::Wrapping as w;
const MSG :&'static str = "a Top Secret secret";
const KEY: &'static str = "this is my secret key";
#[cfg(not(test))]
fn main () {
let mut isaac = Isaac::new();
isaac.seed(KEY, true);
let encr = isaac.vernam(MSG.as_bytes());
println!("msg: {}", MSG);
println!("key: {}", KEY);
print!("XOR: ");
for a in &encr {
print!("{:02X}", *a);
}
let mut isaac = Isaac::new();
isaac.seed(KEY, true);
let decr = isaac.vernam(&encr[..]);
print!("\nXOR dcr: ");
println!("{}", String::from_utf8(decr).unwrap())
}
macro_rules! mix_v(
($a:expr) => (
{
$a[0] = $a[0] ^ $a[1] << 11; $a[3] = $a[3] + $a[0]; $a[1] = $a[1] + $a[2];
$a[1] = $a[1] ^ $a[2] >> 2; $a[4] = $a[4] + $a[1]; $a[2] = $a[2] + $a[3];
$a[2] = $a[2] ^ $a[3] << 8; $a[5] = $a[5] + $a[2]; $a[3] = $a[3] + $a[4];
$a[3] = $a[3] ^ $a[4] >> 16; $a[6] = $a[6] + $a[3]; $a[4] = $a[4] + $a[5];
$a[4] = $a[4] ^ $a[5] << 10; $a[7] = $a[7] + $a[4]; $a[5] = $a[5] + $a[6];
$a[5] = $a[5] ^ $a[6] >> 4; $a[0] = $a[0] + $a[5]; $a[6] = $a[6] + $a[7];
$a[6] = $a[6] ^ $a[7] << 8; $a[1] = $a[1] + $a[6]; $a[7] = $a[7] + $a[0];
$a[7] = $a[7] ^ $a[0] >> 9; $a[2] = $a[2] + $a[7]; $a[0] = $a[0] + $a[1];
} );
);
struct Isaac {
mm: [w<u32>; 256],
aa: w<u32>,
bb: w<u32>,
cc: w<u32>,
rand_rsl: [w<u32>; 256],
rand_cnt: u32
}
impl Isaac {
fn new() -> Isaac {
Isaac {
mm: [w(0u32); 256],
aa: w(0),
bb: w(0),
cc: w(0),
rand_rsl: [w(0u32); 256],
rand_cnt: 0
}
}
fn isaac(&mut self) {
self.cc = self.cc + w(1);
self.bb = self.bb + self.cc;
for i in 0..256 {
let w(x) = self.mm[i];
match i%4 {
0 => self.aa = self.aa ^ self.aa << 13,
1 => self.aa = self.aa ^ self.aa >> 6,
2 => self.aa = self.aa ^ self.aa << 2,
3 => self.aa = self.aa ^ self.aa >> 16,
_ => unreachable!()
}
self.aa = self.mm[((i + 128) % 256) as usize] + self.aa;
let w(y) = self.mm[((x >> 2) % 256) as usize] + self.aa + self.bb;
self.bb = self.mm[((y >> 10) % 256) as usize] + w(x);
self.rand_rsl[i] = self.bb;
}
self.rand_cnt = 0;
}
fn rand_init(&mut self, flag: bool)
{
let mut a_v = [w(0x9e3779b9u32); 8];
for _ in 0..4 {
// scramble it
mix_v!(a_v);
}
for i in (0..256).step_by(8) {
// fill in mm[] with messy stuff
if flag {
// use all the information in the seed
for j in 0..8 { a_v[j] = a_v[j] + self.rand_rsl[i+j]; }
}
mix_v!(a_v);
for j in 0..8 { self.mm[i+j] = a_v[j]; }
}
if flag {
// do a second pass to make all of the seed affect all of mm
for i in (0..256).step_by(8) {
for j in 0..8 { a_v[j] = a_v[j] + self.mm[i+j]; }
mix_v!(a_v);
for j in 0..8 { self.mm[i+j] = a_v[j]; }
}
}
self.isaac(); // fill in the first set of results
self.rand_cnt = 0; // prepare to use the first set of results
}
// Get a random 32-bit value
fn i_random(&mut self) -> u32 {
let r = self.rand_rsl[self.rand_cnt as usize];
self.rand_cnt += 1;
if self.rand_cnt >255 {
self.isaac();
self.rand_cnt = 0;
}
r.0
}
// Seed ISAAC with a string
fn
|
(&mut self, seed: &str, flag: bool) {
for i in 0..256 { self.mm[i] = w(0); }
for i in 0..256 { self.rand_rsl[i] = w(0); }
for i in 0..seed.len() {
self.rand_rsl[i] = w(seed.as_bytes()[i] as u32);
}
// initialize ISAAC with seed
self.rand_init(flag);
}
// Get a random character in printable ASCII range
fn i_rand_ascii(&mut self) -> u8 {
(self.i_random() % 95 + 32) as u8
}
/// XOR message
fn vernam(&mut self, msg :&[u8]) -> Vec<u8> {
msg.iter().map(|&b| (self.i_rand_ascii() ^ b))
.collect::<Vec<u8>>()
}
}
#[cfg(test)]
mod test {
use super::{Isaac, MSG, KEY};
const ENCRIPTED: [u8; 19] = [0x1C, 0x06, 0x36, 0x19, 0x0B, 0x12,
0x60, 0x23, 0x3B, 0x35, 0x12, 0x5F, 0x1E, 0x1D, 0x0E, 0x2F,
0x4C, 0x54, 0x22];
#[test]
fn encrypt() {
let mut isaac = Isaac::new();
isaac.seed(KEY, true);
let encr = isaac.vernam(MSG.as_bytes());
for (a, b) in encr.iter().zip(ENCRIPTED.iter()) {
assert_eq!(a, b);
}
}
#[test]
fn decrypt() {
let expected = MSG;
let mut isaac = Isaac::new();
isaac.seed(KEY, true);
let decr = isaac.vernam(&ENCRIPTED[..]);
for (&a, b) in decr.iter().zip(expected.bytes()) {
assert_eq!(a, b);
}
}
}
|
seed
|
identifier_name
|
isaac.rs
|
// http://rosettacode.org/wiki/The_ISAAC_Cipher
// includes the XOR version of the encryption scheme
#![feature(step_by)]
use std::num::Wrapping as w;
const MSG :&'static str = "a Top Secret secret";
const KEY: &'static str = "this is my secret key";
#[cfg(not(test))]
fn main () {
let mut isaac = Isaac::new();
isaac.seed(KEY, true);
let encr = isaac.vernam(MSG.as_bytes());
println!("msg: {}", MSG);
println!("key: {}", KEY);
print!("XOR: ");
for a in &encr {
print!("{:02X}", *a);
}
let mut isaac = Isaac::new();
isaac.seed(KEY, true);
let decr = isaac.vernam(&encr[..]);
print!("\nXOR dcr: ");
println!("{}", String::from_utf8(decr).unwrap())
}
macro_rules! mix_v(
($a:expr) => (
{
$a[0] = $a[0] ^ $a[1] << 11; $a[3] = $a[3] + $a[0]; $a[1] = $a[1] + $a[2];
$a[1] = $a[1] ^ $a[2] >> 2; $a[4] = $a[4] + $a[1]; $a[2] = $a[2] + $a[3];
$a[2] = $a[2] ^ $a[3] << 8; $a[5] = $a[5] + $a[2]; $a[3] = $a[3] + $a[4];
$a[3] = $a[3] ^ $a[4] >> 16; $a[6] = $a[6] + $a[3]; $a[4] = $a[4] + $a[5];
$a[4] = $a[4] ^ $a[5] << 10; $a[7] = $a[7] + $a[4]; $a[5] = $a[5] + $a[6];
$a[5] = $a[5] ^ $a[6] >> 4; $a[0] = $a[0] + $a[5]; $a[6] = $a[6] + $a[7];
$a[6] = $a[6] ^ $a[7] << 8; $a[1] = $a[1] + $a[6]; $a[7] = $a[7] + $a[0];
$a[7] = $a[7] ^ $a[0] >> 9; $a[2] = $a[2] + $a[7]; $a[0] = $a[0] + $a[1];
} );
);
struct Isaac {
mm: [w<u32>; 256],
aa: w<u32>,
bb: w<u32>,
cc: w<u32>,
rand_rsl: [w<u32>; 256],
rand_cnt: u32
}
impl Isaac {
fn new() -> Isaac {
Isaac {
mm: [w(0u32); 256],
aa: w(0),
bb: w(0),
cc: w(0),
rand_rsl: [w(0u32); 256],
rand_cnt: 0
}
}
fn isaac(&mut self) {
self.cc = self.cc + w(1);
self.bb = self.bb + self.cc;
for i in 0..256 {
let w(x) = self.mm[i];
match i%4 {
0 => self.aa = self.aa ^ self.aa << 13,
1 => self.aa = self.aa ^ self.aa >> 6,
2 => self.aa = self.aa ^ self.aa << 2,
3 => self.aa = self.aa ^ self.aa >> 16,
_ => unreachable!()
}
self.aa = self.mm[((i + 128) % 256) as usize] + self.aa;
let w(y) = self.mm[((x >> 2) % 256) as usize] + self.aa + self.bb;
self.bb = self.mm[((y >> 10) % 256) as usize] + w(x);
self.rand_rsl[i] = self.bb;
}
self.rand_cnt = 0;
}
fn rand_init(&mut self, flag: bool)
{
let mut a_v = [w(0x9e3779b9u32); 8];
for _ in 0..4 {
// scramble it
mix_v!(a_v);
}
for i in (0..256).step_by(8) {
// fill in mm[] with messy stuff
if flag {
// use all the information in the seed
for j in 0..8 { a_v[j] = a_v[j] + self.rand_rsl[i+j]; }
}
mix_v!(a_v);
for j in 0..8 { self.mm[i+j] = a_v[j]; }
}
if flag {
// do a second pass to make all of the seed affect all of mm
for i in (0..256).step_by(8) {
for j in 0..8 { a_v[j] = a_v[j] + self.mm[i+j]; }
mix_v!(a_v);
for j in 0..8 { self.mm[i+j] = a_v[j]; }
}
}
self.isaac(); // fill in the first set of results
self.rand_cnt = 0; // prepare to use the first set of results
}
// Get a random 32-bit value
fn i_random(&mut self) -> u32 {
let r = self.rand_rsl[self.rand_cnt as usize];
self.rand_cnt += 1;
if self.rand_cnt >255 {
self.isaac();
self.rand_cnt = 0;
}
r.0
}
// Seed ISAAC with a string
fn seed(&mut self, seed: &str, flag: bool) {
for i in 0..256 { self.mm[i] = w(0); }
for i in 0..256 { self.rand_rsl[i] = w(0); }
for i in 0..seed.len() {
self.rand_rsl[i] = w(seed.as_bytes()[i] as u32);
}
// initialize ISAAC with seed
self.rand_init(flag);
}
// Get a random character in printable ASCII range
fn i_rand_ascii(&mut self) -> u8 {
(self.i_random() % 95 + 32) as u8
}
/// XOR message
fn vernam(&mut self, msg :&[u8]) -> Vec<u8> {
msg.iter().map(|&b| (self.i_rand_ascii() ^ b))
.collect::<Vec<u8>>()
}
}
#[cfg(test)]
mod test {
use super::{Isaac, MSG, KEY};
const ENCRIPTED: [u8; 19] = [0x1C, 0x06, 0x36, 0x19, 0x0B, 0x12,
0x60, 0x23, 0x3B, 0x35, 0x12, 0x5F, 0x1E, 0x1D, 0x0E, 0x2F,
0x4C, 0x54, 0x22];
#[test]
fn encrypt() {
let mut isaac = Isaac::new();
|
for (a, b) in encr.iter().zip(ENCRIPTED.iter()) {
assert_eq!(a, b);
}
}
#[test]
fn decrypt() {
let expected = MSG;
let mut isaac = Isaac::new();
isaac.seed(KEY, true);
let decr = isaac.vernam(&ENCRIPTED[..]);
for (&a, b) in decr.iter().zip(expected.bytes()) {
assert_eq!(a, b);
}
}
}
|
isaac.seed(KEY, true);
let encr = isaac.vernam(MSG.as_bytes());
|
random_line_split
|
lib.rs
|
#![feature(libc)]
extern crate estimate_pi;
use estimate_pi::estimate;
#[cfg(not(target_os = "emscripten"))]
use estimate_pi::ws;
extern crate libc;
use libc::{c_double};
#[no_mangle]
pub extern "C" fn pi_est(points: c_double) -> c_double {
estimate(points)
}
#[cfg(not(target_os = "emscripten"))]
#[no_mangle]
pub extern "C" fn ws_pi_est(points: c_double) -> c_double {
ws::estimate(points)
}
#[cfg(test)]
mod pi_est_tests {
use pi_est;
#[test]
fn pi_est_test() {
let pi = pi_est(1e6);
assert!((pi > 2.64) && (pi < 3.64), "estimated pi value is more than 0.5 off");
}
}
#[cfg(not(target_os = "emscripten"))]
#[cfg(test)]
mod ws_pi_est_tests {
use ws_pi_est;
|
let pi = ws_pi_est(1e6);
assert!((pi > 2.64) && (pi < 3.64), "estimated pi value is more than 0.5 off");
}
}
|
#[test]
fn ws_pi_est_test() {
|
random_line_split
|
lib.rs
|
#![feature(libc)]
extern crate estimate_pi;
use estimate_pi::estimate;
#[cfg(not(target_os = "emscripten"))]
use estimate_pi::ws;
extern crate libc;
use libc::{c_double};
#[no_mangle]
pub extern "C" fn
|
(points: c_double) -> c_double {
estimate(points)
}
#[cfg(not(target_os = "emscripten"))]
#[no_mangle]
pub extern "C" fn ws_pi_est(points: c_double) -> c_double {
ws::estimate(points)
}
#[cfg(test)]
mod pi_est_tests {
use pi_est;
#[test]
fn pi_est_test() {
let pi = pi_est(1e6);
assert!((pi > 2.64) && (pi < 3.64), "estimated pi value is more than 0.5 off");
}
}
#[cfg(not(target_os = "emscripten"))]
#[cfg(test)]
mod ws_pi_est_tests {
use ws_pi_est;
#[test]
fn ws_pi_est_test() {
let pi = ws_pi_est(1e6);
assert!((pi > 2.64) && (pi < 3.64), "estimated pi value is more than 0.5 off");
}
}
|
pi_est
|
identifier_name
|
lib.rs
|
#![feature(libc)]
extern crate estimate_pi;
use estimate_pi::estimate;
#[cfg(not(target_os = "emscripten"))]
use estimate_pi::ws;
extern crate libc;
use libc::{c_double};
#[no_mangle]
pub extern "C" fn pi_est(points: c_double) -> c_double
|
#[cfg(not(target_os = "emscripten"))]
#[no_mangle]
pub extern "C" fn ws_pi_est(points: c_double) -> c_double {
ws::estimate(points)
}
#[cfg(test)]
mod pi_est_tests {
use pi_est;
#[test]
fn pi_est_test() {
let pi = pi_est(1e6);
assert!((pi > 2.64) && (pi < 3.64), "estimated pi value is more than 0.5 off");
}
}
#[cfg(not(target_os = "emscripten"))]
#[cfg(test)]
mod ws_pi_est_tests {
use ws_pi_est;
#[test]
fn ws_pi_est_test() {
let pi = ws_pi_est(1e6);
assert!((pi > 2.64) && (pi < 3.64), "estimated pi value is more than 0.5 off");
}
}
|
{
estimate(points)
}
|
identifier_body
|
while-prelude-drop.rs
|
// Copyright 2012 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.
#[deriving(Eq)]
enum t { a, b(~str), }
fn make(i: int) -> t {
if i > 10 { return a; }
let mut s = ~"hello";
// Ensure s is non-const.
s += ~"there";
return b(s);
}
pub fn
|
() {
let mut i = 0;
// The auto slot for the result of make(i) should not leak.
while make(i)!= a { i += 1; }
}
|
main
|
identifier_name
|
while-prelude-drop.rs
|
// Copyright 2012 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.
#[deriving(Eq)]
enum t { a, b(~str), }
fn make(i: int) -> t {
if i > 10 { return a; }
let mut s = ~"hello";
// Ensure s is non-const.
s += ~"there";
return b(s);
}
pub fn main()
|
{
let mut i = 0;
// The auto slot for the result of make(i) should not leak.
while make(i) != a { i += 1; }
}
|
identifier_body
|
|
while-prelude-drop.rs
|
// Copyright 2012 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.
#[deriving(Eq)]
enum t { a, b(~str), }
fn make(i: int) -> t {
if i > 10
|
let mut s = ~"hello";
// Ensure s is non-const.
s += ~"there";
return b(s);
}
pub fn main() {
let mut i = 0;
// The auto slot for the result of make(i) should not leak.
while make(i)!= a { i += 1; }
}
|
{ return a; }
|
conditional_block
|
while-prelude-drop.rs
|
// Copyright 2012 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.
#[deriving(Eq)]
enum t { a, b(~str), }
fn make(i: int) -> t {
if i > 10 { return a; }
let mut s = ~"hello";
// Ensure s is non-const.
s += ~"there";
return b(s);
}
pub fn main() {
let mut i = 0;
// The auto slot for the result of make(i) should not leak.
while make(i)!= a { i += 1; }
}
|
random_line_split
|
|
lib.rs
|
use formats::{match_name, Format};
use once_cell::sync::Lazy;
use parser::{
eyre::{bail, Result},
graph_triples::{Resource, ResourceInfo},
ParserTrait,
};
use std::collections::BTreeMap;
use std::sync::Arc;
// Re-exports
pub use parser::Parser;
// The following high level functions hide the implementation
// detail of having a static list of parsers. They are intended as the
// only public interface for this crate.
pub fn parse(resource: Resource, code: &str) -> Result<ResourceInfo> {
PARSERS.parse(resource, code)
}
/// The set of registered parsers in the current process
static PARSERS: Lazy<Arc<Parsers>> = Lazy::new(|| Arc::new(Parsers::new()));
/// A set of registered parsers, either built-in, or provided by plugins
struct Parsers {
inner: BTreeMap<String, Parser>,
}
/// A macro to dispatch methods to builtin parsers
///
/// This avoids having to do a search over the parsers's specs for matching `languages`.
macro_rules! dispatch_builtins {
($format:expr, $method:ident $(,$arg:expr)*) => {
match $format {
#[cfg(feature = "parser-bash")]
Format::Bash | Format::Shell | Format::Zsh => Some(parser_bash::BashParser::$method($($arg),*)),
#[cfg(feature = "parser-calc")]
Format::Calc => Some(parser_calc::CalcParser::$method($($arg),*)),
#[cfg(feature = "parser-js")]
Format::JavaScript => Some(parser_js::JsParser::$method($($arg),*)),
#[cfg(feature = "parser-py")]
Format::Python => Some(parser_py::PyParser::$method($($arg),*)),
#[cfg(feature = "parser-r")]
Format::R => Some(parser_r::RParser::$method($($arg),*)),
#[cfg(feature = "parser-rust")]
Format::Rust => Some(parser_rust::RustParser::$method($($arg),*)),
#[cfg(feature = "parser-ts")]
Format::TypeScript => Some(parser_ts::TsParser::$method($($arg),*)),
// Fallback to empty result
_ => Option::<Result<ResourceInfo>>::None
}
};
}
impl Parsers {
/// Create a set of parsers
///
/// Note that these strings are labels for the parser which
/// aim to be consistent with the parser name, are convenient
/// to use to `stencila parsers show`, and don't need to be
/// consistent with format names or aliases.
pub fn new() -> Self {
let inner = vec![
#[cfg(feature = "parser-bash")]
("bash", parser_bash::BashParser::spec()),
#[cfg(feature = "parser-calc")]
("calc", parser_calc::CalcParser::spec()),
#[cfg(feature = "parser-js")]
("js", parser_js::JsParser::spec()),
#[cfg(feature = "parser-py")]
("py", parser_py::PyParser::spec()),
#[cfg(feature = "parser-r")]
("r", parser_r::RParser::spec()),
#[cfg(feature = "parser-rust")]
("rust", parser_rust::RustParser::spec()),
#[cfg(feature = "parser-ts")]
("ts", parser_ts::TsParser::spec()),
]
.into_iter()
.map(|(label, parser): (&str, Parser)| (label.to_string(), parser))
.collect();
Self { inner }
}
/// List the available parsers
fn list(&self) -> Vec<String> {
self.inner
.keys()
.into_iter()
.cloned()
.collect::<Vec<String>>()
}
/// Get a parser by label
fn get(&self, label: &str) -> Result<Parser> {
match self.inner.get(label) {
Some(parser) => Ok(parser.clone()),
None => bail!("No parser with label `{}`", label),
}
}
/// Parse a code resource
fn parse(&self, resource: Resource, code: &str) -> Result<ResourceInfo> {
let (path, language) = if let Resource::Code(code) = &resource {
(code.path.clone(), code.language.clone().unwrap_or_default())
} else {
bail!("Attempting to parse a resource that is not a `Code` resource")
};
let format = match_name(&language);
let resource_info =
if let Some(result) = dispatch_builtins!(format, parse, resource, &path, code) {
result?
} else {
bail!(
"Unable to parse code in language `{}`: no matching parser found",
language
)
};
Ok(resource_info)
}
}
impl Default for Parsers {
fn default() -> Self {
Self::new()
}
}
#[cfg(feature = "cli")]
pub mod commands {
use std::{fs, path::PathBuf};
use super::*;
use cli_utils::{async_trait::async_trait, result, Result, Run};
use parser::graph_triples::resources;
use structopt::StructOpt;
#[derive(Debug, StructOpt)]
#[structopt(
about = "Manage and use parsers",
setting = structopt::clap::AppSettings::ColoredHelp,
setting = structopt::clap::AppSettings::VersionlessSubcommands
)]
pub struct Command {
#[structopt(subcommand)]
pub action: Action,
}
#[derive(Debug, StructOpt)]
#[structopt(
setting = structopt::clap::AppSettings::DeriveDisplayOrder
)]
pub enum Action {
List(List),
Show(Show),
Parse(Parse),
}
#[async_trait]
impl Run for Command {
async fn run(&self) -> Result {
let Self { action } = self;
match action {
Action::List(action) => action.run().await,
Action::Show(action) => action.run().await,
Action::Parse(action) => action.run().await,
}
}
}
/// List the parsers that are available
///
/// The list of available parsers includes those that are built into the Stencila
/// binary as well as any parsers provided by plugins.
#[derive(Debug, StructOpt)]
#[structopt(
setting = structopt::clap::AppSettings::ColoredHelp
)]
|
impl Run for List {
async fn run(&self) -> Result {
let list = PARSERS.list();
result::value(list)
}
}
/// Show the specifications of a parser
#[derive(Debug, StructOpt)]
#[structopt(
setting = structopt::clap::AppSettings::ColoredHelp
)]
pub struct Show {
/// The label of the parser
///
/// To get the list of parser labels use `stencila parsers list`.
label: String,
}
#[async_trait]
impl Run for Show {
async fn run(&self) -> Result {
let parser = PARSERS.get(&self.label)?;
result::value(parser)
}
}
/// Parse some code using a parser
///
/// The code is parsed into a set of graph `Relation`/`Resource` pairs using the
/// parser that matches the filename extension (or specified using `--lang`).
/// Useful for testing Stencila's static code analysis for a particular language.
#[derive(Debug, StructOpt)]
#[structopt(
setting = structopt::clap::AppSettings::ColoredHelp
)]
pub struct Parse {
/// The file (or code) to parse
#[structopt(multiple = true)]
code: Vec<String>,
/// If the argument should be treated as text, rather than a file path
#[structopt(short, long)]
text: bool,
/// The language of the code
#[structopt(short, long)]
lang: Option<String>,
}
#[async_trait]
impl Run for Parse {
async fn run(&self) -> Result {
let (path, code, lang) = if self.text || self.code.len() > 1 {
let code = self.code.join(" ");
(
"<text>".to_string(),
code,
self.lang.clone().unwrap_or_default(),
)
} else {
let file = self.code[0].clone();
let code = fs::read_to_string(&file)?;
let ext = PathBuf::from(&file)
.extension()
.map(|ext| ext.to_string_lossy().to_string())
.unwrap_or_default();
let lang = self.lang.clone().or(Some(ext)).unwrap_or_default();
(file, code, lang)
};
let path = PathBuf::from(path);
let resource = resources::code(&path, "<id>", "<cli>", Some(lang));
let resource_info = PARSERS.parse(resource, &code)?;
result::value(resource_info)
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use parser::graph_triples::{relations, resources};
use std::path::PathBuf;
use test_utils::assert_json_eq;
#[test]
#[cfg(feature = "parser-calc")]
fn test_parse() -> Result<()> {
let path = PathBuf::from("<test>");
let resource = resources::code(&path, "<id>", "<cli>", Some("Calc".to_string()));
let resource_info = parse(resource, "a = 1\nb = a * a")?;
assert!(matches!(resource_info.execute_pure, None));
assert!(!resource_info.is_pure());
assert_json_eq!(
resource_info.relations,
vec![
(
relations::assigns((0, 0, 0, 1)),
resources::symbol(&path, "a", "Number")
),
(
relations::assigns((1, 0, 1, 1)),
resources::symbol(&path, "b", "Number")
),
(
relations::uses((1, 4, 1, 5)),
resources::symbol(&path, "a", "Number")
),
(
relations::uses((1, 8, 1, 9)),
resources::symbol(&path, "a", "Number")
)
]
);
Ok(())
}
}
|
pub struct List {}
#[async_trait]
|
random_line_split
|
lib.rs
|
use formats::{match_name, Format};
use once_cell::sync::Lazy;
use parser::{
eyre::{bail, Result},
graph_triples::{Resource, ResourceInfo},
ParserTrait,
};
use std::collections::BTreeMap;
use std::sync::Arc;
// Re-exports
pub use parser::Parser;
// The following high level functions hide the implementation
// detail of having a static list of parsers. They are intended as the
// only public interface for this crate.
pub fn parse(resource: Resource, code: &str) -> Result<ResourceInfo> {
PARSERS.parse(resource, code)
}
/// The set of registered parsers in the current process
static PARSERS: Lazy<Arc<Parsers>> = Lazy::new(|| Arc::new(Parsers::new()));
/// A set of registered parsers, either built-in, or provided by plugins
struct Parsers {
inner: BTreeMap<String, Parser>,
}
/// A macro to dispatch methods to builtin parsers
///
/// This avoids having to do a search over the parsers's specs for matching `languages`.
macro_rules! dispatch_builtins {
($format:expr, $method:ident $(,$arg:expr)*) => {
match $format {
#[cfg(feature = "parser-bash")]
Format::Bash | Format::Shell | Format::Zsh => Some(parser_bash::BashParser::$method($($arg),*)),
#[cfg(feature = "parser-calc")]
Format::Calc => Some(parser_calc::CalcParser::$method($($arg),*)),
#[cfg(feature = "parser-js")]
Format::JavaScript => Some(parser_js::JsParser::$method($($arg),*)),
#[cfg(feature = "parser-py")]
Format::Python => Some(parser_py::PyParser::$method($($arg),*)),
#[cfg(feature = "parser-r")]
Format::R => Some(parser_r::RParser::$method($($arg),*)),
#[cfg(feature = "parser-rust")]
Format::Rust => Some(parser_rust::RustParser::$method($($arg),*)),
#[cfg(feature = "parser-ts")]
Format::TypeScript => Some(parser_ts::TsParser::$method($($arg),*)),
// Fallback to empty result
_ => Option::<Result<ResourceInfo>>::None
}
};
}
impl Parsers {
/// Create a set of parsers
///
/// Note that these strings are labels for the parser which
/// aim to be consistent with the parser name, are convenient
/// to use to `stencila parsers show`, and don't need to be
/// consistent with format names or aliases.
pub fn new() -> Self {
let inner = vec![
#[cfg(feature = "parser-bash")]
("bash", parser_bash::BashParser::spec()),
#[cfg(feature = "parser-calc")]
("calc", parser_calc::CalcParser::spec()),
#[cfg(feature = "parser-js")]
("js", parser_js::JsParser::spec()),
#[cfg(feature = "parser-py")]
("py", parser_py::PyParser::spec()),
#[cfg(feature = "parser-r")]
("r", parser_r::RParser::spec()),
#[cfg(feature = "parser-rust")]
("rust", parser_rust::RustParser::spec()),
#[cfg(feature = "parser-ts")]
("ts", parser_ts::TsParser::spec()),
]
.into_iter()
.map(|(label, parser): (&str, Parser)| (label.to_string(), parser))
.collect();
Self { inner }
}
/// List the available parsers
fn list(&self) -> Vec<String> {
self.inner
.keys()
.into_iter()
.cloned()
.collect::<Vec<String>>()
}
/// Get a parser by label
fn get(&self, label: &str) -> Result<Parser> {
match self.inner.get(label) {
Some(parser) => Ok(parser.clone()),
None => bail!("No parser with label `{}`", label),
}
}
/// Parse a code resource
fn parse(&self, resource: Resource, code: &str) -> Result<ResourceInfo> {
let (path, language) = if let Resource::Code(code) = &resource {
(code.path.clone(), code.language.clone().unwrap_or_default())
} else {
bail!("Attempting to parse a resource that is not a `Code` resource")
};
let format = match_name(&language);
let resource_info =
if let Some(result) = dispatch_builtins!(format, parse, resource, &path, code) {
result?
} else {
bail!(
"Unable to parse code in language `{}`: no matching parser found",
language
)
};
Ok(resource_info)
}
}
impl Default for Parsers {
fn default() -> Self {
Self::new()
}
}
#[cfg(feature = "cli")]
pub mod commands {
use std::{fs, path::PathBuf};
use super::*;
use cli_utils::{async_trait::async_trait, result, Result, Run};
use parser::graph_triples::resources;
use structopt::StructOpt;
#[derive(Debug, StructOpt)]
#[structopt(
about = "Manage and use parsers",
setting = structopt::clap::AppSettings::ColoredHelp,
setting = structopt::clap::AppSettings::VersionlessSubcommands
)]
pub struct Command {
#[structopt(subcommand)]
pub action: Action,
}
#[derive(Debug, StructOpt)]
#[structopt(
setting = structopt::clap::AppSettings::DeriveDisplayOrder
)]
pub enum Action {
List(List),
Show(Show),
Parse(Parse),
}
#[async_trait]
impl Run for Command {
async fn run(&self) -> Result {
let Self { action } = self;
match action {
Action::List(action) => action.run().await,
Action::Show(action) => action.run().await,
Action::Parse(action) => action.run().await,
}
}
}
/// List the parsers that are available
///
/// The list of available parsers includes those that are built into the Stencila
/// binary as well as any parsers provided by plugins.
#[derive(Debug, StructOpt)]
#[structopt(
setting = structopt::clap::AppSettings::ColoredHelp
)]
pub struct List {}
#[async_trait]
impl Run for List {
async fn run(&self) -> Result {
let list = PARSERS.list();
result::value(list)
}
}
/// Show the specifications of a parser
#[derive(Debug, StructOpt)]
#[structopt(
setting = structopt::clap::AppSettings::ColoredHelp
)]
pub struct Show {
/// The label of the parser
///
/// To get the list of parser labels use `stencila parsers list`.
label: String,
}
#[async_trait]
impl Run for Show {
async fn run(&self) -> Result {
let parser = PARSERS.get(&self.label)?;
result::value(parser)
}
}
/// Parse some code using a parser
///
/// The code is parsed into a set of graph `Relation`/`Resource` pairs using the
/// parser that matches the filename extension (or specified using `--lang`).
/// Useful for testing Stencila's static code analysis for a particular language.
#[derive(Debug, StructOpt)]
#[structopt(
setting = structopt::clap::AppSettings::ColoredHelp
)]
pub struct Parse {
/// The file (or code) to parse
#[structopt(multiple = true)]
code: Vec<String>,
/// If the argument should be treated as text, rather than a file path
#[structopt(short, long)]
text: bool,
/// The language of the code
#[structopt(short, long)]
lang: Option<String>,
}
#[async_trait]
impl Run for Parse {
async fn run(&self) -> Result {
let (path, code, lang) = if self.text || self.code.len() > 1 {
let code = self.code.join(" ");
(
"<text>".to_string(),
code,
self.lang.clone().unwrap_or_default(),
)
} else {
let file = self.code[0].clone();
let code = fs::read_to_string(&file)?;
let ext = PathBuf::from(&file)
.extension()
.map(|ext| ext.to_string_lossy().to_string())
.unwrap_or_default();
let lang = self.lang.clone().or(Some(ext)).unwrap_or_default();
(file, code, lang)
};
let path = PathBuf::from(path);
let resource = resources::code(&path, "<id>", "<cli>", Some(lang));
let resource_info = PARSERS.parse(resource, &code)?;
result::value(resource_info)
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use parser::graph_triples::{relations, resources};
use std::path::PathBuf;
use test_utils::assert_json_eq;
#[test]
#[cfg(feature = "parser-calc")]
fn test_parse() -> Result<()>
|
),
(
relations::uses((1, 8, 1, 9)),
resources::symbol(&path, "a", "Number")
)
]
);
Ok(())
}
}
|
{
let path = PathBuf::from("<test>");
let resource = resources::code(&path, "<id>", "<cli>", Some("Calc".to_string()));
let resource_info = parse(resource, "a = 1\nb = a * a")?;
assert!(matches!(resource_info.execute_pure, None));
assert!(!resource_info.is_pure());
assert_json_eq!(
resource_info.relations,
vec![
(
relations::assigns((0, 0, 0, 1)),
resources::symbol(&path, "a", "Number")
),
(
relations::assigns((1, 0, 1, 1)),
resources::symbol(&path, "b", "Number")
),
(
relations::uses((1, 4, 1, 5)),
resources::symbol(&path, "a", "Number")
|
identifier_body
|
lib.rs
|
use formats::{match_name, Format};
use once_cell::sync::Lazy;
use parser::{
eyre::{bail, Result},
graph_triples::{Resource, ResourceInfo},
ParserTrait,
};
use std::collections::BTreeMap;
use std::sync::Arc;
// Re-exports
pub use parser::Parser;
// The following high level functions hide the implementation
// detail of having a static list of parsers. They are intended as the
// only public interface for this crate.
pub fn parse(resource: Resource, code: &str) -> Result<ResourceInfo> {
PARSERS.parse(resource, code)
}
/// The set of registered parsers in the current process
static PARSERS: Lazy<Arc<Parsers>> = Lazy::new(|| Arc::new(Parsers::new()));
/// A set of registered parsers, either built-in, or provided by plugins
struct Parsers {
inner: BTreeMap<String, Parser>,
}
/// A macro to dispatch methods to builtin parsers
///
/// This avoids having to do a search over the parsers's specs for matching `languages`.
macro_rules! dispatch_builtins {
($format:expr, $method:ident $(,$arg:expr)*) => {
match $format {
#[cfg(feature = "parser-bash")]
Format::Bash | Format::Shell | Format::Zsh => Some(parser_bash::BashParser::$method($($arg),*)),
#[cfg(feature = "parser-calc")]
Format::Calc => Some(parser_calc::CalcParser::$method($($arg),*)),
#[cfg(feature = "parser-js")]
Format::JavaScript => Some(parser_js::JsParser::$method($($arg),*)),
#[cfg(feature = "parser-py")]
Format::Python => Some(parser_py::PyParser::$method($($arg),*)),
#[cfg(feature = "parser-r")]
Format::R => Some(parser_r::RParser::$method($($arg),*)),
#[cfg(feature = "parser-rust")]
Format::Rust => Some(parser_rust::RustParser::$method($($arg),*)),
#[cfg(feature = "parser-ts")]
Format::TypeScript => Some(parser_ts::TsParser::$method($($arg),*)),
// Fallback to empty result
_ => Option::<Result<ResourceInfo>>::None
}
};
}
impl Parsers {
/// Create a set of parsers
///
/// Note that these strings are labels for the parser which
/// aim to be consistent with the parser name, are convenient
/// to use to `stencila parsers show`, and don't need to be
/// consistent with format names or aliases.
pub fn new() -> Self {
let inner = vec![
#[cfg(feature = "parser-bash")]
("bash", parser_bash::BashParser::spec()),
#[cfg(feature = "parser-calc")]
("calc", parser_calc::CalcParser::spec()),
#[cfg(feature = "parser-js")]
("js", parser_js::JsParser::spec()),
#[cfg(feature = "parser-py")]
("py", parser_py::PyParser::spec()),
#[cfg(feature = "parser-r")]
("r", parser_r::RParser::spec()),
#[cfg(feature = "parser-rust")]
("rust", parser_rust::RustParser::spec()),
#[cfg(feature = "parser-ts")]
("ts", parser_ts::TsParser::spec()),
]
.into_iter()
.map(|(label, parser): (&str, Parser)| (label.to_string(), parser))
.collect();
Self { inner }
}
/// List the available parsers
fn list(&self) -> Vec<String> {
self.inner
.keys()
.into_iter()
.cloned()
.collect::<Vec<String>>()
}
/// Get a parser by label
fn get(&self, label: &str) -> Result<Parser> {
match self.inner.get(label) {
Some(parser) => Ok(parser.clone()),
None => bail!("No parser with label `{}`", label),
}
}
/// Parse a code resource
fn parse(&self, resource: Resource, code: &str) -> Result<ResourceInfo> {
let (path, language) = if let Resource::Code(code) = &resource {
(code.path.clone(), code.language.clone().unwrap_or_default())
} else {
bail!("Attempting to parse a resource that is not a `Code` resource")
};
let format = match_name(&language);
let resource_info =
if let Some(result) = dispatch_builtins!(format, parse, resource, &path, code) {
result?
} else {
bail!(
"Unable to parse code in language `{}`: no matching parser found",
language
)
};
Ok(resource_info)
}
}
impl Default for Parsers {
fn default() -> Self {
Self::new()
}
}
#[cfg(feature = "cli")]
pub mod commands {
use std::{fs, path::PathBuf};
use super::*;
use cli_utils::{async_trait::async_trait, result, Result, Run};
use parser::graph_triples::resources;
use structopt::StructOpt;
#[derive(Debug, StructOpt)]
#[structopt(
about = "Manage and use parsers",
setting = structopt::clap::AppSettings::ColoredHelp,
setting = structopt::clap::AppSettings::VersionlessSubcommands
)]
pub struct Command {
#[structopt(subcommand)]
pub action: Action,
}
#[derive(Debug, StructOpt)]
#[structopt(
setting = structopt::clap::AppSettings::DeriveDisplayOrder
)]
pub enum Action {
List(List),
Show(Show),
Parse(Parse),
}
#[async_trait]
impl Run for Command {
async fn run(&self) -> Result {
let Self { action } = self;
match action {
Action::List(action) => action.run().await,
Action::Show(action) => action.run().await,
Action::Parse(action) => action.run().await,
}
}
}
/// List the parsers that are available
///
/// The list of available parsers includes those that are built into the Stencila
/// binary as well as any parsers provided by plugins.
#[derive(Debug, StructOpt)]
#[structopt(
setting = structopt::clap::AppSettings::ColoredHelp
)]
pub struct
|
{}
#[async_trait]
impl Run for List {
async fn run(&self) -> Result {
let list = PARSERS.list();
result::value(list)
}
}
/// Show the specifications of a parser
#[derive(Debug, StructOpt)]
#[structopt(
setting = structopt::clap::AppSettings::ColoredHelp
)]
pub struct Show {
/// The label of the parser
///
/// To get the list of parser labels use `stencila parsers list`.
label: String,
}
#[async_trait]
impl Run for Show {
async fn run(&self) -> Result {
let parser = PARSERS.get(&self.label)?;
result::value(parser)
}
}
/// Parse some code using a parser
///
/// The code is parsed into a set of graph `Relation`/`Resource` pairs using the
/// parser that matches the filename extension (or specified using `--lang`).
/// Useful for testing Stencila's static code analysis for a particular language.
#[derive(Debug, StructOpt)]
#[structopt(
setting = structopt::clap::AppSettings::ColoredHelp
)]
pub struct Parse {
/// The file (or code) to parse
#[structopt(multiple = true)]
code: Vec<String>,
/// If the argument should be treated as text, rather than a file path
#[structopt(short, long)]
text: bool,
/// The language of the code
#[structopt(short, long)]
lang: Option<String>,
}
#[async_trait]
impl Run for Parse {
async fn run(&self) -> Result {
let (path, code, lang) = if self.text || self.code.len() > 1 {
let code = self.code.join(" ");
(
"<text>".to_string(),
code,
self.lang.clone().unwrap_or_default(),
)
} else {
let file = self.code[0].clone();
let code = fs::read_to_string(&file)?;
let ext = PathBuf::from(&file)
.extension()
.map(|ext| ext.to_string_lossy().to_string())
.unwrap_or_default();
let lang = self.lang.clone().or(Some(ext)).unwrap_or_default();
(file, code, lang)
};
let path = PathBuf::from(path);
let resource = resources::code(&path, "<id>", "<cli>", Some(lang));
let resource_info = PARSERS.parse(resource, &code)?;
result::value(resource_info)
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use parser::graph_triples::{relations, resources};
use std::path::PathBuf;
use test_utils::assert_json_eq;
#[test]
#[cfg(feature = "parser-calc")]
fn test_parse() -> Result<()> {
let path = PathBuf::from("<test>");
let resource = resources::code(&path, "<id>", "<cli>", Some("Calc".to_string()));
let resource_info = parse(resource, "a = 1\nb = a * a")?;
assert!(matches!(resource_info.execute_pure, None));
assert!(!resource_info.is_pure());
assert_json_eq!(
resource_info.relations,
vec![
(
relations::assigns((0, 0, 0, 1)),
resources::symbol(&path, "a", "Number")
),
(
relations::assigns((1, 0, 1, 1)),
resources::symbol(&path, "b", "Number")
),
(
relations::uses((1, 4, 1, 5)),
resources::symbol(&path, "a", "Number")
),
(
relations::uses((1, 8, 1, 9)),
resources::symbol(&path, "a", "Number")
)
]
);
Ok(())
}
}
|
List
|
identifier_name
|
lib.rs
|
use formats::{match_name, Format};
use once_cell::sync::Lazy;
use parser::{
eyre::{bail, Result},
graph_triples::{Resource, ResourceInfo},
ParserTrait,
};
use std::collections::BTreeMap;
use std::sync::Arc;
// Re-exports
pub use parser::Parser;
// The following high level functions hide the implementation
// detail of having a static list of parsers. They are intended as the
// only public interface for this crate.
pub fn parse(resource: Resource, code: &str) -> Result<ResourceInfo> {
PARSERS.parse(resource, code)
}
/// The set of registered parsers in the current process
static PARSERS: Lazy<Arc<Parsers>> = Lazy::new(|| Arc::new(Parsers::new()));
/// A set of registered parsers, either built-in, or provided by plugins
struct Parsers {
inner: BTreeMap<String, Parser>,
}
/// A macro to dispatch methods to builtin parsers
///
/// This avoids having to do a search over the parsers's specs for matching `languages`.
macro_rules! dispatch_builtins {
($format:expr, $method:ident $(,$arg:expr)*) => {
match $format {
#[cfg(feature = "parser-bash")]
Format::Bash | Format::Shell | Format::Zsh => Some(parser_bash::BashParser::$method($($arg),*)),
#[cfg(feature = "parser-calc")]
Format::Calc => Some(parser_calc::CalcParser::$method($($arg),*)),
#[cfg(feature = "parser-js")]
Format::JavaScript => Some(parser_js::JsParser::$method($($arg),*)),
#[cfg(feature = "parser-py")]
Format::Python => Some(parser_py::PyParser::$method($($arg),*)),
#[cfg(feature = "parser-r")]
Format::R => Some(parser_r::RParser::$method($($arg),*)),
#[cfg(feature = "parser-rust")]
Format::Rust => Some(parser_rust::RustParser::$method($($arg),*)),
#[cfg(feature = "parser-ts")]
Format::TypeScript => Some(parser_ts::TsParser::$method($($arg),*)),
// Fallback to empty result
_ => Option::<Result<ResourceInfo>>::None
}
};
}
impl Parsers {
/// Create a set of parsers
///
/// Note that these strings are labels for the parser which
/// aim to be consistent with the parser name, are convenient
/// to use to `stencila parsers show`, and don't need to be
/// consistent with format names or aliases.
pub fn new() -> Self {
let inner = vec![
#[cfg(feature = "parser-bash")]
("bash", parser_bash::BashParser::spec()),
#[cfg(feature = "parser-calc")]
("calc", parser_calc::CalcParser::spec()),
#[cfg(feature = "parser-js")]
("js", parser_js::JsParser::spec()),
#[cfg(feature = "parser-py")]
("py", parser_py::PyParser::spec()),
#[cfg(feature = "parser-r")]
("r", parser_r::RParser::spec()),
#[cfg(feature = "parser-rust")]
("rust", parser_rust::RustParser::spec()),
#[cfg(feature = "parser-ts")]
("ts", parser_ts::TsParser::spec()),
]
.into_iter()
.map(|(label, parser): (&str, Parser)| (label.to_string(), parser))
.collect();
Self { inner }
}
/// List the available parsers
fn list(&self) -> Vec<String> {
self.inner
.keys()
.into_iter()
.cloned()
.collect::<Vec<String>>()
}
/// Get a parser by label
fn get(&self, label: &str) -> Result<Parser> {
match self.inner.get(label) {
Some(parser) => Ok(parser.clone()),
None => bail!("No parser with label `{}`", label),
}
}
/// Parse a code resource
fn parse(&self, resource: Resource, code: &str) -> Result<ResourceInfo> {
let (path, language) = if let Resource::Code(code) = &resource
|
else {
bail!("Attempting to parse a resource that is not a `Code` resource")
};
let format = match_name(&language);
let resource_info =
if let Some(result) = dispatch_builtins!(format, parse, resource, &path, code) {
result?
} else {
bail!(
"Unable to parse code in language `{}`: no matching parser found",
language
)
};
Ok(resource_info)
}
}
impl Default for Parsers {
fn default() -> Self {
Self::new()
}
}
#[cfg(feature = "cli")]
pub mod commands {
use std::{fs, path::PathBuf};
use super::*;
use cli_utils::{async_trait::async_trait, result, Result, Run};
use parser::graph_triples::resources;
use structopt::StructOpt;
#[derive(Debug, StructOpt)]
#[structopt(
about = "Manage and use parsers",
setting = structopt::clap::AppSettings::ColoredHelp,
setting = structopt::clap::AppSettings::VersionlessSubcommands
)]
pub struct Command {
#[structopt(subcommand)]
pub action: Action,
}
#[derive(Debug, StructOpt)]
#[structopt(
setting = structopt::clap::AppSettings::DeriveDisplayOrder
)]
pub enum Action {
List(List),
Show(Show),
Parse(Parse),
}
#[async_trait]
impl Run for Command {
async fn run(&self) -> Result {
let Self { action } = self;
match action {
Action::List(action) => action.run().await,
Action::Show(action) => action.run().await,
Action::Parse(action) => action.run().await,
}
}
}
/// List the parsers that are available
///
/// The list of available parsers includes those that are built into the Stencila
/// binary as well as any parsers provided by plugins.
#[derive(Debug, StructOpt)]
#[structopt(
setting = structopt::clap::AppSettings::ColoredHelp
)]
pub struct List {}
#[async_trait]
impl Run for List {
async fn run(&self) -> Result {
let list = PARSERS.list();
result::value(list)
}
}
/// Show the specifications of a parser
#[derive(Debug, StructOpt)]
#[structopt(
setting = structopt::clap::AppSettings::ColoredHelp
)]
pub struct Show {
/// The label of the parser
///
/// To get the list of parser labels use `stencila parsers list`.
label: String,
}
#[async_trait]
impl Run for Show {
async fn run(&self) -> Result {
let parser = PARSERS.get(&self.label)?;
result::value(parser)
}
}
/// Parse some code using a parser
///
/// The code is parsed into a set of graph `Relation`/`Resource` pairs using the
/// parser that matches the filename extension (or specified using `--lang`).
/// Useful for testing Stencila's static code analysis for a particular language.
#[derive(Debug, StructOpt)]
#[structopt(
setting = structopt::clap::AppSettings::ColoredHelp
)]
pub struct Parse {
/// The file (or code) to parse
#[structopt(multiple = true)]
code: Vec<String>,
/// If the argument should be treated as text, rather than a file path
#[structopt(short, long)]
text: bool,
/// The language of the code
#[structopt(short, long)]
lang: Option<String>,
}
#[async_trait]
impl Run for Parse {
async fn run(&self) -> Result {
let (path, code, lang) = if self.text || self.code.len() > 1 {
let code = self.code.join(" ");
(
"<text>".to_string(),
code,
self.lang.clone().unwrap_or_default(),
)
} else {
let file = self.code[0].clone();
let code = fs::read_to_string(&file)?;
let ext = PathBuf::from(&file)
.extension()
.map(|ext| ext.to_string_lossy().to_string())
.unwrap_or_default();
let lang = self.lang.clone().or(Some(ext)).unwrap_or_default();
(file, code, lang)
};
let path = PathBuf::from(path);
let resource = resources::code(&path, "<id>", "<cli>", Some(lang));
let resource_info = PARSERS.parse(resource, &code)?;
result::value(resource_info)
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use parser::graph_triples::{relations, resources};
use std::path::PathBuf;
use test_utils::assert_json_eq;
#[test]
#[cfg(feature = "parser-calc")]
fn test_parse() -> Result<()> {
let path = PathBuf::from("<test>");
let resource = resources::code(&path, "<id>", "<cli>", Some("Calc".to_string()));
let resource_info = parse(resource, "a = 1\nb = a * a")?;
assert!(matches!(resource_info.execute_pure, None));
assert!(!resource_info.is_pure());
assert_json_eq!(
resource_info.relations,
vec![
(
relations::assigns((0, 0, 0, 1)),
resources::symbol(&path, "a", "Number")
),
(
relations::assigns((1, 0, 1, 1)),
resources::symbol(&path, "b", "Number")
),
(
relations::uses((1, 4, 1, 5)),
resources::symbol(&path, "a", "Number")
),
(
relations::uses((1, 8, 1, 9)),
resources::symbol(&path, "a", "Number")
)
]
);
Ok(())
}
}
|
{
(code.path.clone(), code.language.clone().unwrap_or_default())
}
|
conditional_block
|
comment.rs
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
use crate::dom::bindings::codegen::Bindings::WindowBinding::WindowMethods;
use crate::dom::bindings::error::Fallible;
use crate::dom::bindings::root::DomRoot;
use crate::dom::bindings::str::DOMString;
use crate::dom::characterdata::CharacterData;
use crate::dom::document::Document;
use crate::dom::node::Node;
use crate::dom::window::Window;
use dom_struct::dom_struct;
/// An HTML comment.
#[dom_struct]
pub struct Comment {
characterdata: CharacterData,
}
impl Comment {
fn new_inherited(text: DOMString, document: &Document) -> Comment {
Comment {
characterdata: CharacterData::new_inherited(text, document),
}
}
pub fn new(text: DOMString, document: &Document) -> DomRoot<Comment> {
Node::reflect_node(
Box::new(Comment::new_inherited(text, document)),
document,
CommentBinding::Wrap,
)
}
pub fn Constructor(window: &Window, data: DOMString) -> Fallible<DomRoot<Comment>> {
let document = window.Document();
Ok(Comment::new(data, &document))
}
}
|
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use crate::dom::bindings::codegen::Bindings::CommentBinding;
|
random_line_split
|
comment.rs
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use crate::dom::bindings::codegen::Bindings::CommentBinding;
use crate::dom::bindings::codegen::Bindings::WindowBinding::WindowMethods;
use crate::dom::bindings::error::Fallible;
use crate::dom::bindings::root::DomRoot;
use crate::dom::bindings::str::DOMString;
use crate::dom::characterdata::CharacterData;
use crate::dom::document::Document;
use crate::dom::node::Node;
use crate::dom::window::Window;
use dom_struct::dom_struct;
/// An HTML comment.
#[dom_struct]
pub struct Comment {
characterdata: CharacterData,
}
impl Comment {
fn new_inherited(text: DOMString, document: &Document) -> Comment {
Comment {
characterdata: CharacterData::new_inherited(text, document),
}
}
pub fn
|
(text: DOMString, document: &Document) -> DomRoot<Comment> {
Node::reflect_node(
Box::new(Comment::new_inherited(text, document)),
document,
CommentBinding::Wrap,
)
}
pub fn Constructor(window: &Window, data: DOMString) -> Fallible<DomRoot<Comment>> {
let document = window.Document();
Ok(Comment::new(data, &document))
}
}
|
new
|
identifier_name
|
craft_output_metadata.rs
|
use rustc_serialize::{Encodable, Encoder};
use ops;
use package::Package;
use package_id::PackageId;
use resolver::Resolve;
use util::CraftResult;
use workspace::Workspace;
const VERSION: u32 = 1;
pub struct OutputMetadataOptions {
pub features: Vec<String>,
pub no_default_features: bool,
pub all_features: bool,
pub no_deps: bool,
pub version: u32,
}
/// Loads the manifest, resolves the dependencies of the project to the concrete
/// used versions - considering overrides - and writes all dependencies in a JSON
/// format to stdout.
pub fn output_metadata(ws: &Workspace, opt: &OutputMetadataOptions) -> CraftResult<ExportInfo> {
if opt.version!= VERSION {
bail!("metadata version {} not supported, only {} is currently supported",
opt.version,
VERSION);
}
if opt.no_deps {
metadata_no_deps(ws, opt)
} else {
metadata_full(ws, opt)
}
}
fn metadata_no_deps(ws: &Workspace, _opt: &OutputMetadataOptions) -> CraftResult<ExportInfo> {
Ok(ExportInfo {
packages: ws.members().cloned().collect(),
workspace_members: ws.members().map(|pkg| pkg.package_id().clone()).collect(),
resolve: None,
version: VERSION,
})
}
fn metadata_full(ws: &Workspace, opt: &OutputMetadataOptions) -> CraftResult<ExportInfo> {
let deps = ops::resolve_dependencies(ws,
None,
&opt.features,
opt.all_features,
opt.no_default_features,
&[])?;
let (packages, resolve) = deps;
let packages = try!(packages.package_ids()
.map(|i| packages.get(i).map(|p| p.clone()))
.collect());
Ok(ExportInfo {
packages: packages,
workspace_members: ws.members().map(|pkg| pkg.package_id().clone()).collect(),
resolve: Some(MetadataResolve {
resolve: resolve,
root: ws.current_opt().map(|pkg| pkg.package_id().clone()),
}),
version: VERSION,
})
}
#[derive(RustcEncodable)]
pub struct ExportInfo {
packages: Vec<Package>,
workspace_members: Vec<PackageId>,
resolve: Option<MetadataResolve>,
version: u32,
}
/// Newtype wrapper to provide a custom `Encodable` implementation.
/// The one from lockfile does not fit because it uses a non-standard
/// format for `PackageId`s
struct MetadataResolve {
resolve: Resolve,
root: Option<PackageId>,
}
impl Encodable for MetadataResolve {
fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
#[derive(RustcEncodable)]
struct EncodableResolve<'a> {
root: Option<&'a PackageId>,
nodes: Vec<Node<'a>>,
}
#[derive(RustcEncodable)]
struct Node<'a> {
|
}
let encodable = EncodableResolve {
root: self.root.as_ref(),
nodes: self.resolve
.iter()
.map(|id| {
Node {
id: id,
dependencies: self.resolve.deps(id).collect(),
}
})
.collect(),
};
encodable.encode(s)
}
}
|
id: &'a PackageId,
dependencies: Vec<&'a PackageId>,
|
random_line_split
|
craft_output_metadata.rs
|
use rustc_serialize::{Encodable, Encoder};
use ops;
use package::Package;
use package_id::PackageId;
use resolver::Resolve;
use util::CraftResult;
use workspace::Workspace;
const VERSION: u32 = 1;
pub struct OutputMetadataOptions {
pub features: Vec<String>,
pub no_default_features: bool,
pub all_features: bool,
pub no_deps: bool,
pub version: u32,
}
/// Loads the manifest, resolves the dependencies of the project to the concrete
/// used versions - considering overrides - and writes all dependencies in a JSON
/// format to stdout.
pub fn output_metadata(ws: &Workspace, opt: &OutputMetadataOptions) -> CraftResult<ExportInfo> {
if opt.version!= VERSION {
bail!("metadata version {} not supported, only {} is currently supported",
opt.version,
VERSION);
}
if opt.no_deps {
metadata_no_deps(ws, opt)
} else {
metadata_full(ws, opt)
}
}
fn metadata_no_deps(ws: &Workspace, _opt: &OutputMetadataOptions) -> CraftResult<ExportInfo> {
Ok(ExportInfo {
packages: ws.members().cloned().collect(),
workspace_members: ws.members().map(|pkg| pkg.package_id().clone()).collect(),
resolve: None,
version: VERSION,
})
}
fn metadata_full(ws: &Workspace, opt: &OutputMetadataOptions) -> CraftResult<ExportInfo> {
let deps = ops::resolve_dependencies(ws,
None,
&opt.features,
opt.all_features,
opt.no_default_features,
&[])?;
let (packages, resolve) = deps;
let packages = try!(packages.package_ids()
.map(|i| packages.get(i).map(|p| p.clone()))
.collect());
Ok(ExportInfo {
packages: packages,
workspace_members: ws.members().map(|pkg| pkg.package_id().clone()).collect(),
resolve: Some(MetadataResolve {
resolve: resolve,
root: ws.current_opt().map(|pkg| pkg.package_id().clone()),
}),
version: VERSION,
})
}
#[derive(RustcEncodable)]
pub struct ExportInfo {
packages: Vec<Package>,
workspace_members: Vec<PackageId>,
resolve: Option<MetadataResolve>,
version: u32,
}
/// Newtype wrapper to provide a custom `Encodable` implementation.
/// The one from lockfile does not fit because it uses a non-standard
/// format for `PackageId`s
struct MetadataResolve {
resolve: Resolve,
root: Option<PackageId>,
}
impl Encodable for MetadataResolve {
fn
|
<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
#[derive(RustcEncodable)]
struct EncodableResolve<'a> {
root: Option<&'a PackageId>,
nodes: Vec<Node<'a>>,
}
#[derive(RustcEncodable)]
struct Node<'a> {
id: &'a PackageId,
dependencies: Vec<&'a PackageId>,
}
let encodable = EncodableResolve {
root: self.root.as_ref(),
nodes: self.resolve
.iter()
.map(|id| {
Node {
id: id,
dependencies: self.resolve.deps(id).collect(),
}
})
.collect(),
};
encodable.encode(s)
}
}
|
encode
|
identifier_name
|
craft_output_metadata.rs
|
use rustc_serialize::{Encodable, Encoder};
use ops;
use package::Package;
use package_id::PackageId;
use resolver::Resolve;
use util::CraftResult;
use workspace::Workspace;
const VERSION: u32 = 1;
pub struct OutputMetadataOptions {
pub features: Vec<String>,
pub no_default_features: bool,
pub all_features: bool,
pub no_deps: bool,
pub version: u32,
}
/// Loads the manifest, resolves the dependencies of the project to the concrete
/// used versions - considering overrides - and writes all dependencies in a JSON
/// format to stdout.
pub fn output_metadata(ws: &Workspace, opt: &OutputMetadataOptions) -> CraftResult<ExportInfo> {
if opt.version!= VERSION
|
if opt.no_deps {
metadata_no_deps(ws, opt)
} else {
metadata_full(ws, opt)
}
}
fn metadata_no_deps(ws: &Workspace, _opt: &OutputMetadataOptions) -> CraftResult<ExportInfo> {
Ok(ExportInfo {
packages: ws.members().cloned().collect(),
workspace_members: ws.members().map(|pkg| pkg.package_id().clone()).collect(),
resolve: None,
version: VERSION,
})
}
fn metadata_full(ws: &Workspace, opt: &OutputMetadataOptions) -> CraftResult<ExportInfo> {
let deps = ops::resolve_dependencies(ws,
None,
&opt.features,
opt.all_features,
opt.no_default_features,
&[])?;
let (packages, resolve) = deps;
let packages = try!(packages.package_ids()
.map(|i| packages.get(i).map(|p| p.clone()))
.collect());
Ok(ExportInfo {
packages: packages,
workspace_members: ws.members().map(|pkg| pkg.package_id().clone()).collect(),
resolve: Some(MetadataResolve {
resolve: resolve,
root: ws.current_opt().map(|pkg| pkg.package_id().clone()),
}),
version: VERSION,
})
}
#[derive(RustcEncodable)]
pub struct ExportInfo {
packages: Vec<Package>,
workspace_members: Vec<PackageId>,
resolve: Option<MetadataResolve>,
version: u32,
}
/// Newtype wrapper to provide a custom `Encodable` implementation.
/// The one from lockfile does not fit because it uses a non-standard
/// format for `PackageId`s
struct MetadataResolve {
resolve: Resolve,
root: Option<PackageId>,
}
impl Encodable for MetadataResolve {
fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
#[derive(RustcEncodable)]
struct EncodableResolve<'a> {
root: Option<&'a PackageId>,
nodes: Vec<Node<'a>>,
}
#[derive(RustcEncodable)]
struct Node<'a> {
id: &'a PackageId,
dependencies: Vec<&'a PackageId>,
}
let encodable = EncodableResolve {
root: self.root.as_ref(),
nodes: self.resolve
.iter()
.map(|id| {
Node {
id: id,
dependencies: self.resolve.deps(id).collect(),
}
})
.collect(),
};
encodable.encode(s)
}
}
|
{
bail!("metadata version {} not supported, only {} is currently supported",
opt.version,
VERSION);
}
|
conditional_block
|
p065.rs
|
//! [Problem 65](https://projecteuler.net/problem=65) solver.
#![warn(
bad_style,
unused,
unused_extern_crates,
unused_import_braces,
unused_qualifications,
unused_results
)]
use num_bigint::BigUint;
fn
|
(i: u32) -> u32 {
match i {
0 => 2,
i if i % 3 == 2 => 2 * (i + 1) / 3,
_ => 1,
}
}
fn solve() -> String {
let len = 100;
let napier = (0u32..len).map(napier_seq);
let (n, _d) = cont_frac::fold::<BigUint, _>(napier);
n.to_string()
.chars()
.filter_map(|c| c.to_digit(10))
.sum::<u32>()
.to_string()
}
common::problem!("272", solve);
|
napier_seq
|
identifier_name
|
p065.rs
|
//! [Problem 65](https://projecteuler.net/problem=65) solver.
#![warn(
bad_style,
unused,
unused_extern_crates,
unused_import_braces,
unused_qualifications,
unused_results
)]
use num_bigint::BigUint;
fn napier_seq(i: u32) -> u32 {
match i {
0 => 2,
i if i % 3 == 2 => 2 * (i + 1) / 3,
_ => 1,
}
}
fn solve() -> String {
let len = 100;
let napier = (0u32..len).map(napier_seq);
let (n, _d) = cont_frac::fold::<BigUint, _>(napier);
n.to_string()
.chars()
.filter_map(|c| c.to_digit(10))
|
.to_string()
}
common::problem!("272", solve);
|
.sum::<u32>()
|
random_line_split
|
p065.rs
|
//! [Problem 65](https://projecteuler.net/problem=65) solver.
#![warn(
bad_style,
unused,
unused_extern_crates,
unused_import_braces,
unused_qualifications,
unused_results
)]
use num_bigint::BigUint;
fn napier_seq(i: u32) -> u32 {
match i {
0 => 2,
i if i % 3 == 2 => 2 * (i + 1) / 3,
_ => 1,
}
}
fn solve() -> String
|
common::problem!("272", solve);
|
{
let len = 100;
let napier = (0u32..len).map(napier_seq);
let (n, _d) = cont_frac::fold::<BigUint, _>(napier);
n.to_string()
.chars()
.filter_map(|c| c.to_digit(10))
.sum::<u32>()
.to_string()
}
|
identifier_body
|
source.rs
|
use std::ffi::{OsStr};
use std::path::{Path};
use clang::*;
use clang::source::*;
pub fn test(clang: &Clang) {
// File ______________________________________
super::with_file(&clang, "int a = 322;", |_, f| {
#[cfg(feature="clang_6_0")]
fn test_get_contents(file: &File) {
assert_eq!(file.get_contents(), Some("int a = 322;".into()));
}
#[cfg(not(feature="clang_6_0"))]
fn test_get_contents(_: &File) { }
test_get_contents(&f);
});
super::with_file(&clang, "int a = 322;", |p, f| {
assert_eq!(f.get_path(), p.to_path_buf());
assert!(f.get_time()!= 0);
super::with_file(&clang, "int a = 322;", |_, g| assert!(f.get_id()!= g.get_id()));
assert_eq!(f.get_skipped_ranges(), &[]);
assert!(!f.is_include_guarded());
});
let source = "
#if 0
int skipped = 32;
#endif
int unskipped = 32;
";
super::with_temporary_file("test.cpp", source, |_, f| {
let index = Index::new(&clang, false, false);
let tu = index.parser(f).detailed_preprocessing_record(true).parse().unwrap();
#[cfg(feature="clang_4_0")]
fn test_get_skipped_ranges<'tu>(tu: TranslationUnit<'tu>, f: &Path) {
let file = tu.get_file(f).unwrap();
if cfg!(feature="clang_6_0") {
assert_eq!(tu.get_skipped_ranges(), &[range!(file, 2, 9, 4, 15)]);
assert_eq!(file.get_skipped_ranges(), &[range!(file, 2, 9, 4, 15)]);
} else
|
}
#[cfg(not(feature="clang_4_0"))]
fn test_get_skipped_ranges<'tu>(tu: TranslationUnit<'tu>, f: &Path) {
let file = tu.get_file(f).unwrap();
assert_eq!(file.get_skipped_ranges(), &[range!(file, 2, 10, 4, 15)]);
}
test_get_skipped_ranges(tu, f);
});
super::with_file(&clang, "#ifndef _TEST_H_\n#define _TEST_H_\nint a = 322;\n#endif", |_, f| {
assert!(f.is_include_guarded());
});
let source = r#"
void f() {
int a = 2 + 2;
double b = 0.25 * 2.0;
const char* c = "Hello, world!";
}
"#;
super::with_temporary_file("test.cpp", source, |_, f| {
let index = Index::new(&clang, false, false);
let tu = index.parser(f).detailed_preprocessing_record(true).parse().unwrap();
let tukids = tu.get_entity().get_children();
let child = tukids.first().unwrap();
// This may fail, if clang internals DO have a source
let file = child.get_location().unwrap().get_file_location().file;
assert_eq!(file, None);
});
// Module ____________________________________
let files = &[
("module.modulemap", "module parent { module child [system] { header \"test.hpp\" } }"),
("test.hpp", ""),
("test.cpp", "#include \"test.hpp\""),
];
super::with_temporary_files(files, |_, fs| {
// Fails with clang 3.5 on Travis CI for some reason...
if cfg!(feature="clang_3_6") {
let index = Index::new(&clang, false, false);
let tu = index.parser(&fs[2]).arguments(&["-fmodules"]).parse().unwrap();
let module = tu.get_file(&fs[1]).unwrap().get_module().unwrap();
assert_eq!(module.get_file().get_path().extension(), Some(OsStr::new("pcm")));
assert_eq!(module.get_full_name(), "parent.child");
assert_eq!(module.get_name(), "child");
assert_eq!(module.get_top_level_headers(), &[tu.get_file(&fs[1]).unwrap()]);
assert!(module.is_system());
let module = module.get_parent().unwrap();
assert_eq!(module.get_file().get_path().extension(), Some(OsStr::new("pcm")));
assert_eq!(module.get_full_name(), "parent");
assert_eq!(module.get_name(), "parent");
assert_eq!(module.get_parent(), None);
assert_eq!(module.get_top_level_headers(), &[]);
assert!(!module.is_system());
}
});
// SourceLocation ____________________________
let source = "
#define ADD(LEFT, RIGHT) (LEFT + RIGHT)
#line 322 \"presumed.hpp\"
int add(int left, int right) { return ADD(left, right); }
";
super::with_file(&clang, source, |_, f| {
let location = f.get_location(3, 51);
assert_location_eq!(location.get_expansion_location(), Some(f), 3, 33, 81);
assert_location_eq!(location.get_file_location(), Some(f), 3, 33, 81);
assert_eq!(location.get_presumed_location(), ("presumed.hpp".into(), 321, 33));
assert_location_eq!(location.get_spelling_location(), Some(f), 3, 33, 81);
assert!(location.is_in_main_file());
assert!(!location.is_in_system_header());
});
// SourceRange _______________________________
super::with_file(&clang, "int a = 322;", |_, f| {
let range = range!(f, 1, 5, 1, 6);
assert_location_eq!(range.get_start().get_spelling_location(), Some(f), 1, 5, 4);
assert_location_eq!(range.get_end().get_spelling_location(), Some(f), 1, 6, 5);
});
}
|
{
assert_eq!(tu.get_skipped_ranges(), &[range!(file, 2, 10, 4, 15)]);
assert_eq!(file.get_skipped_ranges(), &[range!(file, 2, 10, 4, 15)]);
}
|
conditional_block
|
source.rs
|
use std::ffi::{OsStr};
use std::path::{Path};
use clang::*;
use clang::source::*;
pub fn test(clang: &Clang) {
// File ______________________________________
super::with_file(&clang, "int a = 322;", |_, f| {
#[cfg(feature="clang_6_0")]
fn test_get_contents(file: &File) {
assert_eq!(file.get_contents(), Some("int a = 322;".into()));
}
#[cfg(not(feature="clang_6_0"))]
fn test_get_contents(_: &File) { }
test_get_contents(&f);
});
super::with_file(&clang, "int a = 322;", |p, f| {
assert_eq!(f.get_path(), p.to_path_buf());
assert!(f.get_time()!= 0);
super::with_file(&clang, "int a = 322;", |_, g| assert!(f.get_id()!= g.get_id()));
assert_eq!(f.get_skipped_ranges(), &[]);
assert!(!f.is_include_guarded());
});
let source = "
#if 0
int skipped = 32;
#endif
int unskipped = 32;
";
super::with_temporary_file("test.cpp", source, |_, f| {
let index = Index::new(&clang, false, false);
let tu = index.parser(f).detailed_preprocessing_record(true).parse().unwrap();
#[cfg(feature="clang_4_0")]
fn test_get_skipped_ranges<'tu>(tu: TranslationUnit<'tu>, f: &Path) {
let file = tu.get_file(f).unwrap();
if cfg!(feature="clang_6_0") {
assert_eq!(tu.get_skipped_ranges(), &[range!(file, 2, 9, 4, 15)]);
assert_eq!(file.get_skipped_ranges(), &[range!(file, 2, 9, 4, 15)]);
} else {
assert_eq!(tu.get_skipped_ranges(), &[range!(file, 2, 10, 4, 15)]);
assert_eq!(file.get_skipped_ranges(), &[range!(file, 2, 10, 4, 15)]);
}
}
#[cfg(not(feature="clang_4_0"))]
fn test_get_skipped_ranges<'tu>(tu: TranslationUnit<'tu>, f: &Path)
|
test_get_skipped_ranges(tu, f);
});
super::with_file(&clang, "#ifndef _TEST_H_\n#define _TEST_H_\nint a = 322;\n#endif", |_, f| {
assert!(f.is_include_guarded());
});
let source = r#"
void f() {
int a = 2 + 2;
double b = 0.25 * 2.0;
const char* c = "Hello, world!";
}
"#;
super::with_temporary_file("test.cpp", source, |_, f| {
let index = Index::new(&clang, false, false);
let tu = index.parser(f).detailed_preprocessing_record(true).parse().unwrap();
let tukids = tu.get_entity().get_children();
let child = tukids.first().unwrap();
// This may fail, if clang internals DO have a source
let file = child.get_location().unwrap().get_file_location().file;
assert_eq!(file, None);
});
// Module ____________________________________
let files = &[
("module.modulemap", "module parent { module child [system] { header \"test.hpp\" } }"),
("test.hpp", ""),
("test.cpp", "#include \"test.hpp\""),
];
super::with_temporary_files(files, |_, fs| {
// Fails with clang 3.5 on Travis CI for some reason...
if cfg!(feature="clang_3_6") {
let index = Index::new(&clang, false, false);
let tu = index.parser(&fs[2]).arguments(&["-fmodules"]).parse().unwrap();
let module = tu.get_file(&fs[1]).unwrap().get_module().unwrap();
assert_eq!(module.get_file().get_path().extension(), Some(OsStr::new("pcm")));
assert_eq!(module.get_full_name(), "parent.child");
assert_eq!(module.get_name(), "child");
assert_eq!(module.get_top_level_headers(), &[tu.get_file(&fs[1]).unwrap()]);
assert!(module.is_system());
let module = module.get_parent().unwrap();
assert_eq!(module.get_file().get_path().extension(), Some(OsStr::new("pcm")));
assert_eq!(module.get_full_name(), "parent");
assert_eq!(module.get_name(), "parent");
assert_eq!(module.get_parent(), None);
assert_eq!(module.get_top_level_headers(), &[]);
assert!(!module.is_system());
}
});
// SourceLocation ____________________________
let source = "
#define ADD(LEFT, RIGHT) (LEFT + RIGHT)
#line 322 \"presumed.hpp\"
int add(int left, int right) { return ADD(left, right); }
";
super::with_file(&clang, source, |_, f| {
let location = f.get_location(3, 51);
assert_location_eq!(location.get_expansion_location(), Some(f), 3, 33, 81);
assert_location_eq!(location.get_file_location(), Some(f), 3, 33, 81);
assert_eq!(location.get_presumed_location(), ("presumed.hpp".into(), 321, 33));
assert_location_eq!(location.get_spelling_location(), Some(f), 3, 33, 81);
assert!(location.is_in_main_file());
assert!(!location.is_in_system_header());
});
// SourceRange _______________________________
super::with_file(&clang, "int a = 322;", |_, f| {
let range = range!(f, 1, 5, 1, 6);
assert_location_eq!(range.get_start().get_spelling_location(), Some(f), 1, 5, 4);
assert_location_eq!(range.get_end().get_spelling_location(), Some(f), 1, 6, 5);
});
}
|
{
let file = tu.get_file(f).unwrap();
assert_eq!(file.get_skipped_ranges(), &[range!(file, 2, 10, 4, 15)]);
}
|
identifier_body
|
source.rs
|
use std::ffi::{OsStr};
use std::path::{Path};
use clang::*;
use clang::source::*;
pub fn
|
(clang: &Clang) {
// File ______________________________________
super::with_file(&clang, "int a = 322;", |_, f| {
#[cfg(feature="clang_6_0")]
fn test_get_contents(file: &File) {
assert_eq!(file.get_contents(), Some("int a = 322;".into()));
}
#[cfg(not(feature="clang_6_0"))]
fn test_get_contents(_: &File) { }
test_get_contents(&f);
});
super::with_file(&clang, "int a = 322;", |p, f| {
assert_eq!(f.get_path(), p.to_path_buf());
assert!(f.get_time()!= 0);
super::with_file(&clang, "int a = 322;", |_, g| assert!(f.get_id()!= g.get_id()));
assert_eq!(f.get_skipped_ranges(), &[]);
assert!(!f.is_include_guarded());
});
let source = "
#if 0
int skipped = 32;
#endif
int unskipped = 32;
";
super::with_temporary_file("test.cpp", source, |_, f| {
let index = Index::new(&clang, false, false);
let tu = index.parser(f).detailed_preprocessing_record(true).parse().unwrap();
#[cfg(feature="clang_4_0")]
fn test_get_skipped_ranges<'tu>(tu: TranslationUnit<'tu>, f: &Path) {
let file = tu.get_file(f).unwrap();
if cfg!(feature="clang_6_0") {
assert_eq!(tu.get_skipped_ranges(), &[range!(file, 2, 9, 4, 15)]);
assert_eq!(file.get_skipped_ranges(), &[range!(file, 2, 9, 4, 15)]);
} else {
assert_eq!(tu.get_skipped_ranges(), &[range!(file, 2, 10, 4, 15)]);
assert_eq!(file.get_skipped_ranges(), &[range!(file, 2, 10, 4, 15)]);
}
}
#[cfg(not(feature="clang_4_0"))]
fn test_get_skipped_ranges<'tu>(tu: TranslationUnit<'tu>, f: &Path) {
let file = tu.get_file(f).unwrap();
assert_eq!(file.get_skipped_ranges(), &[range!(file, 2, 10, 4, 15)]);
}
test_get_skipped_ranges(tu, f);
});
super::with_file(&clang, "#ifndef _TEST_H_\n#define _TEST_H_\nint a = 322;\n#endif", |_, f| {
assert!(f.is_include_guarded());
});
let source = r#"
void f() {
int a = 2 + 2;
double b = 0.25 * 2.0;
const char* c = "Hello, world!";
}
"#;
super::with_temporary_file("test.cpp", source, |_, f| {
let index = Index::new(&clang, false, false);
let tu = index.parser(f).detailed_preprocessing_record(true).parse().unwrap();
let tukids = tu.get_entity().get_children();
let child = tukids.first().unwrap();
// This may fail, if clang internals DO have a source
let file = child.get_location().unwrap().get_file_location().file;
assert_eq!(file, None);
});
// Module ____________________________________
let files = &[
("module.modulemap", "module parent { module child [system] { header \"test.hpp\" } }"),
("test.hpp", ""),
("test.cpp", "#include \"test.hpp\""),
];
super::with_temporary_files(files, |_, fs| {
// Fails with clang 3.5 on Travis CI for some reason...
if cfg!(feature="clang_3_6") {
let index = Index::new(&clang, false, false);
let tu = index.parser(&fs[2]).arguments(&["-fmodules"]).parse().unwrap();
let module = tu.get_file(&fs[1]).unwrap().get_module().unwrap();
assert_eq!(module.get_file().get_path().extension(), Some(OsStr::new("pcm")));
assert_eq!(module.get_full_name(), "parent.child");
assert_eq!(module.get_name(), "child");
assert_eq!(module.get_top_level_headers(), &[tu.get_file(&fs[1]).unwrap()]);
assert!(module.is_system());
let module = module.get_parent().unwrap();
assert_eq!(module.get_file().get_path().extension(), Some(OsStr::new("pcm")));
assert_eq!(module.get_full_name(), "parent");
assert_eq!(module.get_name(), "parent");
assert_eq!(module.get_parent(), None);
assert_eq!(module.get_top_level_headers(), &[]);
assert!(!module.is_system());
}
});
// SourceLocation ____________________________
let source = "
#define ADD(LEFT, RIGHT) (LEFT + RIGHT)
#line 322 \"presumed.hpp\"
int add(int left, int right) { return ADD(left, right); }
";
super::with_file(&clang, source, |_, f| {
let location = f.get_location(3, 51);
assert_location_eq!(location.get_expansion_location(), Some(f), 3, 33, 81);
assert_location_eq!(location.get_file_location(), Some(f), 3, 33, 81);
assert_eq!(location.get_presumed_location(), ("presumed.hpp".into(), 321, 33));
assert_location_eq!(location.get_spelling_location(), Some(f), 3, 33, 81);
assert!(location.is_in_main_file());
assert!(!location.is_in_system_header());
});
// SourceRange _______________________________
super::with_file(&clang, "int a = 322;", |_, f| {
let range = range!(f, 1, 5, 1, 6);
assert_location_eq!(range.get_start().get_spelling_location(), Some(f), 1, 5, 4);
assert_location_eq!(range.get_end().get_spelling_location(), Some(f), 1, 6, 5);
});
}
|
test
|
identifier_name
|
source.rs
|
use std::ffi::{OsStr};
use std::path::{Path};
use clang::*;
use clang::source::*;
pub fn test(clang: &Clang) {
// File ______________________________________
super::with_file(&clang, "int a = 322;", |_, f| {
#[cfg(feature="clang_6_0")]
fn test_get_contents(file: &File) {
assert_eq!(file.get_contents(), Some("int a = 322;".into()));
}
#[cfg(not(feature="clang_6_0"))]
fn test_get_contents(_: &File) { }
|
assert!(f.get_time()!= 0);
super::with_file(&clang, "int a = 322;", |_, g| assert!(f.get_id()!= g.get_id()));
assert_eq!(f.get_skipped_ranges(), &[]);
assert!(!f.is_include_guarded());
});
let source = "
#if 0
int skipped = 32;
#endif
int unskipped = 32;
";
super::with_temporary_file("test.cpp", source, |_, f| {
let index = Index::new(&clang, false, false);
let tu = index.parser(f).detailed_preprocessing_record(true).parse().unwrap();
#[cfg(feature="clang_4_0")]
fn test_get_skipped_ranges<'tu>(tu: TranslationUnit<'tu>, f: &Path) {
let file = tu.get_file(f).unwrap();
if cfg!(feature="clang_6_0") {
assert_eq!(tu.get_skipped_ranges(), &[range!(file, 2, 9, 4, 15)]);
assert_eq!(file.get_skipped_ranges(), &[range!(file, 2, 9, 4, 15)]);
} else {
assert_eq!(tu.get_skipped_ranges(), &[range!(file, 2, 10, 4, 15)]);
assert_eq!(file.get_skipped_ranges(), &[range!(file, 2, 10, 4, 15)]);
}
}
#[cfg(not(feature="clang_4_0"))]
fn test_get_skipped_ranges<'tu>(tu: TranslationUnit<'tu>, f: &Path) {
let file = tu.get_file(f).unwrap();
assert_eq!(file.get_skipped_ranges(), &[range!(file, 2, 10, 4, 15)]);
}
test_get_skipped_ranges(tu, f);
});
super::with_file(&clang, "#ifndef _TEST_H_\n#define _TEST_H_\nint a = 322;\n#endif", |_, f| {
assert!(f.is_include_guarded());
});
let source = r#"
void f() {
int a = 2 + 2;
double b = 0.25 * 2.0;
const char* c = "Hello, world!";
}
"#;
super::with_temporary_file("test.cpp", source, |_, f| {
let index = Index::new(&clang, false, false);
let tu = index.parser(f).detailed_preprocessing_record(true).parse().unwrap();
let tukids = tu.get_entity().get_children();
let child = tukids.first().unwrap();
// This may fail, if clang internals DO have a source
let file = child.get_location().unwrap().get_file_location().file;
assert_eq!(file, None);
});
// Module ____________________________________
let files = &[
("module.modulemap", "module parent { module child [system] { header \"test.hpp\" } }"),
("test.hpp", ""),
("test.cpp", "#include \"test.hpp\""),
];
super::with_temporary_files(files, |_, fs| {
// Fails with clang 3.5 on Travis CI for some reason...
if cfg!(feature="clang_3_6") {
let index = Index::new(&clang, false, false);
let tu = index.parser(&fs[2]).arguments(&["-fmodules"]).parse().unwrap();
let module = tu.get_file(&fs[1]).unwrap().get_module().unwrap();
assert_eq!(module.get_file().get_path().extension(), Some(OsStr::new("pcm")));
assert_eq!(module.get_full_name(), "parent.child");
assert_eq!(module.get_name(), "child");
assert_eq!(module.get_top_level_headers(), &[tu.get_file(&fs[1]).unwrap()]);
assert!(module.is_system());
let module = module.get_parent().unwrap();
assert_eq!(module.get_file().get_path().extension(), Some(OsStr::new("pcm")));
assert_eq!(module.get_full_name(), "parent");
assert_eq!(module.get_name(), "parent");
assert_eq!(module.get_parent(), None);
assert_eq!(module.get_top_level_headers(), &[]);
assert!(!module.is_system());
}
});
// SourceLocation ____________________________
let source = "
#define ADD(LEFT, RIGHT) (LEFT + RIGHT)
#line 322 \"presumed.hpp\"
int add(int left, int right) { return ADD(left, right); }
";
super::with_file(&clang, source, |_, f| {
let location = f.get_location(3, 51);
assert_location_eq!(location.get_expansion_location(), Some(f), 3, 33, 81);
assert_location_eq!(location.get_file_location(), Some(f), 3, 33, 81);
assert_eq!(location.get_presumed_location(), ("presumed.hpp".into(), 321, 33));
assert_location_eq!(location.get_spelling_location(), Some(f), 3, 33, 81);
assert!(location.is_in_main_file());
assert!(!location.is_in_system_header());
});
// SourceRange _______________________________
super::with_file(&clang, "int a = 322;", |_, f| {
let range = range!(f, 1, 5, 1, 6);
assert_location_eq!(range.get_start().get_spelling_location(), Some(f), 1, 5, 4);
assert_location_eq!(range.get_end().get_spelling_location(), Some(f), 1, 6, 5);
});
}
|
test_get_contents(&f);
});
super::with_file(&clang, "int a = 322;", |p, f| {
assert_eq!(f.get_path(), p.to_path_buf());
|
random_line_split
|
path.rs
|
use fnv;
use super::Entry;
#[derive(Debug, Clone)]
pub struct Path {
pub src: u32,
pub dst: u32,
pub path: Result<Vec<u32>,PathError>,
}
#[derive(Debug, Clone)]
pub enum PathError {
NoSuchPath,
Terminated(u32)
}
impl Path {
pub fn len(&self) -> Option<usize> {
if let Ok(ref v) = self.path {
Some(v.len()-1)
} else {
None
}
}
pub fn is_empty(&self) -> bool {
if let Ok(ref v) = self.path {
v.len() <= 1
} else {
false
}
}
pub fn print(&self, entries: &fnv::FnvHashMap<u32,Entry>) {
println!("Path from {}\t(\"{}\")", self.src, entries.get(&self.src).unwrap().title);
println!("\t to {}\t(\"{}\") :", self.dst, entries.get(&self.dst).unwrap().title);
match self.path {
Ok(ref v) => for i in v {
|
},
Err(PathError::NoSuchPath) => println!("\tNo such path exists"),
Err(PathError::Terminated(i)) =>
println!("\tSearch expired after {} iterations", i),
}
println!("\tlen = {:?}", self.len());
}
}
|
println!("\t{}:\t\"{}\"", i, entries[i].title);
|
random_line_split
|
path.rs
|
use fnv;
use super::Entry;
#[derive(Debug, Clone)]
pub struct Path {
pub src: u32,
pub dst: u32,
pub path: Result<Vec<u32>,PathError>,
}
#[derive(Debug, Clone)]
pub enum PathError {
NoSuchPath,
Terminated(u32)
}
impl Path {
pub fn len(&self) -> Option<usize> {
if let Ok(ref v) = self.path
|
else {
None
}
}
pub fn is_empty(&self) -> bool {
if let Ok(ref v) = self.path {
v.len() <= 1
} else {
false
}
}
pub fn print(&self, entries: &fnv::FnvHashMap<u32,Entry>) {
println!("Path from {}\t(\"{}\")", self.src, entries.get(&self.src).unwrap().title);
println!("\t to {}\t(\"{}\") :", self.dst, entries.get(&self.dst).unwrap().title);
match self.path {
Ok(ref v) => for i in v {
println!("\t{}:\t\"{}\"", i, entries[i].title);
},
Err(PathError::NoSuchPath) => println!("\tNo such path exists"),
Err(PathError::Terminated(i)) =>
println!("\tSearch expired after {} iterations", i),
}
println!("\tlen = {:?}", self.len());
}
}
|
{
Some(v.len()-1)
}
|
conditional_block
|
path.rs
|
use fnv;
use super::Entry;
#[derive(Debug, Clone)]
pub struct
|
{
pub src: u32,
pub dst: u32,
pub path: Result<Vec<u32>,PathError>,
}
#[derive(Debug, Clone)]
pub enum PathError {
NoSuchPath,
Terminated(u32)
}
impl Path {
pub fn len(&self) -> Option<usize> {
if let Ok(ref v) = self.path {
Some(v.len()-1)
} else {
None
}
}
pub fn is_empty(&self) -> bool {
if let Ok(ref v) = self.path {
v.len() <= 1
} else {
false
}
}
pub fn print(&self, entries: &fnv::FnvHashMap<u32,Entry>) {
println!("Path from {}\t(\"{}\")", self.src, entries.get(&self.src).unwrap().title);
println!("\t to {}\t(\"{}\") :", self.dst, entries.get(&self.dst).unwrap().title);
match self.path {
Ok(ref v) => for i in v {
println!("\t{}:\t\"{}\"", i, entries[i].title);
},
Err(PathError::NoSuchPath) => println!("\tNo such path exists"),
Err(PathError::Terminated(i)) =>
println!("\tSearch expired after {} iterations", i),
}
println!("\tlen = {:?}", self.len());
}
}
|
Path
|
identifier_name
|
matrix.rs
|
use num::{Zero,One};
use num::{Num,Float};
use std::fmt;
use std::ops::{Index,IndexMut,Add,Mul,Div,Sub,Range};
use alg::Vector;
/// Represents a simple `NxM` matrix.
#[derive(Clone,PartialEq,Debug)]
pub struct Matrix<T> {
/// Number of rows (max Y)
pub m: usize,
/// Number of columns (max X)
pub n: usize,
// Inner data. Cols concatenated.
data: Vec<T>,
}
impl <T> Matrix<T> {
/// Creates a new matrix with the given dimensions,
/// initializing each cell with the given functor.
///
/// * `m` is the number of lines (the Y size)
/// * `n` is the number of columns (the X size)
pub fn new<F>(n: usize, m: usize, f: F) -> Self
where F: Fn(usize,usize) -> T
{
let data = (0..n*m).map(|i| (i/m,i%m)).map(|(x,y)| f(x,y)).collect();
Matrix {
m: m,
n: n,
data: data,
}
}
/// Only keeps a subset of consecutive columns indicated
/// by the given range, and discard the rest.
pub fn keep_cols(&mut self, cols: Range<usize>) {
let n_cols = cols.end - cols.start;
let start = cols.start * self.m;
let end = cols.end * self.m;
self.data.truncate(end);
if start > 0 {
self.data = self.data.split_off(start);
}
self.n = n_cols;
}
/// Appends the columnds from the given matrix to this one.
///
/// Panics if the matrices don't have the same height.
pub fn append_cols(&mut self, mut other: Matrix<T>) {
if self.m!= other.m {
panic!("Matrices don't have the same height.");
}
self.n += other.n;
// append is currently unstable. See../lib.rs
self.data.append(&mut other.data);
}
/// Returns the index in the data array corresponding to the given cell.
fn get_index(&self, (x,y): (usize,usize)) -> usize {
y + x * self.m
}
/// Creates a dummy empty matrix.
pub fn dummy() -> Self {
Matrix {
m: 0,
n: 0,
data: Vec::new(),
}
}
/// Returns TRUE if the matrix is square.
pub fn is_square(&self) -> bool {
return self.m == self.n
}
/// Swaps the content from two cells.
pub fn swap(&mut self, a: (usize,usize), b: (usize,usize)) {
let ia = self.get_index(a);
let ib = self.get_index(b);
self.data.swap(ia, ib);
}
/// Swaps the content from two columns.
pub fn swap_cols(&mut self, xa: usize, xb: usize) {
if xa == xb { return; }
for y in 0..self.n {
self.swap((xa,y), (xb,y));
}
}
/// Swaps the content from two rows.
pub fn swap_rows(&mut self, ya: usize, yb: usize) {
if ya == yb { return; }
for x in 0..self.n {
self.swap((x,ya),(x,yb));
}
}
}
impl <T: Zero> Matrix<T> {
/// Creates a new matrix initialized to zero.
pub fn
|
(n: usize, m: usize) -> Self {
Matrix::new(n,m, |_,_| T::zero())
}
}
impl <T: Clone> Matrix<T> {
/// Returns a new Vector, cloned from the given row.
pub fn row(&self, y: usize) -> Vector<T> {
Vector::new(self.n, |i| self[(i,y)].clone())
}
/// Returns a new Vector, cloned from the given column.
pub fn col(&self, x: usize) -> Vector<T> {
Vector::new(self.m, |i| self[(x,i)].clone())
}
/// Sets a column content from the given vector.
pub fn set_col(&mut self, x: usize, col: Vector<T>) {
for (i,v) in col.into_iter().enumerate() {
self[(x,i)] = v;
}
}
/// Sets a row content from the given vector.
pub fn set_row(&mut self, y: usize, row: Vector<T>) {
for (i,v) in row.into_iter().enumerate() {
self[(i,y)] = v;
}
}
/// Create a single-column matrix from the given Vector.
pub fn from_col(v: &Vector<T>) -> Self {
Matrix::new(1, v.dim(), |_,y| v[y].clone())
}
/// Make a matrix from the given vectors, to treat as columns.
pub fn from_cols(cols: &[Vector<T>]) -> Self {
if cols.is_empty() {
Matrix::dummy()
} else {
let n = cols.len();
let m = cols.first().unwrap().dim();
Matrix::new(n, m, |x,y| cols[x][y].clone())
}
}
/// Create a single-row matrix from the given Vector.
pub fn from_row(v: &Vector<T>) -> Self {
Matrix::new(v.dim(), 1, |x,_| v[x].clone())
}
/// Make a matrix from the given vectors, to treas as rows.
pub fn from_rows(rows: &[Vector<T>]) -> Self {
if rows.is_empty() {
Matrix::dummy()
} else {
let m = rows.len();
let n = rows.first().unwrap().dim();
Matrix::new(n, m, |x,y| rows[y][x].clone())
}
}
/// Returns the transposed matrix.
pub fn transpose(&self) -> Matrix<T> {
Matrix::new(self.m, self.n, |x,y| self[(y,x)].clone())
}
/// If this matrix is single-row or single-column,
/// transforms this into a Vector.
pub fn to_vector(self) -> Vector<T> {
if self.n == 1 || self.m == 1 {
Vector::from(self.data)
} else {
panic!("Matrix is not single-row or single-column.");
}
}
}
impl <T: Clone + Zero> Matrix<T> {
/// Creates a new diagonal matrix, with the given vector serving as the diagonal.
pub fn diagonal(vector: Vector<T>) -> Self {
let n = vector.dim();
let mut m = Matrix::zero(n,n);
for (i,x) in vector.into_iter().enumerate() {
m[(i,i)] = x;
}
m
}
/// Creates a new scalar matrix with the given value.
pub fn scalar(n: usize, value: T) -> Self {
Matrix::diagonal(Vector::from_copies(n, value))
}
}
impl <T: Clone + Zero + One> Matrix<T> {
/// Creates a new square identity matrix, with ones on the diagonal.
pub fn identity(n: usize) -> Self {
Matrix::scalar(n, T::one())
}
}
impl <T: Clone + Num> Matrix<T> {
/// Returns the square norm of a matrix: the sum of the square of all cells.
pub fn square_norm(&self) -> T {
self.data.iter().map(|a| a.clone() * a.clone()).fold(T::zero(), |a,b| a+b)
}
/// Returns the matrix determinant.
///
/// Returns zero for non-square and non-invertible matrices.
pub fn determinant(&self) -> T {
if self.m!= self.n { return T::zero(); }
let mut sum = T::zero();
let range: Vec<usize> = (0..self.n).collect();
for sigma in range.permutations() {
// TODO: actually compute the signature!!
// We must multiply by +1 or -1 depending on thepermutation.
sum = sum + sigma.into_iter().enumerate().map(|(i,j)| self[(i,j)].clone()).fold(T::one(), |a,b| a*b);
}
sum
}
/// Returns the inverse of the given matrix, if it is invertible.
pub fn inverse(&self) -> Option<Self> {
self.clone().invert_in_place()
}
/// Consumes the given matrix, and returns its inverse, if it is invertible.
pub fn invert_in_place(mut self) -> Option<Self> {
if!self.is_square() {
panic!("Attempting to invert a non-square matrix.");
}
let n = self.n;
// Waaa matrix inversion is a complex business.
// Let's keep it `simple` with a Gauss-Jordan elimination...
// The idea is: append an Identity matrix to the right (so we have a 2x1 aspect ratio)
// Apply simple linear row operations (permutation, multiplication, addition) until the
// first half is an identity matrix.
// At this point, the second half should be the inverse matrix.
// (Since we apply the inverse of the first half to an identity matrix.)
self.append_cols(Matrix::scalar(n, T::one()));
// For each (original) column...
for k in 0..n {
// Make sure the column is C[i] = i==k? 1 : 0
// Find the perfect candidate: a non-zero element
let j = match (k..n).find(|&i| self[(k,i)]!= T::zero()) {
None => return None,
Some(j) => j,
};
self.swap_rows(j, k);
// Now divide the row by the diagonal value
let pivot = self[(k,k)].clone();
// No need to divide the first k values, they should be zeroes
for x in k..self.n {
self[(x,k)] = self[(x,k)].clone() / pivot.clone();
}
// Finally, zero all other rows
for y in (0..n).filter(|&i| i!= k) {
let value = self[(k,y)].clone();
for x in k..self.n {
self[(x,y)] = self[(x,y)].clone() - value.clone() * self[(x,k)].clone();
}
}
}
// And remove the first half
self.keep_cols(n..2*n);
Some(self)
}
}
impl <T: Clone + Float> Matrix<T> {
/// Returns the triangular matrix from the cholesky decomposition.
pub fn cholesky(&self) -> Self {
self.clone().cholesky_in_place()
}
/// Returns a matrix `L` such that `L * L.transpose() == self`. Assumes that self is symmetric.
pub fn cholesky_in_place(mut self) -> Self {
let n = self.n;
for x in 0..n {
for y in 0..x { self[(x,y)] = T::zero(); }
let sum = (0..x).map(|i| self[(i,x)]).map(|v| v*v).fold(T::zero(), |a,b| a+b);
let ljj = (self[(x,x)] - sum).sqrt();
self[(x,x)] = ljj;
let iv = ljj.recip();
for y in x+1..n {
let sum = (0..x).map(|i| self[(i,x)] * self[(i,y)]).fold(T::zero(), |a,b| a+b);
let lij = (self[(x,y)] - sum) * iv;
self[(x,y)] = lij;
}
}
self
}
}
impl <T: Clone + Mul<Output=T> + Add<Output=T> + Zero> Mul for Matrix<T> {
type Output = Matrix<T>;
fn mul(self, other: Matrix<T>) -> Matrix<T> {
&self * &other
}
}
impl <'a,'b, T: Add<Output=T> + Mul<Output=T> + Zero + Clone> Mul<&'b Matrix<T>> for &'a Matrix<T> {
type Output = Matrix<T>;
fn mul(self, other: &'b Matrix<T>) -> Matrix<T> {
// TODO: might want to make this faster. Parallel? Skip zero values?
Matrix::new(other.n, self.m, |x,y| (0..self.n).map(|i| self[(i,y)].clone() * other[(x,i)].clone()).fold(T::zero(), |a,b|a+b))
}
}
impl <T: Add<Output=T> + Mul<Output=T> + Zero + Clone> Mul<Vector<T>> for Matrix<T> {
type Output = Vector<T>;
fn mul(self, other: Vector<T>) -> Vector<T> {
&self * &other
}
}
impl <'a, T: Add<Output=T> + Mul<Output=T> + Zero + Clone> Mul<Vector<T>> for &'a Matrix<T> {
type Output = Vector<T>;
fn mul(self, other: Vector<T>) -> Vector<T> {
self * &other
}
}
impl <'a,'b, T: Add<Output=T> + Mul<Output=T> + Zero + Clone> Mul<&'b Vector<T>> for &'a Matrix<T> {
type Output = Vector<T>;
fn mul(self, other: &'b Vector<T>) -> Vector<T> {
Vector::new(self.m, |i| (0..self.n).map(|j| self[(j,i)].clone() * other[j].clone()).fold(T::zero(), |a,b| a+b))
}
}
impl <'a, T: Add<Output=T> + Clone> Add for &'a Matrix<T> {
type Output = Matrix<T>;
fn add(self, other: &'a Matrix<T>) -> Matrix<T> {
Matrix::new(self.n, self.m, |x,y| self[(x,y)].clone() + other[(x,y)].clone())
}
}
impl <T: Sub<Output=T> + Clone> Sub for Matrix<T> {
type Output = Matrix<T>;
fn sub(mut self, other: Matrix<T>) -> Matrix<T> {
for (s,o) in self.data.iter_mut().zip(other.data.into_iter()) {
*s = s.clone() - o;
}
self
}
}
impl <'a, T: Sub<Output=T> + Clone> Sub for &'a Matrix<T> {
type Output = Matrix<T>;
fn sub(self, other: &'a Matrix<T>) -> Matrix<T> {
Matrix::new(self.n, self.m, |x,y| self[(x,y)].clone() - other[(x,y)].clone())
}
}
impl <'a, T: Mul<Output=T> + Clone> Mul<T> for &'a Matrix<T> {
type Output = Matrix<T>;
fn mul(self, other: T) -> Matrix<T> {
Matrix::new(self.n, self.m, |x,y| self[(x,y)].clone() * other.clone())
}
}
impl <'a, T: Div<Output=T> + Clone> Div<T> for &'a Matrix<T> {
type Output = Matrix<T>;
fn div(self, other: T) -> Matrix<T> {
Matrix::new(self.n, self.m, |x,y| self[(x,y)].clone() / other.clone())
}
}
impl <T> Index<(usize,usize)> for Matrix<T> {
type Output = T;
fn index(&self, (x,y): (usize,usize)) -> &T {
let i = self.get_index((x,y));
&self.data[i]
}
}
impl <T> IndexMut<(usize,usize)> for Matrix<T> {
fn index_mut(&mut self, (x,y): (usize,usize)) -> &mut T {
let i = self.get_index((x,y));
&mut self.data[i]
}
}
impl <T: fmt::Display> fmt::Display for Matrix<T> {
fn fmt(&self, fmt: &mut fmt::Formatter) -> Result<(),fmt::Error> {
try!(fmt.write_str(&format!("[{} x {}]", self.n, self.m)));
for y in 0..self.m {
try!(fmt.write_str("["));
for x in 0..self.n {
try!(self[(x,y)].fmt(fmt));
try!(fmt.write_str(", "));
}
try!(fmt.write_str("]\n"));
}
Ok(())
}
}
#[test]
fn test_i3() {
let i3 = Matrix::scalar(3, 1);
assert_eq!(i3.n, 3);
assert_eq!(i3.m, 3);
assert_eq!(i3[(0,0)], 1);
assert_eq!(i3[(1,1)], 1);
assert_eq!(i3[(2,2)], 1);
}
#[test]
fn test_add() {
let i3 = Matrix::scalar(3, 1);
let double = &i3 + &i3;
assert_eq!(double, Matrix::scalar(3,2));
}
#[test]
fn test_transpose() {
let v = Vector::new(4, |i| 1+i);
assert_eq!(Matrix::from_row(&v), Matrix::from_col(&v).transpose());
let m = Matrix::new(4,3, |x,y| x+4*y);
let n = Matrix::new(3,4, |x,y| y+4*x);
assert!(m!= n);
assert_eq!(m.transpose().transpose(), m);
assert_eq!(m.transpose(), n);
assert_eq!(n.transpose(), m);
}
#[test]
fn test_transpose_commutation() {
let a = Matrix::new(5,3, |x,y| x+5*y);
let b = Matrix::new(4,5, |x,y| x+y + 2*(x+y)%2);
assert_eq!((&a * &b).transpose(), &b.transpose() * &a.transpose());
}
#[test]
fn test_from_row() {
let v = Vector::new(4, |i| 1+i);
let m = Matrix::new(4,1, |x,_| 1+x);
assert_eq!(Matrix::from_row(&v), m);
assert_eq!(m.to_vector(), v);
}
#[test]
fn test_sub() {
let a = Matrix::new(4,3, |x,y| x+y);
assert_eq!(&a - &a, Matrix::zero(4,3));
}
#[test]
fn test_cols() {
let a = Matrix::new(4,4, |x,y| x+y);
let b = Matrix::new(4,4, |x,y| 8 - (x+y));
let mut c = a.clone();
c.append_cols(b.clone());
c.keep_cols(4..8);
assert_eq!(b, c);
let mut d = b.clone();
d.append_cols(a.clone());
d.keep_cols(4..8);
assert_eq!(a, d);
}
#[test]
fn test_determinant() {
let i5 = Matrix::<f64>::identity(5);
assert_eq!(i5.determinant(), 1f64);
}
#[test]
fn test_inverse() {
let a = Matrix::new(2,2, |x,y| (x+y) as f64);
let b = a.inverse().unwrap();
assert_eq!((&a * &b), Matrix::identity(2));
}
#[test]
fn test_mul() {
let m = Matrix::new(4,4, |x,y| x+y);
let v = Vector::new(4, |i| i+1);
assert_eq!(Matrix::from_col(&(&m * &v)), &m * &Matrix::from_col(&v));
}
|
zero
|
identifier_name
|
matrix.rs
|
use num::{Zero,One};
use num::{Num,Float};
use std::fmt;
use std::ops::{Index,IndexMut,Add,Mul,Div,Sub,Range};
use alg::Vector;
/// Represents a simple `NxM` matrix.
#[derive(Clone,PartialEq,Debug)]
pub struct Matrix<T> {
/// Number of rows (max Y)
pub m: usize,
/// Number of columns (max X)
pub n: usize,
// Inner data. Cols concatenated.
data: Vec<T>,
}
impl <T> Matrix<T> {
/// Creates a new matrix with the given dimensions,
/// initializing each cell with the given functor.
///
/// * `m` is the number of lines (the Y size)
/// * `n` is the number of columns (the X size)
pub fn new<F>(n: usize, m: usize, f: F) -> Self
where F: Fn(usize,usize) -> T
{
let data = (0..n*m).map(|i| (i/m,i%m)).map(|(x,y)| f(x,y)).collect();
Matrix {
m: m,
n: n,
data: data,
}
}
/// Only keeps a subset of consecutive columns indicated
/// by the given range, and discard the rest.
pub fn keep_cols(&mut self, cols: Range<usize>) {
let n_cols = cols.end - cols.start;
let start = cols.start * self.m;
let end = cols.end * self.m;
self.data.truncate(end);
if start > 0 {
self.data = self.data.split_off(start);
}
self.n = n_cols;
}
/// Appends the columnds from the given matrix to this one.
///
/// Panics if the matrices don't have the same height.
pub fn append_cols(&mut self, mut other: Matrix<T>) {
if self.m!= other.m {
panic!("Matrices don't have the same height.");
}
self.n += other.n;
// append is currently unstable. See../lib.rs
self.data.append(&mut other.data);
}
/// Returns the index in the data array corresponding to the given cell.
fn get_index(&self, (x,y): (usize,usize)) -> usize {
y + x * self.m
}
/// Creates a dummy empty matrix.
pub fn dummy() -> Self {
Matrix {
m: 0,
n: 0,
data: Vec::new(),
}
}
/// Returns TRUE if the matrix is square.
pub fn is_square(&self) -> bool {
return self.m == self.n
}
/// Swaps the content from two cells.
pub fn swap(&mut self, a: (usize,usize), b: (usize,usize)) {
let ia = self.get_index(a);
let ib = self.get_index(b);
self.data.swap(ia, ib);
}
/// Swaps the content from two columns.
pub fn swap_cols(&mut self, xa: usize, xb: usize) {
if xa == xb { return; }
for y in 0..self.n {
self.swap((xa,y), (xb,y));
}
}
/// Swaps the content from two rows.
pub fn swap_rows(&mut self, ya: usize, yb: usize) {
if ya == yb
|
for x in 0..self.n {
self.swap((x,ya),(x,yb));
}
}
}
impl <T: Zero> Matrix<T> {
/// Creates a new matrix initialized to zero.
pub fn zero(n: usize, m: usize) -> Self {
Matrix::new(n,m, |_,_| T::zero())
}
}
impl <T: Clone> Matrix<T> {
/// Returns a new Vector, cloned from the given row.
pub fn row(&self, y: usize) -> Vector<T> {
Vector::new(self.n, |i| self[(i,y)].clone())
}
/// Returns a new Vector, cloned from the given column.
pub fn col(&self, x: usize) -> Vector<T> {
Vector::new(self.m, |i| self[(x,i)].clone())
}
/// Sets a column content from the given vector.
pub fn set_col(&mut self, x: usize, col: Vector<T>) {
for (i,v) in col.into_iter().enumerate() {
self[(x,i)] = v;
}
}
/// Sets a row content from the given vector.
pub fn set_row(&mut self, y: usize, row: Vector<T>) {
for (i,v) in row.into_iter().enumerate() {
self[(i,y)] = v;
}
}
/// Create a single-column matrix from the given Vector.
pub fn from_col(v: &Vector<T>) -> Self {
Matrix::new(1, v.dim(), |_,y| v[y].clone())
}
/// Make a matrix from the given vectors, to treat as columns.
pub fn from_cols(cols: &[Vector<T>]) -> Self {
if cols.is_empty() {
Matrix::dummy()
} else {
let n = cols.len();
let m = cols.first().unwrap().dim();
Matrix::new(n, m, |x,y| cols[x][y].clone())
}
}
/// Create a single-row matrix from the given Vector.
pub fn from_row(v: &Vector<T>) -> Self {
Matrix::new(v.dim(), 1, |x,_| v[x].clone())
}
/// Make a matrix from the given vectors, to treas as rows.
pub fn from_rows(rows: &[Vector<T>]) -> Self {
if rows.is_empty() {
Matrix::dummy()
} else {
let m = rows.len();
let n = rows.first().unwrap().dim();
Matrix::new(n, m, |x,y| rows[y][x].clone())
}
}
/// Returns the transposed matrix.
pub fn transpose(&self) -> Matrix<T> {
Matrix::new(self.m, self.n, |x,y| self[(y,x)].clone())
}
/// If this matrix is single-row or single-column,
/// transforms this into a Vector.
pub fn to_vector(self) -> Vector<T> {
if self.n == 1 || self.m == 1 {
Vector::from(self.data)
} else {
panic!("Matrix is not single-row or single-column.");
}
}
}
impl <T: Clone + Zero> Matrix<T> {
/// Creates a new diagonal matrix, with the given vector serving as the diagonal.
pub fn diagonal(vector: Vector<T>) -> Self {
let n = vector.dim();
let mut m = Matrix::zero(n,n);
for (i,x) in vector.into_iter().enumerate() {
m[(i,i)] = x;
}
m
}
/// Creates a new scalar matrix with the given value.
pub fn scalar(n: usize, value: T) -> Self {
Matrix::diagonal(Vector::from_copies(n, value))
}
}
impl <T: Clone + Zero + One> Matrix<T> {
/// Creates a new square identity matrix, with ones on the diagonal.
pub fn identity(n: usize) -> Self {
Matrix::scalar(n, T::one())
}
}
impl <T: Clone + Num> Matrix<T> {
/// Returns the square norm of a matrix: the sum of the square of all cells.
pub fn square_norm(&self) -> T {
self.data.iter().map(|a| a.clone() * a.clone()).fold(T::zero(), |a,b| a+b)
}
/// Returns the matrix determinant.
///
/// Returns zero for non-square and non-invertible matrices.
pub fn determinant(&self) -> T {
if self.m!= self.n { return T::zero(); }
let mut sum = T::zero();
let range: Vec<usize> = (0..self.n).collect();
for sigma in range.permutations() {
// TODO: actually compute the signature!!
// We must multiply by +1 or -1 depending on thepermutation.
sum = sum + sigma.into_iter().enumerate().map(|(i,j)| self[(i,j)].clone()).fold(T::one(), |a,b| a*b);
}
sum
}
/// Returns the inverse of the given matrix, if it is invertible.
pub fn inverse(&self) -> Option<Self> {
self.clone().invert_in_place()
}
/// Consumes the given matrix, and returns its inverse, if it is invertible.
pub fn invert_in_place(mut self) -> Option<Self> {
if!self.is_square() {
panic!("Attempting to invert a non-square matrix.");
}
let n = self.n;
// Waaa matrix inversion is a complex business.
// Let's keep it `simple` with a Gauss-Jordan elimination...
// The idea is: append an Identity matrix to the right (so we have a 2x1 aspect ratio)
// Apply simple linear row operations (permutation, multiplication, addition) until the
// first half is an identity matrix.
// At this point, the second half should be the inverse matrix.
// (Since we apply the inverse of the first half to an identity matrix.)
self.append_cols(Matrix::scalar(n, T::one()));
// For each (original) column...
for k in 0..n {
// Make sure the column is C[i] = i==k? 1 : 0
// Find the perfect candidate: a non-zero element
let j = match (k..n).find(|&i| self[(k,i)]!= T::zero()) {
None => return None,
Some(j) => j,
};
self.swap_rows(j, k);
// Now divide the row by the diagonal value
let pivot = self[(k,k)].clone();
// No need to divide the first k values, they should be zeroes
for x in k..self.n {
self[(x,k)] = self[(x,k)].clone() / pivot.clone();
}
// Finally, zero all other rows
for y in (0..n).filter(|&i| i!= k) {
let value = self[(k,y)].clone();
for x in k..self.n {
self[(x,y)] = self[(x,y)].clone() - value.clone() * self[(x,k)].clone();
}
}
}
// And remove the first half
self.keep_cols(n..2*n);
Some(self)
}
}
impl <T: Clone + Float> Matrix<T> {
/// Returns the triangular matrix from the cholesky decomposition.
pub fn cholesky(&self) -> Self {
self.clone().cholesky_in_place()
}
/// Returns a matrix `L` such that `L * L.transpose() == self`. Assumes that self is symmetric.
pub fn cholesky_in_place(mut self) -> Self {
let n = self.n;
for x in 0..n {
for y in 0..x { self[(x,y)] = T::zero(); }
let sum = (0..x).map(|i| self[(i,x)]).map(|v| v*v).fold(T::zero(), |a,b| a+b);
let ljj = (self[(x,x)] - sum).sqrt();
self[(x,x)] = ljj;
let iv = ljj.recip();
for y in x+1..n {
let sum = (0..x).map(|i| self[(i,x)] * self[(i,y)]).fold(T::zero(), |a,b| a+b);
let lij = (self[(x,y)] - sum) * iv;
self[(x,y)] = lij;
}
}
self
}
}
impl <T: Clone + Mul<Output=T> + Add<Output=T> + Zero> Mul for Matrix<T> {
type Output = Matrix<T>;
fn mul(self, other: Matrix<T>) -> Matrix<T> {
&self * &other
}
}
impl <'a,'b, T: Add<Output=T> + Mul<Output=T> + Zero + Clone> Mul<&'b Matrix<T>> for &'a Matrix<T> {
type Output = Matrix<T>;
fn mul(self, other: &'b Matrix<T>) -> Matrix<T> {
// TODO: might want to make this faster. Parallel? Skip zero values?
Matrix::new(other.n, self.m, |x,y| (0..self.n).map(|i| self[(i,y)].clone() * other[(x,i)].clone()).fold(T::zero(), |a,b|a+b))
}
}
impl <T: Add<Output=T> + Mul<Output=T> + Zero + Clone> Mul<Vector<T>> for Matrix<T> {
type Output = Vector<T>;
fn mul(self, other: Vector<T>) -> Vector<T> {
&self * &other
}
}
impl <'a, T: Add<Output=T> + Mul<Output=T> + Zero + Clone> Mul<Vector<T>> for &'a Matrix<T> {
type Output = Vector<T>;
fn mul(self, other: Vector<T>) -> Vector<T> {
self * &other
}
}
impl <'a,'b, T: Add<Output=T> + Mul<Output=T> + Zero + Clone> Mul<&'b Vector<T>> for &'a Matrix<T> {
type Output = Vector<T>;
fn mul(self, other: &'b Vector<T>) -> Vector<T> {
Vector::new(self.m, |i| (0..self.n).map(|j| self[(j,i)].clone() * other[j].clone()).fold(T::zero(), |a,b| a+b))
}
}
impl <'a, T: Add<Output=T> + Clone> Add for &'a Matrix<T> {
type Output = Matrix<T>;
fn add(self, other: &'a Matrix<T>) -> Matrix<T> {
Matrix::new(self.n, self.m, |x,y| self[(x,y)].clone() + other[(x,y)].clone())
}
}
impl <T: Sub<Output=T> + Clone> Sub for Matrix<T> {
type Output = Matrix<T>;
fn sub(mut self, other: Matrix<T>) -> Matrix<T> {
for (s,o) in self.data.iter_mut().zip(other.data.into_iter()) {
*s = s.clone() - o;
}
self
}
}
impl <'a, T: Sub<Output=T> + Clone> Sub for &'a Matrix<T> {
type Output = Matrix<T>;
fn sub(self, other: &'a Matrix<T>) -> Matrix<T> {
Matrix::new(self.n, self.m, |x,y| self[(x,y)].clone() - other[(x,y)].clone())
}
}
impl <'a, T: Mul<Output=T> + Clone> Mul<T> for &'a Matrix<T> {
type Output = Matrix<T>;
fn mul(self, other: T) -> Matrix<T> {
Matrix::new(self.n, self.m, |x,y| self[(x,y)].clone() * other.clone())
}
}
impl <'a, T: Div<Output=T> + Clone> Div<T> for &'a Matrix<T> {
type Output = Matrix<T>;
fn div(self, other: T) -> Matrix<T> {
Matrix::new(self.n, self.m, |x,y| self[(x,y)].clone() / other.clone())
}
}
impl <T> Index<(usize,usize)> for Matrix<T> {
type Output = T;
fn index(&self, (x,y): (usize,usize)) -> &T {
let i = self.get_index((x,y));
&self.data[i]
}
}
impl <T> IndexMut<(usize,usize)> for Matrix<T> {
fn index_mut(&mut self, (x,y): (usize,usize)) -> &mut T {
let i = self.get_index((x,y));
&mut self.data[i]
}
}
impl <T: fmt::Display> fmt::Display for Matrix<T> {
fn fmt(&self, fmt: &mut fmt::Formatter) -> Result<(),fmt::Error> {
try!(fmt.write_str(&format!("[{} x {}]", self.n, self.m)));
for y in 0..self.m {
try!(fmt.write_str("["));
for x in 0..self.n {
try!(self[(x,y)].fmt(fmt));
try!(fmt.write_str(", "));
}
try!(fmt.write_str("]\n"));
}
Ok(())
}
}
#[test]
fn test_i3() {
let i3 = Matrix::scalar(3, 1);
assert_eq!(i3.n, 3);
assert_eq!(i3.m, 3);
assert_eq!(i3[(0,0)], 1);
assert_eq!(i3[(1,1)], 1);
assert_eq!(i3[(2,2)], 1);
}
#[test]
fn test_add() {
let i3 = Matrix::scalar(3, 1);
let double = &i3 + &i3;
assert_eq!(double, Matrix::scalar(3,2));
}
#[test]
fn test_transpose() {
let v = Vector::new(4, |i| 1+i);
assert_eq!(Matrix::from_row(&v), Matrix::from_col(&v).transpose());
let m = Matrix::new(4,3, |x,y| x+4*y);
let n = Matrix::new(3,4, |x,y| y+4*x);
assert!(m!= n);
assert_eq!(m.transpose().transpose(), m);
assert_eq!(m.transpose(), n);
assert_eq!(n.transpose(), m);
}
#[test]
fn test_transpose_commutation() {
let a = Matrix::new(5,3, |x,y| x+5*y);
let b = Matrix::new(4,5, |x,y| x+y + 2*(x+y)%2);
assert_eq!((&a * &b).transpose(), &b.transpose() * &a.transpose());
}
#[test]
fn test_from_row() {
let v = Vector::new(4, |i| 1+i);
let m = Matrix::new(4,1, |x,_| 1+x);
assert_eq!(Matrix::from_row(&v), m);
assert_eq!(m.to_vector(), v);
}
#[test]
fn test_sub() {
let a = Matrix::new(4,3, |x,y| x+y);
assert_eq!(&a - &a, Matrix::zero(4,3));
}
#[test]
fn test_cols() {
let a = Matrix::new(4,4, |x,y| x+y);
let b = Matrix::new(4,4, |x,y| 8 - (x+y));
let mut c = a.clone();
c.append_cols(b.clone());
c.keep_cols(4..8);
assert_eq!(b, c);
let mut d = b.clone();
d.append_cols(a.clone());
d.keep_cols(4..8);
assert_eq!(a, d);
}
#[test]
fn test_determinant() {
let i5 = Matrix::<f64>::identity(5);
assert_eq!(i5.determinant(), 1f64);
}
#[test]
fn test_inverse() {
let a = Matrix::new(2,2, |x,y| (x+y) as f64);
let b = a.inverse().unwrap();
assert_eq!((&a * &b), Matrix::identity(2));
}
#[test]
fn test_mul() {
let m = Matrix::new(4,4, |x,y| x+y);
let v = Vector::new(4, |i| i+1);
assert_eq!(Matrix::from_col(&(&m * &v)), &m * &Matrix::from_col(&v));
}
|
{ return; }
|
conditional_block
|
matrix.rs
|
use num::{Zero,One};
use num::{Num,Float};
use std::fmt;
use std::ops::{Index,IndexMut,Add,Mul,Div,Sub,Range};
use alg::Vector;
/// Represents a simple `NxM` matrix.
#[derive(Clone,PartialEq,Debug)]
pub struct Matrix<T> {
/// Number of rows (max Y)
pub m: usize,
/// Number of columns (max X)
pub n: usize,
// Inner data. Cols concatenated.
data: Vec<T>,
}
impl <T> Matrix<T> {
/// Creates a new matrix with the given dimensions,
/// initializing each cell with the given functor.
///
/// * `m` is the number of lines (the Y size)
/// * `n` is the number of columns (the X size)
pub fn new<F>(n: usize, m: usize, f: F) -> Self
where F: Fn(usize,usize) -> T
{
let data = (0..n*m).map(|i| (i/m,i%m)).map(|(x,y)| f(x,y)).collect();
Matrix {
m: m,
n: n,
data: data,
}
}
/// Only keeps a subset of consecutive columns indicated
/// by the given range, and discard the rest.
pub fn keep_cols(&mut self, cols: Range<usize>) {
let n_cols = cols.end - cols.start;
let start = cols.start * self.m;
let end = cols.end * self.m;
self.data.truncate(end);
if start > 0 {
self.data = self.data.split_off(start);
}
self.n = n_cols;
}
/// Appends the columnds from the given matrix to this one.
///
/// Panics if the matrices don't have the same height.
pub fn append_cols(&mut self, mut other: Matrix<T>) {
if self.m!= other.m {
panic!("Matrices don't have the same height.");
}
self.n += other.n;
// append is currently unstable. See../lib.rs
self.data.append(&mut other.data);
}
/// Returns the index in the data array corresponding to the given cell.
fn get_index(&self, (x,y): (usize,usize)) -> usize {
y + x * self.m
}
/// Creates a dummy empty matrix.
pub fn dummy() -> Self {
Matrix {
m: 0,
n: 0,
data: Vec::new(),
}
}
/// Returns TRUE if the matrix is square.
pub fn is_square(&self) -> bool {
return self.m == self.n
}
/// Swaps the content from two cells.
pub fn swap(&mut self, a: (usize,usize), b: (usize,usize)) {
let ia = self.get_index(a);
let ib = self.get_index(b);
self.data.swap(ia, ib);
}
/// Swaps the content from two columns.
pub fn swap_cols(&mut self, xa: usize, xb: usize) {
if xa == xb { return; }
for y in 0..self.n {
self.swap((xa,y), (xb,y));
}
}
/// Swaps the content from two rows.
pub fn swap_rows(&mut self, ya: usize, yb: usize) {
if ya == yb { return; }
for x in 0..self.n {
self.swap((x,ya),(x,yb));
}
}
}
impl <T: Zero> Matrix<T> {
/// Creates a new matrix initialized to zero.
pub fn zero(n: usize, m: usize) -> Self {
Matrix::new(n,m, |_,_| T::zero())
}
}
impl <T: Clone> Matrix<T> {
/// Returns a new Vector, cloned from the given row.
pub fn row(&self, y: usize) -> Vector<T> {
Vector::new(self.n, |i| self[(i,y)].clone())
}
/// Returns a new Vector, cloned from the given column.
pub fn col(&self, x: usize) -> Vector<T> {
Vector::new(self.m, |i| self[(x,i)].clone())
}
/// Sets a column content from the given vector.
pub fn set_col(&mut self, x: usize, col: Vector<T>) {
for (i,v) in col.into_iter().enumerate() {
self[(x,i)] = v;
}
}
/// Sets a row content from the given vector.
pub fn set_row(&mut self, y: usize, row: Vector<T>) {
for (i,v) in row.into_iter().enumerate() {
self[(i,y)] = v;
}
}
/// Create a single-column matrix from the given Vector.
pub fn from_col(v: &Vector<T>) -> Self {
Matrix::new(1, v.dim(), |_,y| v[y].clone())
}
/// Make a matrix from the given vectors, to treat as columns.
pub fn from_cols(cols: &[Vector<T>]) -> Self {
if cols.is_empty() {
Matrix::dummy()
} else {
let n = cols.len();
let m = cols.first().unwrap().dim();
Matrix::new(n, m, |x,y| cols[x][y].clone())
}
}
/// Create a single-row matrix from the given Vector.
pub fn from_row(v: &Vector<T>) -> Self {
Matrix::new(v.dim(), 1, |x,_| v[x].clone())
}
/// Make a matrix from the given vectors, to treas as rows.
pub fn from_rows(rows: &[Vector<T>]) -> Self {
if rows.is_empty() {
Matrix::dummy()
} else {
let m = rows.len();
let n = rows.first().unwrap().dim();
Matrix::new(n, m, |x,y| rows[y][x].clone())
}
}
/// Returns the transposed matrix.
pub fn transpose(&self) -> Matrix<T> {
Matrix::new(self.m, self.n, |x,y| self[(y,x)].clone())
}
/// If this matrix is single-row or single-column,
/// transforms this into a Vector.
pub fn to_vector(self) -> Vector<T> {
if self.n == 1 || self.m == 1 {
Vector::from(self.data)
} else {
panic!("Matrix is not single-row or single-column.");
}
}
}
impl <T: Clone + Zero> Matrix<T> {
/// Creates a new diagonal matrix, with the given vector serving as the diagonal.
pub fn diagonal(vector: Vector<T>) -> Self {
let n = vector.dim();
let mut m = Matrix::zero(n,n);
for (i,x) in vector.into_iter().enumerate() {
m[(i,i)] = x;
}
m
}
/// Creates a new scalar matrix with the given value.
pub fn scalar(n: usize, value: T) -> Self {
Matrix::diagonal(Vector::from_copies(n, value))
}
}
impl <T: Clone + Zero + One> Matrix<T> {
/// Creates a new square identity matrix, with ones on the diagonal.
pub fn identity(n: usize) -> Self
|
}
impl <T: Clone + Num> Matrix<T> {
/// Returns the square norm of a matrix: the sum of the square of all cells.
pub fn square_norm(&self) -> T {
self.data.iter().map(|a| a.clone() * a.clone()).fold(T::zero(), |a,b| a+b)
}
/// Returns the matrix determinant.
///
/// Returns zero for non-square and non-invertible matrices.
pub fn determinant(&self) -> T {
if self.m!= self.n { return T::zero(); }
let mut sum = T::zero();
let range: Vec<usize> = (0..self.n).collect();
for sigma in range.permutations() {
// TODO: actually compute the signature!!
// We must multiply by +1 or -1 depending on thepermutation.
sum = sum + sigma.into_iter().enumerate().map(|(i,j)| self[(i,j)].clone()).fold(T::one(), |a,b| a*b);
}
sum
}
/// Returns the inverse of the given matrix, if it is invertible.
pub fn inverse(&self) -> Option<Self> {
self.clone().invert_in_place()
}
/// Consumes the given matrix, and returns its inverse, if it is invertible.
pub fn invert_in_place(mut self) -> Option<Self> {
if!self.is_square() {
panic!("Attempting to invert a non-square matrix.");
}
let n = self.n;
// Waaa matrix inversion is a complex business.
// Let's keep it `simple` with a Gauss-Jordan elimination...
// The idea is: append an Identity matrix to the right (so we have a 2x1 aspect ratio)
// Apply simple linear row operations (permutation, multiplication, addition) until the
// first half is an identity matrix.
// At this point, the second half should be the inverse matrix.
// (Since we apply the inverse of the first half to an identity matrix.)
self.append_cols(Matrix::scalar(n, T::one()));
// For each (original) column...
for k in 0..n {
// Make sure the column is C[i] = i==k? 1 : 0
// Find the perfect candidate: a non-zero element
let j = match (k..n).find(|&i| self[(k,i)]!= T::zero()) {
None => return None,
Some(j) => j,
};
self.swap_rows(j, k);
// Now divide the row by the diagonal value
let pivot = self[(k,k)].clone();
// No need to divide the first k values, they should be zeroes
for x in k..self.n {
self[(x,k)] = self[(x,k)].clone() / pivot.clone();
}
// Finally, zero all other rows
for y in (0..n).filter(|&i| i!= k) {
let value = self[(k,y)].clone();
for x in k..self.n {
self[(x,y)] = self[(x,y)].clone() - value.clone() * self[(x,k)].clone();
}
}
}
// And remove the first half
self.keep_cols(n..2*n);
Some(self)
}
}
impl <T: Clone + Float> Matrix<T> {
/// Returns the triangular matrix from the cholesky decomposition.
pub fn cholesky(&self) -> Self {
self.clone().cholesky_in_place()
}
/// Returns a matrix `L` such that `L * L.transpose() == self`. Assumes that self is symmetric.
pub fn cholesky_in_place(mut self) -> Self {
let n = self.n;
for x in 0..n {
for y in 0..x { self[(x,y)] = T::zero(); }
let sum = (0..x).map(|i| self[(i,x)]).map(|v| v*v).fold(T::zero(), |a,b| a+b);
let ljj = (self[(x,x)] - sum).sqrt();
self[(x,x)] = ljj;
let iv = ljj.recip();
for y in x+1..n {
let sum = (0..x).map(|i| self[(i,x)] * self[(i,y)]).fold(T::zero(), |a,b| a+b);
let lij = (self[(x,y)] - sum) * iv;
self[(x,y)] = lij;
}
}
self
}
}
impl <T: Clone + Mul<Output=T> + Add<Output=T> + Zero> Mul for Matrix<T> {
type Output = Matrix<T>;
fn mul(self, other: Matrix<T>) -> Matrix<T> {
&self * &other
}
}
impl <'a,'b, T: Add<Output=T> + Mul<Output=T> + Zero + Clone> Mul<&'b Matrix<T>> for &'a Matrix<T> {
type Output = Matrix<T>;
fn mul(self, other: &'b Matrix<T>) -> Matrix<T> {
// TODO: might want to make this faster. Parallel? Skip zero values?
Matrix::new(other.n, self.m, |x,y| (0..self.n).map(|i| self[(i,y)].clone() * other[(x,i)].clone()).fold(T::zero(), |a,b|a+b))
}
}
impl <T: Add<Output=T> + Mul<Output=T> + Zero + Clone> Mul<Vector<T>> for Matrix<T> {
type Output = Vector<T>;
fn mul(self, other: Vector<T>) -> Vector<T> {
&self * &other
}
}
impl <'a, T: Add<Output=T> + Mul<Output=T> + Zero + Clone> Mul<Vector<T>> for &'a Matrix<T> {
type Output = Vector<T>;
fn mul(self, other: Vector<T>) -> Vector<T> {
self * &other
}
}
impl <'a,'b, T: Add<Output=T> + Mul<Output=T> + Zero + Clone> Mul<&'b Vector<T>> for &'a Matrix<T> {
type Output = Vector<T>;
fn mul(self, other: &'b Vector<T>) -> Vector<T> {
Vector::new(self.m, |i| (0..self.n).map(|j| self[(j,i)].clone() * other[j].clone()).fold(T::zero(), |a,b| a+b))
}
}
impl <'a, T: Add<Output=T> + Clone> Add for &'a Matrix<T> {
type Output = Matrix<T>;
fn add(self, other: &'a Matrix<T>) -> Matrix<T> {
Matrix::new(self.n, self.m, |x,y| self[(x,y)].clone() + other[(x,y)].clone())
}
}
impl <T: Sub<Output=T> + Clone> Sub for Matrix<T> {
type Output = Matrix<T>;
fn sub(mut self, other: Matrix<T>) -> Matrix<T> {
for (s,o) in self.data.iter_mut().zip(other.data.into_iter()) {
*s = s.clone() - o;
}
self
}
}
impl <'a, T: Sub<Output=T> + Clone> Sub for &'a Matrix<T> {
type Output = Matrix<T>;
fn sub(self, other: &'a Matrix<T>) -> Matrix<T> {
Matrix::new(self.n, self.m, |x,y| self[(x,y)].clone() - other[(x,y)].clone())
}
}
impl <'a, T: Mul<Output=T> + Clone> Mul<T> for &'a Matrix<T> {
type Output = Matrix<T>;
fn mul(self, other: T) -> Matrix<T> {
Matrix::new(self.n, self.m, |x,y| self[(x,y)].clone() * other.clone())
}
}
impl <'a, T: Div<Output=T> + Clone> Div<T> for &'a Matrix<T> {
type Output = Matrix<T>;
fn div(self, other: T) -> Matrix<T> {
Matrix::new(self.n, self.m, |x,y| self[(x,y)].clone() / other.clone())
}
}
impl <T> Index<(usize,usize)> for Matrix<T> {
type Output = T;
fn index(&self, (x,y): (usize,usize)) -> &T {
let i = self.get_index((x,y));
&self.data[i]
}
}
impl <T> IndexMut<(usize,usize)> for Matrix<T> {
fn index_mut(&mut self, (x,y): (usize,usize)) -> &mut T {
let i = self.get_index((x,y));
&mut self.data[i]
}
}
impl <T: fmt::Display> fmt::Display for Matrix<T> {
fn fmt(&self, fmt: &mut fmt::Formatter) -> Result<(),fmt::Error> {
try!(fmt.write_str(&format!("[{} x {}]", self.n, self.m)));
for y in 0..self.m {
try!(fmt.write_str("["));
for x in 0..self.n {
try!(self[(x,y)].fmt(fmt));
try!(fmt.write_str(", "));
}
try!(fmt.write_str("]\n"));
}
Ok(())
}
}
#[test]
fn test_i3() {
let i3 = Matrix::scalar(3, 1);
assert_eq!(i3.n, 3);
assert_eq!(i3.m, 3);
assert_eq!(i3[(0,0)], 1);
assert_eq!(i3[(1,1)], 1);
assert_eq!(i3[(2,2)], 1);
}
#[test]
fn test_add() {
let i3 = Matrix::scalar(3, 1);
let double = &i3 + &i3;
assert_eq!(double, Matrix::scalar(3,2));
}
#[test]
fn test_transpose() {
let v = Vector::new(4, |i| 1+i);
assert_eq!(Matrix::from_row(&v), Matrix::from_col(&v).transpose());
let m = Matrix::new(4,3, |x,y| x+4*y);
let n = Matrix::new(3,4, |x,y| y+4*x);
assert!(m!= n);
assert_eq!(m.transpose().transpose(), m);
assert_eq!(m.transpose(), n);
assert_eq!(n.transpose(), m);
}
#[test]
fn test_transpose_commutation() {
let a = Matrix::new(5,3, |x,y| x+5*y);
let b = Matrix::new(4,5, |x,y| x+y + 2*(x+y)%2);
assert_eq!((&a * &b).transpose(), &b.transpose() * &a.transpose());
}
#[test]
fn test_from_row() {
let v = Vector::new(4, |i| 1+i);
let m = Matrix::new(4,1, |x,_| 1+x);
assert_eq!(Matrix::from_row(&v), m);
assert_eq!(m.to_vector(), v);
}
#[test]
fn test_sub() {
let a = Matrix::new(4,3, |x,y| x+y);
assert_eq!(&a - &a, Matrix::zero(4,3));
}
#[test]
fn test_cols() {
let a = Matrix::new(4,4, |x,y| x+y);
let b = Matrix::new(4,4, |x,y| 8 - (x+y));
let mut c = a.clone();
c.append_cols(b.clone());
c.keep_cols(4..8);
assert_eq!(b, c);
let mut d = b.clone();
d.append_cols(a.clone());
d.keep_cols(4..8);
assert_eq!(a, d);
}
#[test]
fn test_determinant() {
let i5 = Matrix::<f64>::identity(5);
assert_eq!(i5.determinant(), 1f64);
}
#[test]
fn test_inverse() {
let a = Matrix::new(2,2, |x,y| (x+y) as f64);
let b = a.inverse().unwrap();
assert_eq!((&a * &b), Matrix::identity(2));
}
#[test]
fn test_mul() {
let m = Matrix::new(4,4, |x,y| x+y);
let v = Vector::new(4, |i| i+1);
assert_eq!(Matrix::from_col(&(&m * &v)), &m * &Matrix::from_col(&v));
}
|
{
Matrix::scalar(n, T::one())
}
|
identifier_body
|
matrix.rs
|
use num::{Zero,One};
use num::{Num,Float};
use std::fmt;
use std::ops::{Index,IndexMut,Add,Mul,Div,Sub,Range};
use alg::Vector;
/// Represents a simple `NxM` matrix.
#[derive(Clone,PartialEq,Debug)]
pub struct Matrix<T> {
/// Number of rows (max Y)
pub m: usize,
/// Number of columns (max X)
pub n: usize,
// Inner data. Cols concatenated.
data: Vec<T>,
}
impl <T> Matrix<T> {
/// Creates a new matrix with the given dimensions,
/// initializing each cell with the given functor.
///
/// * `m` is the number of lines (the Y size)
/// * `n` is the number of columns (the X size)
pub fn new<F>(n: usize, m: usize, f: F) -> Self
where F: Fn(usize,usize) -> T
{
let data = (0..n*m).map(|i| (i/m,i%m)).map(|(x,y)| f(x,y)).collect();
Matrix {
m: m,
n: n,
data: data,
}
}
/// Only keeps a subset of consecutive columns indicated
/// by the given range, and discard the rest.
pub fn keep_cols(&mut self, cols: Range<usize>) {
let n_cols = cols.end - cols.start;
let start = cols.start * self.m;
let end = cols.end * self.m;
self.data.truncate(end);
if start > 0 {
self.data = self.data.split_off(start);
}
self.n = n_cols;
}
/// Appends the columnds from the given matrix to this one.
///
/// Panics if the matrices don't have the same height.
pub fn append_cols(&mut self, mut other: Matrix<T>) {
if self.m!= other.m {
panic!("Matrices don't have the same height.");
}
self.n += other.n;
// append is currently unstable. See../lib.rs
self.data.append(&mut other.data);
}
/// Returns the index in the data array corresponding to the given cell.
fn get_index(&self, (x,y): (usize,usize)) -> usize {
y + x * self.m
}
/// Creates a dummy empty matrix.
pub fn dummy() -> Self {
Matrix {
m: 0,
n: 0,
data: Vec::new(),
}
}
/// Returns TRUE if the matrix is square.
pub fn is_square(&self) -> bool {
return self.m == self.n
}
/// Swaps the content from two cells.
pub fn swap(&mut self, a: (usize,usize), b: (usize,usize)) {
let ia = self.get_index(a);
let ib = self.get_index(b);
self.data.swap(ia, ib);
}
/// Swaps the content from two columns.
pub fn swap_cols(&mut self, xa: usize, xb: usize) {
if xa == xb { return; }
for y in 0..self.n {
self.swap((xa,y), (xb,y));
}
}
/// Swaps the content from two rows.
pub fn swap_rows(&mut self, ya: usize, yb: usize) {
if ya == yb { return; }
for x in 0..self.n {
self.swap((x,ya),(x,yb));
}
}
}
impl <T: Zero> Matrix<T> {
/// Creates a new matrix initialized to zero.
pub fn zero(n: usize, m: usize) -> Self {
Matrix::new(n,m, |_,_| T::zero())
}
}
impl <T: Clone> Matrix<T> {
/// Returns a new Vector, cloned from the given row.
pub fn row(&self, y: usize) -> Vector<T> {
Vector::new(self.n, |i| self[(i,y)].clone())
}
/// Returns a new Vector, cloned from the given column.
pub fn col(&self, x: usize) -> Vector<T> {
Vector::new(self.m, |i| self[(x,i)].clone())
}
/// Sets a column content from the given vector.
pub fn set_col(&mut self, x: usize, col: Vector<T>) {
for (i,v) in col.into_iter().enumerate() {
self[(x,i)] = v;
}
}
/// Sets a row content from the given vector.
pub fn set_row(&mut self, y: usize, row: Vector<T>) {
for (i,v) in row.into_iter().enumerate() {
self[(i,y)] = v;
}
}
/// Create a single-column matrix from the given Vector.
pub fn from_col(v: &Vector<T>) -> Self {
Matrix::new(1, v.dim(), |_,y| v[y].clone())
}
/// Make a matrix from the given vectors, to treat as columns.
pub fn from_cols(cols: &[Vector<T>]) -> Self {
if cols.is_empty() {
Matrix::dummy()
} else {
let n = cols.len();
let m = cols.first().unwrap().dim();
Matrix::new(n, m, |x,y| cols[x][y].clone())
}
}
/// Create a single-row matrix from the given Vector.
pub fn from_row(v: &Vector<T>) -> Self {
Matrix::new(v.dim(), 1, |x,_| v[x].clone())
}
/// Make a matrix from the given vectors, to treas as rows.
pub fn from_rows(rows: &[Vector<T>]) -> Self {
if rows.is_empty() {
Matrix::dummy()
} else {
let m = rows.len();
let n = rows.first().unwrap().dim();
Matrix::new(n, m, |x,y| rows[y][x].clone())
}
}
/// Returns the transposed matrix.
pub fn transpose(&self) -> Matrix<T> {
Matrix::new(self.m, self.n, |x,y| self[(y,x)].clone())
}
/// If this matrix is single-row or single-column,
/// transforms this into a Vector.
pub fn to_vector(self) -> Vector<T> {
if self.n == 1 || self.m == 1 {
Vector::from(self.data)
} else {
panic!("Matrix is not single-row or single-column.");
}
}
}
impl <T: Clone + Zero> Matrix<T> {
/// Creates a new diagonal matrix, with the given vector serving as the diagonal.
|
let mut m = Matrix::zero(n,n);
for (i,x) in vector.into_iter().enumerate() {
m[(i,i)] = x;
}
m
}
/// Creates a new scalar matrix with the given value.
pub fn scalar(n: usize, value: T) -> Self {
Matrix::diagonal(Vector::from_copies(n, value))
}
}
impl <T: Clone + Zero + One> Matrix<T> {
/// Creates a new square identity matrix, with ones on the diagonal.
pub fn identity(n: usize) -> Self {
Matrix::scalar(n, T::one())
}
}
impl <T: Clone + Num> Matrix<T> {
/// Returns the square norm of a matrix: the sum of the square of all cells.
pub fn square_norm(&self) -> T {
self.data.iter().map(|a| a.clone() * a.clone()).fold(T::zero(), |a,b| a+b)
}
/// Returns the matrix determinant.
///
/// Returns zero for non-square and non-invertible matrices.
pub fn determinant(&self) -> T {
if self.m!= self.n { return T::zero(); }
let mut sum = T::zero();
let range: Vec<usize> = (0..self.n).collect();
for sigma in range.permutations() {
// TODO: actually compute the signature!!
// We must multiply by +1 or -1 depending on thepermutation.
sum = sum + sigma.into_iter().enumerate().map(|(i,j)| self[(i,j)].clone()).fold(T::one(), |a,b| a*b);
}
sum
}
/// Returns the inverse of the given matrix, if it is invertible.
pub fn inverse(&self) -> Option<Self> {
self.clone().invert_in_place()
}
/// Consumes the given matrix, and returns its inverse, if it is invertible.
pub fn invert_in_place(mut self) -> Option<Self> {
if!self.is_square() {
panic!("Attempting to invert a non-square matrix.");
}
let n = self.n;
// Waaa matrix inversion is a complex business.
// Let's keep it `simple` with a Gauss-Jordan elimination...
// The idea is: append an Identity matrix to the right (so we have a 2x1 aspect ratio)
// Apply simple linear row operations (permutation, multiplication, addition) until the
// first half is an identity matrix.
// At this point, the second half should be the inverse matrix.
// (Since we apply the inverse of the first half to an identity matrix.)
self.append_cols(Matrix::scalar(n, T::one()));
// For each (original) column...
for k in 0..n {
// Make sure the column is C[i] = i==k? 1 : 0
// Find the perfect candidate: a non-zero element
let j = match (k..n).find(|&i| self[(k,i)]!= T::zero()) {
None => return None,
Some(j) => j,
};
self.swap_rows(j, k);
// Now divide the row by the diagonal value
let pivot = self[(k,k)].clone();
// No need to divide the first k values, they should be zeroes
for x in k..self.n {
self[(x,k)] = self[(x,k)].clone() / pivot.clone();
}
// Finally, zero all other rows
for y in (0..n).filter(|&i| i!= k) {
let value = self[(k,y)].clone();
for x in k..self.n {
self[(x,y)] = self[(x,y)].clone() - value.clone() * self[(x,k)].clone();
}
}
}
// And remove the first half
self.keep_cols(n..2*n);
Some(self)
}
}
impl <T: Clone + Float> Matrix<T> {
/// Returns the triangular matrix from the cholesky decomposition.
pub fn cholesky(&self) -> Self {
self.clone().cholesky_in_place()
}
/// Returns a matrix `L` such that `L * L.transpose() == self`. Assumes that self is symmetric.
pub fn cholesky_in_place(mut self) -> Self {
let n = self.n;
for x in 0..n {
for y in 0..x { self[(x,y)] = T::zero(); }
let sum = (0..x).map(|i| self[(i,x)]).map(|v| v*v).fold(T::zero(), |a,b| a+b);
let ljj = (self[(x,x)] - sum).sqrt();
self[(x,x)] = ljj;
let iv = ljj.recip();
for y in x+1..n {
let sum = (0..x).map(|i| self[(i,x)] * self[(i,y)]).fold(T::zero(), |a,b| a+b);
let lij = (self[(x,y)] - sum) * iv;
self[(x,y)] = lij;
}
}
self
}
}
impl <T: Clone + Mul<Output=T> + Add<Output=T> + Zero> Mul for Matrix<T> {
type Output = Matrix<T>;
fn mul(self, other: Matrix<T>) -> Matrix<T> {
&self * &other
}
}
impl <'a,'b, T: Add<Output=T> + Mul<Output=T> + Zero + Clone> Mul<&'b Matrix<T>> for &'a Matrix<T> {
type Output = Matrix<T>;
fn mul(self, other: &'b Matrix<T>) -> Matrix<T> {
// TODO: might want to make this faster. Parallel? Skip zero values?
Matrix::new(other.n, self.m, |x,y| (0..self.n).map(|i| self[(i,y)].clone() * other[(x,i)].clone()).fold(T::zero(), |a,b|a+b))
}
}
impl <T: Add<Output=T> + Mul<Output=T> + Zero + Clone> Mul<Vector<T>> for Matrix<T> {
type Output = Vector<T>;
fn mul(self, other: Vector<T>) -> Vector<T> {
&self * &other
}
}
impl <'a, T: Add<Output=T> + Mul<Output=T> + Zero + Clone> Mul<Vector<T>> for &'a Matrix<T> {
type Output = Vector<T>;
fn mul(self, other: Vector<T>) -> Vector<T> {
self * &other
}
}
impl <'a,'b, T: Add<Output=T> + Mul<Output=T> + Zero + Clone> Mul<&'b Vector<T>> for &'a Matrix<T> {
type Output = Vector<T>;
fn mul(self, other: &'b Vector<T>) -> Vector<T> {
Vector::new(self.m, |i| (0..self.n).map(|j| self[(j,i)].clone() * other[j].clone()).fold(T::zero(), |a,b| a+b))
}
}
impl <'a, T: Add<Output=T> + Clone> Add for &'a Matrix<T> {
type Output = Matrix<T>;
fn add(self, other: &'a Matrix<T>) -> Matrix<T> {
Matrix::new(self.n, self.m, |x,y| self[(x,y)].clone() + other[(x,y)].clone())
}
}
impl <T: Sub<Output=T> + Clone> Sub for Matrix<T> {
type Output = Matrix<T>;
fn sub(mut self, other: Matrix<T>) -> Matrix<T> {
for (s,o) in self.data.iter_mut().zip(other.data.into_iter()) {
*s = s.clone() - o;
}
self
}
}
impl <'a, T: Sub<Output=T> + Clone> Sub for &'a Matrix<T> {
type Output = Matrix<T>;
fn sub(self, other: &'a Matrix<T>) -> Matrix<T> {
Matrix::new(self.n, self.m, |x,y| self[(x,y)].clone() - other[(x,y)].clone())
}
}
impl <'a, T: Mul<Output=T> + Clone> Mul<T> for &'a Matrix<T> {
type Output = Matrix<T>;
fn mul(self, other: T) -> Matrix<T> {
Matrix::new(self.n, self.m, |x,y| self[(x,y)].clone() * other.clone())
}
}
impl <'a, T: Div<Output=T> + Clone> Div<T> for &'a Matrix<T> {
type Output = Matrix<T>;
fn div(self, other: T) -> Matrix<T> {
Matrix::new(self.n, self.m, |x,y| self[(x,y)].clone() / other.clone())
}
}
impl <T> Index<(usize,usize)> for Matrix<T> {
type Output = T;
fn index(&self, (x,y): (usize,usize)) -> &T {
let i = self.get_index((x,y));
&self.data[i]
}
}
impl <T> IndexMut<(usize,usize)> for Matrix<T> {
fn index_mut(&mut self, (x,y): (usize,usize)) -> &mut T {
let i = self.get_index((x,y));
&mut self.data[i]
}
}
impl <T: fmt::Display> fmt::Display for Matrix<T> {
fn fmt(&self, fmt: &mut fmt::Formatter) -> Result<(),fmt::Error> {
try!(fmt.write_str(&format!("[{} x {}]", self.n, self.m)));
for y in 0..self.m {
try!(fmt.write_str("["));
for x in 0..self.n {
try!(self[(x,y)].fmt(fmt));
try!(fmt.write_str(", "));
}
try!(fmt.write_str("]\n"));
}
Ok(())
}
}
#[test]
fn test_i3() {
let i3 = Matrix::scalar(3, 1);
assert_eq!(i3.n, 3);
assert_eq!(i3.m, 3);
assert_eq!(i3[(0,0)], 1);
assert_eq!(i3[(1,1)], 1);
assert_eq!(i3[(2,2)], 1);
}
#[test]
fn test_add() {
let i3 = Matrix::scalar(3, 1);
let double = &i3 + &i3;
assert_eq!(double, Matrix::scalar(3,2));
}
#[test]
fn test_transpose() {
let v = Vector::new(4, |i| 1+i);
assert_eq!(Matrix::from_row(&v), Matrix::from_col(&v).transpose());
let m = Matrix::new(4,3, |x,y| x+4*y);
let n = Matrix::new(3,4, |x,y| y+4*x);
assert!(m!= n);
assert_eq!(m.transpose().transpose(), m);
assert_eq!(m.transpose(), n);
assert_eq!(n.transpose(), m);
}
#[test]
fn test_transpose_commutation() {
let a = Matrix::new(5,3, |x,y| x+5*y);
let b = Matrix::new(4,5, |x,y| x+y + 2*(x+y)%2);
assert_eq!((&a * &b).transpose(), &b.transpose() * &a.transpose());
}
#[test]
fn test_from_row() {
let v = Vector::new(4, |i| 1+i);
let m = Matrix::new(4,1, |x,_| 1+x);
assert_eq!(Matrix::from_row(&v), m);
assert_eq!(m.to_vector(), v);
}
#[test]
fn test_sub() {
let a = Matrix::new(4,3, |x,y| x+y);
assert_eq!(&a - &a, Matrix::zero(4,3));
}
#[test]
fn test_cols() {
let a = Matrix::new(4,4, |x,y| x+y);
let b = Matrix::new(4,4, |x,y| 8 - (x+y));
let mut c = a.clone();
c.append_cols(b.clone());
c.keep_cols(4..8);
assert_eq!(b, c);
let mut d = b.clone();
d.append_cols(a.clone());
d.keep_cols(4..8);
assert_eq!(a, d);
}
#[test]
fn test_determinant() {
let i5 = Matrix::<f64>::identity(5);
assert_eq!(i5.determinant(), 1f64);
}
#[test]
fn test_inverse() {
let a = Matrix::new(2,2, |x,y| (x+y) as f64);
let b = a.inverse().unwrap();
assert_eq!((&a * &b), Matrix::identity(2));
}
#[test]
fn test_mul() {
let m = Matrix::new(4,4, |x,y| x+y);
let v = Vector::new(4, |i| i+1);
assert_eq!(Matrix::from_col(&(&m * &v)), &m * &Matrix::from_col(&v));
}
|
pub fn diagonal(vector: Vector<T>) -> Self {
let n = vector.dim();
|
random_line_split
|
caa.rs
|
use std::ffi::CStr;
use std::fmt;
use std::marker::PhantomData;
use std::os::raw::{c_char, c_int, c_uchar, c_void};
use std::ptr;
use std::slice;
use itertools::Itertools;
use crate::error::{Error, Result};
use crate::panic;
/// The result of a successful CAA lookup.
#[derive(Debug)]
pub struct CAAResults {
caa_reply: *mut c_ares_sys::ares_caa_reply,
phantom: PhantomData<c_ares_sys::ares_caa_reply>,
}
/// The contents of a single CAA record.
#[derive(Clone, Copy)]
pub struct CAAResult<'a> {
// A single result - reference into a `CAAResults`.
caa_reply: &'a c_ares_sys::ares_caa_reply,
}
impl CAAResults {
/// Obtain a `CAAResults` from the response to a CAA lookup.
pub fn parse_from(data: &[u8]) -> Result<CAAResults> {
let mut caa_reply: *mut c_ares_sys::ares_caa_reply = ptr::null_mut();
let parse_status = unsafe {
c_ares_sys::ares_parse_caa_reply(data.as_ptr(), data.len() as c_int, &mut caa_reply)
};
if parse_status == c_ares_sys::ARES_SUCCESS {
let caa_result = CAAResults::new(caa_reply);
Ok(caa_result)
} else {
Err(Error::from(parse_status))
}
}
fn
|
(caa_reply: *mut c_ares_sys::ares_caa_reply) -> Self {
CAAResults {
caa_reply,
phantom: PhantomData,
}
}
/// Returns an iterator over the `CAAResult` values in this `CAAResults`.
pub fn iter(&self) -> CAAResultsIter {
CAAResultsIter {
next: unsafe { self.caa_reply.as_ref() },
}
}
}
impl fmt::Display for CAAResults {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
let results = self.iter().format("}, {");
write!(fmt, "[{{{}}}]", results)
}
}
/// Iterator of `CAAResult`s.
#[derive(Clone, Copy)]
pub struct CAAResultsIter<'a> {
next: Option<&'a c_ares_sys::ares_caa_reply>,
}
impl<'a> Iterator for CAAResultsIter<'a> {
type Item = CAAResult<'a>;
fn next(&mut self) -> Option<Self::Item> {
let opt_reply = self.next;
self.next = opt_reply.and_then(|reply| unsafe { reply.next.as_ref() });
opt_reply.map(|reply| CAAResult { caa_reply: reply })
}
}
impl<'a> IntoIterator for &'a CAAResults {
type Item = CAAResult<'a>;
type IntoIter = CAAResultsIter<'a>;
fn into_iter(self) -> Self::IntoIter {
self.iter()
}
}
impl Drop for CAAResults {
fn drop(&mut self) {
unsafe {
c_ares_sys::ares_free_data(self.caa_reply as *mut c_void);
}
}
}
unsafe impl Send for CAAResults {}
unsafe impl Sync for CAAResults {}
unsafe impl<'a> Send for CAAResult<'a> {}
unsafe impl<'a> Sync for CAAResult<'a> {}
unsafe impl<'a> Send for CAAResultsIter<'a> {}
unsafe impl<'a> Sync for CAAResultsIter<'a> {}
impl<'a> CAAResult<'a> {
/// Is the 'critical' flag set in this `CAAResult`?
pub fn critical(self) -> bool {
self.caa_reply.critical!= 0
}
/// The property represented by this `CAAResult`.
///
/// In practice this is very likely to be a valid UTF-8 string, but the underlying `c-ares`
/// library does not guarantee this - so we leave it to users to decide whether they prefer a
/// fallible conversion, a lossy conversion, or something else altogether.
pub fn property(self) -> &'a CStr {
unsafe { CStr::from_ptr(self.caa_reply.property as *const c_char) }
}
/// The value represented by this `CAAResult`.
///
/// In practice this is very likely to be a valid UTF-8 string, but the underlying `c-ares`
/// library does not guarantee this - so we leave it to users to decide whether they prefer a
/// fallible conversion, a lossy conversion, or something else altogether.
pub fn value(self) -> &'a CStr {
unsafe { CStr::from_ptr(self.caa_reply.value as *const c_char) }
}
}
impl<'a> fmt::Display for CAAResult<'a> {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
write!(fmt, "Critical: {}, ", self.critical())?;
write!(
fmt,
"Property: {}, ",
self.property().to_str().unwrap_or("<not utf8>")
)?;
write!(
fmt,
"Value: {}",
self.value().to_str().unwrap_or("<not utf8>")
)
}
}
pub(crate) unsafe extern "C" fn query_caa_callback<F>(
arg: *mut c_void,
status: c_int,
_timeouts: c_int,
abuf: *mut c_uchar,
alen: c_int,
) where
F: FnOnce(Result<CAAResults>) + Send +'static,
{
ares_callback!(arg as *mut F, status, abuf, alen, CAAResults::parse_from);
}
|
new
|
identifier_name
|
caa.rs
|
use std::ffi::CStr;
use std::fmt;
use std::marker::PhantomData;
use std::os::raw::{c_char, c_int, c_uchar, c_void};
use std::ptr;
use std::slice;
use itertools::Itertools;
use crate::error::{Error, Result};
use crate::panic;
/// The result of a successful CAA lookup.
#[derive(Debug)]
pub struct CAAResults {
caa_reply: *mut c_ares_sys::ares_caa_reply,
phantom: PhantomData<c_ares_sys::ares_caa_reply>,
}
/// The contents of a single CAA record.
#[derive(Clone, Copy)]
pub struct CAAResult<'a> {
// A single result - reference into a `CAAResults`.
caa_reply: &'a c_ares_sys::ares_caa_reply,
}
impl CAAResults {
/// Obtain a `CAAResults` from the response to a CAA lookup.
pub fn parse_from(data: &[u8]) -> Result<CAAResults> {
let mut caa_reply: *mut c_ares_sys::ares_caa_reply = ptr::null_mut();
let parse_status = unsafe {
c_ares_sys::ares_parse_caa_reply(data.as_ptr(), data.len() as c_int, &mut caa_reply)
};
if parse_status == c_ares_sys::ARES_SUCCESS
|
else {
Err(Error::from(parse_status))
}
}
fn new(caa_reply: *mut c_ares_sys::ares_caa_reply) -> Self {
CAAResults {
caa_reply,
phantom: PhantomData,
}
}
/// Returns an iterator over the `CAAResult` values in this `CAAResults`.
pub fn iter(&self) -> CAAResultsIter {
CAAResultsIter {
next: unsafe { self.caa_reply.as_ref() },
}
}
}
impl fmt::Display for CAAResults {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
let results = self.iter().format("}, {");
write!(fmt, "[{{{}}}]", results)
}
}
/// Iterator of `CAAResult`s.
#[derive(Clone, Copy)]
pub struct CAAResultsIter<'a> {
next: Option<&'a c_ares_sys::ares_caa_reply>,
}
impl<'a> Iterator for CAAResultsIter<'a> {
type Item = CAAResult<'a>;
fn next(&mut self) -> Option<Self::Item> {
let opt_reply = self.next;
self.next = opt_reply.and_then(|reply| unsafe { reply.next.as_ref() });
opt_reply.map(|reply| CAAResult { caa_reply: reply })
}
}
impl<'a> IntoIterator for &'a CAAResults {
type Item = CAAResult<'a>;
type IntoIter = CAAResultsIter<'a>;
fn into_iter(self) -> Self::IntoIter {
self.iter()
}
}
impl Drop for CAAResults {
fn drop(&mut self) {
unsafe {
c_ares_sys::ares_free_data(self.caa_reply as *mut c_void);
}
}
}
unsafe impl Send for CAAResults {}
unsafe impl Sync for CAAResults {}
unsafe impl<'a> Send for CAAResult<'a> {}
unsafe impl<'a> Sync for CAAResult<'a> {}
unsafe impl<'a> Send for CAAResultsIter<'a> {}
unsafe impl<'a> Sync for CAAResultsIter<'a> {}
impl<'a> CAAResult<'a> {
/// Is the 'critical' flag set in this `CAAResult`?
pub fn critical(self) -> bool {
self.caa_reply.critical!= 0
}
/// The property represented by this `CAAResult`.
///
/// In practice this is very likely to be a valid UTF-8 string, but the underlying `c-ares`
/// library does not guarantee this - so we leave it to users to decide whether they prefer a
/// fallible conversion, a lossy conversion, or something else altogether.
pub fn property(self) -> &'a CStr {
unsafe { CStr::from_ptr(self.caa_reply.property as *const c_char) }
}
/// The value represented by this `CAAResult`.
///
/// In practice this is very likely to be a valid UTF-8 string, but the underlying `c-ares`
/// library does not guarantee this - so we leave it to users to decide whether they prefer a
/// fallible conversion, a lossy conversion, or something else altogether.
pub fn value(self) -> &'a CStr {
unsafe { CStr::from_ptr(self.caa_reply.value as *const c_char) }
}
}
impl<'a> fmt::Display for CAAResult<'a> {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
write!(fmt, "Critical: {}, ", self.critical())?;
write!(
fmt,
"Property: {}, ",
self.property().to_str().unwrap_or("<not utf8>")
)?;
write!(
fmt,
"Value: {}",
self.value().to_str().unwrap_or("<not utf8>")
)
}
}
pub(crate) unsafe extern "C" fn query_caa_callback<F>(
arg: *mut c_void,
status: c_int,
_timeouts: c_int,
abuf: *mut c_uchar,
alen: c_int,
) where
F: FnOnce(Result<CAAResults>) + Send +'static,
{
ares_callback!(arg as *mut F, status, abuf, alen, CAAResults::parse_from);
}
|
{
let caa_result = CAAResults::new(caa_reply);
Ok(caa_result)
}
|
conditional_block
|
caa.rs
|
use std::ffi::CStr;
use std::fmt;
use std::marker::PhantomData;
use std::os::raw::{c_char, c_int, c_uchar, c_void};
use std::ptr;
use std::slice;
use itertools::Itertools;
use crate::error::{Error, Result};
use crate::panic;
/// The result of a successful CAA lookup.
#[derive(Debug)]
pub struct CAAResults {
caa_reply: *mut c_ares_sys::ares_caa_reply,
phantom: PhantomData<c_ares_sys::ares_caa_reply>,
}
/// The contents of a single CAA record.
#[derive(Clone, Copy)]
pub struct CAAResult<'a> {
// A single result - reference into a `CAAResults`.
caa_reply: &'a c_ares_sys::ares_caa_reply,
}
impl CAAResults {
/// Obtain a `CAAResults` from the response to a CAA lookup.
pub fn parse_from(data: &[u8]) -> Result<CAAResults> {
let mut caa_reply: *mut c_ares_sys::ares_caa_reply = ptr::null_mut();
let parse_status = unsafe {
c_ares_sys::ares_parse_caa_reply(data.as_ptr(), data.len() as c_int, &mut caa_reply)
};
if parse_status == c_ares_sys::ARES_SUCCESS {
let caa_result = CAAResults::new(caa_reply);
Ok(caa_result)
} else {
Err(Error::from(parse_status))
}
}
fn new(caa_reply: *mut c_ares_sys::ares_caa_reply) -> Self {
CAAResults {
caa_reply,
phantom: PhantomData,
}
}
/// Returns an iterator over the `CAAResult` values in this `CAAResults`.
pub fn iter(&self) -> CAAResultsIter {
CAAResultsIter {
next: unsafe { self.caa_reply.as_ref() },
}
}
}
impl fmt::Display for CAAResults {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
|
/// Iterator of `CAAResult`s.
#[derive(Clone, Copy)]
pub struct CAAResultsIter<'a> {
next: Option<&'a c_ares_sys::ares_caa_reply>,
}
impl<'a> Iterator for CAAResultsIter<'a> {
type Item = CAAResult<'a>;
fn next(&mut self) -> Option<Self::Item> {
let opt_reply = self.next;
self.next = opt_reply.and_then(|reply| unsafe { reply.next.as_ref() });
opt_reply.map(|reply| CAAResult { caa_reply: reply })
}
}
impl<'a> IntoIterator for &'a CAAResults {
type Item = CAAResult<'a>;
type IntoIter = CAAResultsIter<'a>;
fn into_iter(self) -> Self::IntoIter {
self.iter()
}
}
impl Drop for CAAResults {
fn drop(&mut self) {
unsafe {
c_ares_sys::ares_free_data(self.caa_reply as *mut c_void);
}
}
}
unsafe impl Send for CAAResults {}
unsafe impl Sync for CAAResults {}
unsafe impl<'a> Send for CAAResult<'a> {}
unsafe impl<'a> Sync for CAAResult<'a> {}
unsafe impl<'a> Send for CAAResultsIter<'a> {}
unsafe impl<'a> Sync for CAAResultsIter<'a> {}
impl<'a> CAAResult<'a> {
/// Is the 'critical' flag set in this `CAAResult`?
pub fn critical(self) -> bool {
self.caa_reply.critical!= 0
}
/// The property represented by this `CAAResult`.
///
/// In practice this is very likely to be a valid UTF-8 string, but the underlying `c-ares`
/// library does not guarantee this - so we leave it to users to decide whether they prefer a
/// fallible conversion, a lossy conversion, or something else altogether.
pub fn property(self) -> &'a CStr {
unsafe { CStr::from_ptr(self.caa_reply.property as *const c_char) }
}
/// The value represented by this `CAAResult`.
///
/// In practice this is very likely to be a valid UTF-8 string, but the underlying `c-ares`
/// library does not guarantee this - so we leave it to users to decide whether they prefer a
/// fallible conversion, a lossy conversion, or something else altogether.
pub fn value(self) -> &'a CStr {
unsafe { CStr::from_ptr(self.caa_reply.value as *const c_char) }
}
}
impl<'a> fmt::Display for CAAResult<'a> {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
write!(fmt, "Critical: {}, ", self.critical())?;
write!(
fmt,
"Property: {}, ",
self.property().to_str().unwrap_or("<not utf8>")
)?;
write!(
fmt,
"Value: {}",
self.value().to_str().unwrap_or("<not utf8>")
)
}
}
pub(crate) unsafe extern "C" fn query_caa_callback<F>(
arg: *mut c_void,
status: c_int,
_timeouts: c_int,
abuf: *mut c_uchar,
alen: c_int,
) where
F: FnOnce(Result<CAAResults>) + Send +'static,
{
ares_callback!(arg as *mut F, status, abuf, alen, CAAResults::parse_from);
}
|
let results = self.iter().format("}, {");
write!(fmt, "[{{{}}}]", results)
}
}
|
random_line_split
|
batch.rs
|
use snowchains::app::{App, Modify, Opt};
use snowchains::errors::{JudgeError, JudgeErrorKind};
use snowchains::path::AbsPathBuf;
use snowchains::service::ServiceName;
use snowchains::terminal::{AnsiColorChoice, Term, TermImpl};
use snowchains::testsuite::SuiteFileExtension;
use failure::Fallible;
use if_chain::if_chain;
use tempdir::TempDir;
use std::path::Path;
use std::time::Duration;
#[test]
fn it_works_for_atcoder_practice_a() -> Fallible<()> {
static SUITE: &str = r#"---
type: batch
match: exact
cases:
- name: Sample 1
in: |
1
2 3
test
out: |
6 test
- name: Sample 2
in: |
72
128 256
myonmyon
out: |
456 myonmyon
"#;
static CODE: &str = r#"use std::io::{self, Read};
fn main() {
let mut input = "".to_owned();
io::stdin().read_to_string(&mut input).unwrap();
let mut input = input.split(char::is_whitespace);
let a = input.next().unwrap().parse::<u32>().unwrap();
let b = input.next().unwrap().parse::<u32>().unwrap();
let c = input.next().unwrap().parse::<u32>().unwrap();
let s = input.next().unwrap();
println!("{} {}", a + b + c, s);
}
"#;
static INVLID_CODE: &str = "print('Hello!')";
static WRONG_CODE: &str = "fn main() {}";
static FREEZING_CODE: &str = r#"use std::thread;
use std::time::Duration;
fn main() {
thread::sleep(Duration::from_secs(10));
}
"#;
let _ = env_logger::try_init();
let tempdir = TempDir::new("batch_it_works")?;
let dir = tempdir.path().join("atcoder").join("practice");
let src_dir = dir.join("rs").join("src").join("bin");
let src_path = src_dir.join("a.rs");
let suite_dir = dir.join("tests");
let suite_path = suite_dir.join("a.yaml");
std::fs::write(
tempdir.path().join("snowchains.yaml"),
include_bytes!("./snowchains.yaml").as_ref(),
)?;
std::fs::create_dir_all(&src_dir)?;
std::fs::create_dir_all(&suite_dir)?;
std::fs::write(&suite_path, SUITE)?;
let mut app = App {
working_dir: AbsPathBuf::try_new(tempdir.path()).unwrap(),
login_retries: Some(0),
term: TermImpl::null(),
};
|
if let JudgeErrorKind::Build {.. } = ctx.get_context();
then {} else { return Err(err.into()) }
}
if_chain! {
let err = app.test(&src_path, WRONG_CODE).unwrap_err();
if let snowchains::Error::Judge(JudgeError::Context(ctx)) = &err;
if let JudgeErrorKind::TestFailed(2, 2) = ctx.get_context();
then {} else { return Err(err.into()) }
}
app.modify_timelimit(Duration::from_millis(100))?;
if_chain! {
let err = app.test(&src_path, FREEZING_CODE).unwrap_err();
if let snowchains::Error::Judge(JudgeError::Context(ctx)) = &err;
if let JudgeErrorKind::TestFailed(2, 2) = ctx.get_context();
then { Ok(()) } else { Err(err.into()) }
}
}
trait AppExt {
fn test(&mut self, src_path: &Path, code: &str) -> snowchains::Result<()>;
fn modify_timelimit(&mut self, timelimit: Duration) -> snowchains::Result<()>;
}
impl<T: Term> AppExt for App<T> {
fn test(&mut self, src_path: &Path, code: &str) -> snowchains::Result<()> {
std::fs::write(src_path, code)?;
self.run(Opt::Judge {
force_compile: false,
service: Some(ServiceName::Atcoder),
contest: Some("practice".to_owned()),
language: Some("rust".to_owned()),
jobs: None,
color_choice: AnsiColorChoice::Never,
problem: "a".to_owned(),
})
}
fn modify_timelimit(&mut self, timelimit: Duration) -> snowchains::Result<()> {
self.run(Opt::Modify(Modify::Timelimit {
service: Some(ServiceName::Atcoder),
contest: Some("practice".to_owned()),
color_choice: AnsiColorChoice::Never,
problem: "a".to_owned(),
extension: SuiteFileExtension::Yaml,
timelimit: Some(timelimit),
}))
}
}
|
app.test(&src_path, CODE)?;
if_chain! {
let err = app.test(&src_path, INVLID_CODE).unwrap_err();
if let snowchains::Error::Judge(JudgeError::Context(ctx)) = &err;
|
random_line_split
|
batch.rs
|
use snowchains::app::{App, Modify, Opt};
use snowchains::errors::{JudgeError, JudgeErrorKind};
use snowchains::path::AbsPathBuf;
use snowchains::service::ServiceName;
use snowchains::terminal::{AnsiColorChoice, Term, TermImpl};
use snowchains::testsuite::SuiteFileExtension;
use failure::Fallible;
use if_chain::if_chain;
use tempdir::TempDir;
use std::path::Path;
use std::time::Duration;
#[test]
fn it_works_for_atcoder_practice_a() -> Fallible<()> {
static SUITE: &str = r#"---
type: batch
match: exact
cases:
- name: Sample 1
in: |
1
2 3
test
out: |
6 test
- name: Sample 2
in: |
72
128 256
myonmyon
out: |
456 myonmyon
"#;
static CODE: &str = r#"use std::io::{self, Read};
fn main() {
let mut input = "".to_owned();
io::stdin().read_to_string(&mut input).unwrap();
let mut input = input.split(char::is_whitespace);
let a = input.next().unwrap().parse::<u32>().unwrap();
let b = input.next().unwrap().parse::<u32>().unwrap();
let c = input.next().unwrap().parse::<u32>().unwrap();
let s = input.next().unwrap();
println!("{} {}", a + b + c, s);
}
"#;
static INVLID_CODE: &str = "print('Hello!')";
static WRONG_CODE: &str = "fn main() {}";
static FREEZING_CODE: &str = r#"use std::thread;
use std::time::Duration;
fn main() {
thread::sleep(Duration::from_secs(10));
}
"#;
let _ = env_logger::try_init();
let tempdir = TempDir::new("batch_it_works")?;
let dir = tempdir.path().join("atcoder").join("practice");
let src_dir = dir.join("rs").join("src").join("bin");
let src_path = src_dir.join("a.rs");
let suite_dir = dir.join("tests");
let suite_path = suite_dir.join("a.yaml");
std::fs::write(
tempdir.path().join("snowchains.yaml"),
include_bytes!("./snowchains.yaml").as_ref(),
)?;
std::fs::create_dir_all(&src_dir)?;
std::fs::create_dir_all(&suite_dir)?;
std::fs::write(&suite_path, SUITE)?;
let mut app = App {
working_dir: AbsPathBuf::try_new(tempdir.path()).unwrap(),
login_retries: Some(0),
term: TermImpl::null(),
};
app.test(&src_path, CODE)?;
if_chain! {
let err = app.test(&src_path, INVLID_CODE).unwrap_err();
if let snowchains::Error::Judge(JudgeError::Context(ctx)) = &err;
if let JudgeErrorKind::Build {.. } = ctx.get_context();
then {} else { return Err(err.into()) }
}
if_chain! {
let err = app.test(&src_path, WRONG_CODE).unwrap_err();
if let snowchains::Error::Judge(JudgeError::Context(ctx)) = &err;
if let JudgeErrorKind::TestFailed(2, 2) = ctx.get_context();
then {} else { return Err(err.into()) }
}
app.modify_timelimit(Duration::from_millis(100))?;
if_chain! {
let err = app.test(&src_path, FREEZING_CODE).unwrap_err();
if let snowchains::Error::Judge(JudgeError::Context(ctx)) = &err;
if let JudgeErrorKind::TestFailed(2, 2) = ctx.get_context();
then { Ok(()) } else { Err(err.into()) }
}
}
trait AppExt {
fn test(&mut self, src_path: &Path, code: &str) -> snowchains::Result<()>;
fn modify_timelimit(&mut self, timelimit: Duration) -> snowchains::Result<()>;
}
impl<T: Term> AppExt for App<T> {
fn test(&mut self, src_path: &Path, code: &str) -> snowchains::Result<()> {
std::fs::write(src_path, code)?;
self.run(Opt::Judge {
force_compile: false,
service: Some(ServiceName::Atcoder),
contest: Some("practice".to_owned()),
language: Some("rust".to_owned()),
jobs: None,
color_choice: AnsiColorChoice::Never,
problem: "a".to_owned(),
})
}
fn
|
(&mut self, timelimit: Duration) -> snowchains::Result<()> {
self.run(Opt::Modify(Modify::Timelimit {
service: Some(ServiceName::Atcoder),
contest: Some("practice".to_owned()),
color_choice: AnsiColorChoice::Never,
problem: "a".to_owned(),
extension: SuiteFileExtension::Yaml,
timelimit: Some(timelimit),
}))
}
}
|
modify_timelimit
|
identifier_name
|
batch.rs
|
use snowchains::app::{App, Modify, Opt};
use snowchains::errors::{JudgeError, JudgeErrorKind};
use snowchains::path::AbsPathBuf;
use snowchains::service::ServiceName;
use snowchains::terminal::{AnsiColorChoice, Term, TermImpl};
use snowchains::testsuite::SuiteFileExtension;
use failure::Fallible;
use if_chain::if_chain;
use tempdir::TempDir;
use std::path::Path;
use std::time::Duration;
#[test]
fn it_works_for_atcoder_practice_a() -> Fallible<()> {
static SUITE: &str = r#"---
type: batch
match: exact
cases:
- name: Sample 1
in: |
1
2 3
test
out: |
6 test
- name: Sample 2
in: |
72
128 256
myonmyon
out: |
456 myonmyon
"#;
static CODE: &str = r#"use std::io::{self, Read};
fn main() {
let mut input = "".to_owned();
io::stdin().read_to_string(&mut input).unwrap();
let mut input = input.split(char::is_whitespace);
let a = input.next().unwrap().parse::<u32>().unwrap();
let b = input.next().unwrap().parse::<u32>().unwrap();
let c = input.next().unwrap().parse::<u32>().unwrap();
let s = input.next().unwrap();
println!("{} {}", a + b + c, s);
}
"#;
static INVLID_CODE: &str = "print('Hello!')";
static WRONG_CODE: &str = "fn main() {}";
static FREEZING_CODE: &str = r#"use std::thread;
use std::time::Duration;
fn main() {
thread::sleep(Duration::from_secs(10));
}
"#;
let _ = env_logger::try_init();
let tempdir = TempDir::new("batch_it_works")?;
let dir = tempdir.path().join("atcoder").join("practice");
let src_dir = dir.join("rs").join("src").join("bin");
let src_path = src_dir.join("a.rs");
let suite_dir = dir.join("tests");
let suite_path = suite_dir.join("a.yaml");
std::fs::write(
tempdir.path().join("snowchains.yaml"),
include_bytes!("./snowchains.yaml").as_ref(),
)?;
std::fs::create_dir_all(&src_dir)?;
std::fs::create_dir_all(&suite_dir)?;
std::fs::write(&suite_path, SUITE)?;
let mut app = App {
working_dir: AbsPathBuf::try_new(tempdir.path()).unwrap(),
login_retries: Some(0),
term: TermImpl::null(),
};
app.test(&src_path, CODE)?;
if_chain! {
let err = app.test(&src_path, INVLID_CODE).unwrap_err();
if let snowchains::Error::Judge(JudgeError::Context(ctx)) = &err;
if let JudgeErrorKind::Build {.. } = ctx.get_context();
then {} else { return Err(err.into()) }
}
if_chain! {
let err = app.test(&src_path, WRONG_CODE).unwrap_err();
if let snowchains::Error::Judge(JudgeError::Context(ctx)) = &err;
if let JudgeErrorKind::TestFailed(2, 2) = ctx.get_context();
then {} else { return Err(err.into()) }
}
app.modify_timelimit(Duration::from_millis(100))?;
if_chain! {
let err = app.test(&src_path, FREEZING_CODE).unwrap_err();
if let snowchains::Error::Judge(JudgeError::Context(ctx)) = &err;
if let JudgeErrorKind::TestFailed(2, 2) = ctx.get_context();
then { Ok(()) } else { Err(err.into()) }
}
}
trait AppExt {
fn test(&mut self, src_path: &Path, code: &str) -> snowchains::Result<()>;
fn modify_timelimit(&mut self, timelimit: Duration) -> snowchains::Result<()>;
}
impl<T: Term> AppExt for App<T> {
fn test(&mut self, src_path: &Path, code: &str) -> snowchains::Result<()> {
std::fs::write(src_path, code)?;
self.run(Opt::Judge {
force_compile: false,
service: Some(ServiceName::Atcoder),
contest: Some("practice".to_owned()),
language: Some("rust".to_owned()),
jobs: None,
color_choice: AnsiColorChoice::Never,
problem: "a".to_owned(),
})
}
fn modify_timelimit(&mut self, timelimit: Duration) -> snowchains::Result<()>
|
}
|
{
self.run(Opt::Modify(Modify::Timelimit {
service: Some(ServiceName::Atcoder),
contest: Some("practice".to_owned()),
color_choice: AnsiColorChoice::Never,
problem: "a".to_owned(),
extension: SuiteFileExtension::Yaml,
timelimit: Some(timelimit),
}))
}
|
identifier_body
|
tooltip.rs
|
// This file was generated by gir (b7f5189) from gir-files (71d73f0)
// DO NOT EDIT
use Widget;
use ffi;
use gdk;
use gdk_pixbuf;
use glib::object::IsA;
use glib::translate::*;
glib_wrapper! {
pub struct Tooltip(Object<ffi::GtkTooltip>);
match fn {
get_type => || ffi::gtk_tooltip_get_type(),
}
}
impl Tooltip {
pub fn set_custom<T: IsA<Widget>>(&self, custom_widget: Option<&T>) {
unsafe {
ffi::gtk_tooltip_set_custom(self.to_glib_none().0, custom_widget.to_glib_none().0);
}
}
pub fn set_icon(&self, pixbuf: Option<&gdk_pixbuf::Pixbuf>) {
unsafe {
ffi::gtk_tooltip_set_icon(self.to_glib_none().0, pixbuf.to_glib_none().0);
}
}
//pub fn set_icon_from_gicon<T: IsA</*Ignored*/gio::Icon>>(&self, gicon: Option<&T>, size: i32) {
// unsafe { TODO: call ffi::gtk_tooltip_set_icon_from_gicon() }
//}
pub fn set_icon_from_icon_name<'a, T: Into<Option<&'a str>>>(&self, icon_name: T, size: i32) {
unsafe {
ffi::gtk_tooltip_set_icon_from_icon_name(self.to_glib_none().0, icon_name.into().to_glib_none().0, size);
}
}
pub fn set_icon_from_stock<'a, T: Into<Option<&'a str>>>(&self, stock_id: T, size: i32) {
unsafe {
ffi::gtk_tooltip_set_icon_from_stock(self.to_glib_none().0, stock_id.into().to_glib_none().0, size);
}
}
pub fn set_markup<'a, T: Into<Option<&'a str>>>(&self, markup: T) {
unsafe {
ffi::gtk_tooltip_set_markup(self.to_glib_none().0, markup.into().to_glib_none().0);
}
}
pub fn
|
<'a, T: Into<Option<&'a str>>>(&self, text: T) {
unsafe {
ffi::gtk_tooltip_set_text(self.to_glib_none().0, text.into().to_glib_none().0);
}
}
pub fn set_tip_area(&self, rect: &gdk::Rectangle) {
unsafe {
ffi::gtk_tooltip_set_tip_area(self.to_glib_none().0, rect.to_glib_none().0);
}
}
pub fn trigger_tooltip_query(display: &gdk::Display) {
assert_initialized_main_thread!();
unsafe {
ffi::gtk_tooltip_trigger_tooltip_query(display.to_glib_none().0);
}
}
}
|
set_text
|
identifier_name
|
tooltip.rs
|
// This file was generated by gir (b7f5189) from gir-files (71d73f0)
// DO NOT EDIT
use Widget;
use ffi;
use gdk;
use gdk_pixbuf;
use glib::object::IsA;
use glib::translate::*;
glib_wrapper! {
pub struct Tooltip(Object<ffi::GtkTooltip>);
match fn {
get_type => || ffi::gtk_tooltip_get_type(),
}
}
impl Tooltip {
pub fn set_custom<T: IsA<Widget>>(&self, custom_widget: Option<&T>) {
unsafe {
ffi::gtk_tooltip_set_custom(self.to_glib_none().0, custom_widget.to_glib_none().0);
}
}
pub fn set_icon(&self, pixbuf: Option<&gdk_pixbuf::Pixbuf>) {
unsafe {
ffi::gtk_tooltip_set_icon(self.to_glib_none().0, pixbuf.to_glib_none().0);
}
}
//pub fn set_icon_from_gicon<T: IsA</*Ignored*/gio::Icon>>(&self, gicon: Option<&T>, size: i32) {
// unsafe { TODO: call ffi::gtk_tooltip_set_icon_from_gicon() }
//}
pub fn set_icon_from_icon_name<'a, T: Into<Option<&'a str>>>(&self, icon_name: T, size: i32) {
unsafe {
ffi::gtk_tooltip_set_icon_from_icon_name(self.to_glib_none().0, icon_name.into().to_glib_none().0, size);
}
}
pub fn set_icon_from_stock<'a, T: Into<Option<&'a str>>>(&self, stock_id: T, size: i32) {
unsafe {
ffi::gtk_tooltip_set_icon_from_stock(self.to_glib_none().0, stock_id.into().to_glib_none().0, size);
}
}
pub fn set_markup<'a, T: Into<Option<&'a str>>>(&self, markup: T)
|
pub fn set_text<'a, T: Into<Option<&'a str>>>(&self, text: T) {
unsafe {
ffi::gtk_tooltip_set_text(self.to_glib_none().0, text.into().to_glib_none().0);
}
}
pub fn set_tip_area(&self, rect: &gdk::Rectangle) {
unsafe {
ffi::gtk_tooltip_set_tip_area(self.to_glib_none().0, rect.to_glib_none().0);
}
}
pub fn trigger_tooltip_query(display: &gdk::Display) {
assert_initialized_main_thread!();
unsafe {
ffi::gtk_tooltip_trigger_tooltip_query(display.to_glib_none().0);
}
}
}
|
{
unsafe {
ffi::gtk_tooltip_set_markup(self.to_glib_none().0, markup.into().to_glib_none().0);
}
}
|
identifier_body
|
tooltip.rs
|
// This file was generated by gir (b7f5189) from gir-files (71d73f0)
// DO NOT EDIT
use Widget;
use ffi;
use gdk;
use gdk_pixbuf;
use glib::object::IsA;
use glib::translate::*;
glib_wrapper! {
pub struct Tooltip(Object<ffi::GtkTooltip>);
match fn {
get_type => || ffi::gtk_tooltip_get_type(),
}
}
impl Tooltip {
pub fn set_custom<T: IsA<Widget>>(&self, custom_widget: Option<&T>) {
unsafe {
ffi::gtk_tooltip_set_custom(self.to_glib_none().0, custom_widget.to_glib_none().0);
}
}
pub fn set_icon(&self, pixbuf: Option<&gdk_pixbuf::Pixbuf>) {
unsafe {
ffi::gtk_tooltip_set_icon(self.to_glib_none().0, pixbuf.to_glib_none().0);
}
}
//pub fn set_icon_from_gicon<T: IsA</*Ignored*/gio::Icon>>(&self, gicon: Option<&T>, size: i32) {
// unsafe { TODO: call ffi::gtk_tooltip_set_icon_from_gicon() }
//}
pub fn set_icon_from_icon_name<'a, T: Into<Option<&'a str>>>(&self, icon_name: T, size: i32) {
unsafe {
ffi::gtk_tooltip_set_icon_from_icon_name(self.to_glib_none().0, icon_name.into().to_glib_none().0, size);
}
}
pub fn set_icon_from_stock<'a, T: Into<Option<&'a str>>>(&self, stock_id: T, size: i32) {
unsafe {
ffi::gtk_tooltip_set_icon_from_stock(self.to_glib_none().0, stock_id.into().to_glib_none().0, size);
}
}
pub fn set_markup<'a, T: Into<Option<&'a str>>>(&self, markup: T) {
unsafe {
ffi::gtk_tooltip_set_markup(self.to_glib_none().0, markup.into().to_glib_none().0);
}
}
|
}
}
pub fn set_tip_area(&self, rect: &gdk::Rectangle) {
unsafe {
ffi::gtk_tooltip_set_tip_area(self.to_glib_none().0, rect.to_glib_none().0);
}
}
pub fn trigger_tooltip_query(display: &gdk::Display) {
assert_initialized_main_thread!();
unsafe {
ffi::gtk_tooltip_trigger_tooltip_query(display.to_glib_none().0);
}
}
}
|
pub fn set_text<'a, T: Into<Option<&'a str>>>(&self, text: T) {
unsafe {
ffi::gtk_tooltip_set_text(self.to_glib_none().0, text.into().to_glib_none().0);
|
random_line_split
|
system_clock_pt.rs
|
// Zinc, the bare metal stack for rust.
// Copyright 2014 Vladimir "farcaller" Pouzanov <[email protected]>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::rc::Rc;
use syntax::ext::base::ExtCtxt;
use syntax::ext::build::AstBuilder;
use builder::{Builder, TokenString};
use node;
pub fn attach(_: &mut Builder, _: &mut ExtCtxt, node: Rc<node::Node>) {
node.materializer.set(Some(build_clock));
}
fn build_clock(builder: &mut Builder, cx: &mut ExtCtxt,
node: Rc<node::Node>) {
if!node.expect_attributes(cx, [("source", node::StrAttribute)]) {
return;
}
let source = node.get_string_attr("source").unwrap();
let source_freq: uint;
let clock_source = TokenString(match source.as_slice() {
"internal-oscillator" => {
source_freq = 4_000_000;
"system_clock::Internal".to_string()
},
"rtc-oscillator" => {
source_freq = 32_000;
"system_clock::RTC".to_string()
},
"main-oscillator" => {
let some_source_frequency =
node.get_required_int_attr(cx, "source_frequency");
if some_source_frequency == None {
source_freq = 0;
"BAD".to_string()
} else {
|
},
other => {
source_freq = 0;
cx.span_err(
node.get_attr("source").value_span,
format!("unknown oscillator value `{}`", other).as_slice());
"BAD".to_string()
},
});
let some_pll_conf = node.get_by_path("pll").and_then(|sub|
-> Option<(uint, uint, uint)> {
if!sub.expect_no_subnodes(cx) ||!sub.expect_attributes(cx, [
("m", node::IntAttribute),
("n", node::IntAttribute),
("divisor", node::IntAttribute)]) {
None
} else {
let m = sub.get_int_attr("m").unwrap();
let n = sub.get_int_attr("n").unwrap();
let divisor = sub.get_int_attr("divisor").unwrap();
Some((m, n, divisor))
}
});
if some_pll_conf.is_none() {
cx.parse_sess().span_diagnostic.span_err(node.name_span,
"required subnode `pll` is missing");
return;
}
let (m, n, divisor) = some_pll_conf.unwrap();
let pll_m: u8 = m as u8;
let pll_n: u8 = n as u8;
let pll_divisor: u8 = divisor as u8;
let sysfreq = source_freq * 2 * pll_m as uint / pll_n as uint
/ pll_divisor as uint;
node.attributes.borrow_mut().insert("system_frequency".to_string(),
Rc::new(node::Attribute::new_nosp(node::IntValue(sysfreq))));
let ex = quote_expr!(&*cx,
{
use zinc::hal::lpc17xx::system_clock;
system_clock::init_clock(
&system_clock::Clock {
source: $clock_source,
pll: core::option::Some(system_clock::PLL0 {
m: $pll_m,
n: $pll_n,
divisor: $pll_divisor,
})
}
);
}
);
builder.add_main_statement(cx.stmt_expr(ex));
}
#[cfg(test)]
mod test {
use builder::Builder;
use test_helpers::{assert_equal_source, with_parsed, fails_to_build};
#[test]
fn builds_clock_init() {
with_parsed("
clock {
source = \"main-oscillator\";
source_frequency = 12_000_000;
pll {
m = 50;
n = 3;
divisor = 4;
}
}", |cx, failed, pt| {
let mut builder = Builder::new(pt.clone());
super::build_clock(&mut builder, cx, pt.get_by_path("clock").unwrap());
assert!(unsafe{*failed} == false);
assert!(builder.main_stmts().len() == 1);
assert_equal_source(builder.main_stmts()[0],
"{
use zinc::hal::lpc17xx::system_clock;
system_clock::init_clock(
&system_clock::Clock {
source: system_clock::Main(12000000),
pll: core::option::Some(system_clock::PLL0 {
m: 50u8,
n: 3u8,
divisor: 4u8,
}),
}
);
};");
});
}
#[test]
fn clock_provides_out_frequency() {
with_parsed("
clock {
source = \"main-oscillator\";
source_frequency = 12_000_000;
pll {
m = 50;
n = 3;
divisor = 4;
}
}", |cx, _, pt| {
let mut builder = Builder::new(pt.clone());
let node = pt.get_by_path("clock").unwrap();
super::build_clock(&mut builder, cx, node.clone());
let out_freq = node.get_int_attr("system_frequency");
assert!(out_freq.is_some());
assert!(out_freq.unwrap() == 100_000_000);
});
}
#[test]
fn fails_to_parse_bad_clock_conf() {
fails_to_build("lpc17xx@mcu { clock {
no_source = 1;
source_frequency = 12_000_000;
}}");
fails_to_build("lpc17xx@mcu { clock {
source = \"missing\";
source_frequency = 12_000_000;
}}");
}
#[test]
fn fails_to_parse_no_pll_clock() {
fails_to_build("lpc17xx@mcu { clock {
source = \"main-oscillator\";
source_frequency = 12_000_000;
}}");
}
}
|
source_freq = some_source_frequency.unwrap();
format!("system_clock::Main({})", source_freq)
}
|
random_line_split
|
system_clock_pt.rs
|
// Zinc, the bare metal stack for rust.
// Copyright 2014 Vladimir "farcaller" Pouzanov <[email protected]>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::rc::Rc;
use syntax::ext::base::ExtCtxt;
use syntax::ext::build::AstBuilder;
use builder::{Builder, TokenString};
use node;
pub fn attach(_: &mut Builder, _: &mut ExtCtxt, node: Rc<node::Node>) {
node.materializer.set(Some(build_clock));
}
fn build_clock(builder: &mut Builder, cx: &mut ExtCtxt,
node: Rc<node::Node>) {
if!node.expect_attributes(cx, [("source", node::StrAttribute)]) {
return;
}
let source = node.get_string_attr("source").unwrap();
let source_freq: uint;
let clock_source = TokenString(match source.as_slice() {
"internal-oscillator" => {
source_freq = 4_000_000;
"system_clock::Internal".to_string()
},
"rtc-oscillator" => {
source_freq = 32_000;
"system_clock::RTC".to_string()
},
"main-oscillator" => {
let some_source_frequency =
node.get_required_int_attr(cx, "source_frequency");
if some_source_frequency == None {
source_freq = 0;
"BAD".to_string()
} else {
source_freq = some_source_frequency.unwrap();
format!("system_clock::Main({})", source_freq)
}
},
other => {
source_freq = 0;
cx.span_err(
node.get_attr("source").value_span,
format!("unknown oscillator value `{}`", other).as_slice());
"BAD".to_string()
},
});
let some_pll_conf = node.get_by_path("pll").and_then(|sub|
-> Option<(uint, uint, uint)> {
if!sub.expect_no_subnodes(cx) ||!sub.expect_attributes(cx, [
("m", node::IntAttribute),
("n", node::IntAttribute),
("divisor", node::IntAttribute)]) {
None
} else {
let m = sub.get_int_attr("m").unwrap();
let n = sub.get_int_attr("n").unwrap();
let divisor = sub.get_int_attr("divisor").unwrap();
Some((m, n, divisor))
}
});
if some_pll_conf.is_none() {
cx.parse_sess().span_diagnostic.span_err(node.name_span,
"required subnode `pll` is missing");
return;
}
let (m, n, divisor) = some_pll_conf.unwrap();
let pll_m: u8 = m as u8;
let pll_n: u8 = n as u8;
let pll_divisor: u8 = divisor as u8;
let sysfreq = source_freq * 2 * pll_m as uint / pll_n as uint
/ pll_divisor as uint;
node.attributes.borrow_mut().insert("system_frequency".to_string(),
Rc::new(node::Attribute::new_nosp(node::IntValue(sysfreq))));
let ex = quote_expr!(&*cx,
{
use zinc::hal::lpc17xx::system_clock;
system_clock::init_clock(
&system_clock::Clock {
source: $clock_source,
pll: core::option::Some(system_clock::PLL0 {
m: $pll_m,
n: $pll_n,
divisor: $pll_divisor,
})
}
);
}
);
builder.add_main_statement(cx.stmt_expr(ex));
}
#[cfg(test)]
mod test {
use builder::Builder;
use test_helpers::{assert_equal_source, with_parsed, fails_to_build};
#[test]
fn builds_clock_init() {
with_parsed("
clock {
source = \"main-oscillator\";
source_frequency = 12_000_000;
pll {
m = 50;
n = 3;
divisor = 4;
}
}", |cx, failed, pt| {
let mut builder = Builder::new(pt.clone());
super::build_clock(&mut builder, cx, pt.get_by_path("clock").unwrap());
assert!(unsafe{*failed} == false);
assert!(builder.main_stmts().len() == 1);
assert_equal_source(builder.main_stmts()[0],
"{
use zinc::hal::lpc17xx::system_clock;
system_clock::init_clock(
&system_clock::Clock {
source: system_clock::Main(12000000),
pll: core::option::Some(system_clock::PLL0 {
m: 50u8,
n: 3u8,
divisor: 4u8,
}),
}
);
};");
});
}
#[test]
fn clock_provides_out_frequency()
|
#[test]
fn fails_to_parse_bad_clock_conf() {
fails_to_build("lpc17xx@mcu { clock {
no_source = 1;
source_frequency = 12_000_000;
}}");
fails_to_build("lpc17xx@mcu { clock {
source = \"missing\";
source_frequency = 12_000_000;
}}");
}
#[test]
fn fails_to_parse_no_pll_clock() {
fails_to_build("lpc17xx@mcu { clock {
source = \"main-oscillator\";
source_frequency = 12_000_000;
}}");
}
}
|
{
with_parsed("
clock {
source = \"main-oscillator\";
source_frequency = 12_000_000;
pll {
m = 50;
n = 3;
divisor = 4;
}
}", |cx, _, pt| {
let mut builder = Builder::new(pt.clone());
let node = pt.get_by_path("clock").unwrap();
super::build_clock(&mut builder, cx, node.clone());
let out_freq = node.get_int_attr("system_frequency");
assert!(out_freq.is_some());
assert!(out_freq.unwrap() == 100_000_000);
});
}
|
identifier_body
|
system_clock_pt.rs
|
// Zinc, the bare metal stack for rust.
// Copyright 2014 Vladimir "farcaller" Pouzanov <[email protected]>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::rc::Rc;
use syntax::ext::base::ExtCtxt;
use syntax::ext::build::AstBuilder;
use builder::{Builder, TokenString};
use node;
pub fn attach(_: &mut Builder, _: &mut ExtCtxt, node: Rc<node::Node>) {
node.materializer.set(Some(build_clock));
}
fn build_clock(builder: &mut Builder, cx: &mut ExtCtxt,
node: Rc<node::Node>) {
if!node.expect_attributes(cx, [("source", node::StrAttribute)]) {
return;
}
let source = node.get_string_attr("source").unwrap();
let source_freq: uint;
let clock_source = TokenString(match source.as_slice() {
"internal-oscillator" => {
source_freq = 4_000_000;
"system_clock::Internal".to_string()
},
"rtc-oscillator" => {
source_freq = 32_000;
"system_clock::RTC".to_string()
},
"main-oscillator" => {
let some_source_frequency =
node.get_required_int_attr(cx, "source_frequency");
if some_source_frequency == None {
source_freq = 0;
"BAD".to_string()
} else {
source_freq = some_source_frequency.unwrap();
format!("system_clock::Main({})", source_freq)
}
},
other => {
source_freq = 0;
cx.span_err(
node.get_attr("source").value_span,
format!("unknown oscillator value `{}`", other).as_slice());
"BAD".to_string()
},
});
let some_pll_conf = node.get_by_path("pll").and_then(|sub|
-> Option<(uint, uint, uint)> {
if!sub.expect_no_subnodes(cx) ||!sub.expect_attributes(cx, [
("m", node::IntAttribute),
("n", node::IntAttribute),
("divisor", node::IntAttribute)]) {
None
} else {
let m = sub.get_int_attr("m").unwrap();
let n = sub.get_int_attr("n").unwrap();
let divisor = sub.get_int_attr("divisor").unwrap();
Some((m, n, divisor))
}
});
if some_pll_conf.is_none() {
cx.parse_sess().span_diagnostic.span_err(node.name_span,
"required subnode `pll` is missing");
return;
}
let (m, n, divisor) = some_pll_conf.unwrap();
let pll_m: u8 = m as u8;
let pll_n: u8 = n as u8;
let pll_divisor: u8 = divisor as u8;
let sysfreq = source_freq * 2 * pll_m as uint / pll_n as uint
/ pll_divisor as uint;
node.attributes.borrow_mut().insert("system_frequency".to_string(),
Rc::new(node::Attribute::new_nosp(node::IntValue(sysfreq))));
let ex = quote_expr!(&*cx,
{
use zinc::hal::lpc17xx::system_clock;
system_clock::init_clock(
&system_clock::Clock {
source: $clock_source,
pll: core::option::Some(system_clock::PLL0 {
m: $pll_m,
n: $pll_n,
divisor: $pll_divisor,
})
}
);
}
);
builder.add_main_statement(cx.stmt_expr(ex));
}
#[cfg(test)]
mod test {
use builder::Builder;
use test_helpers::{assert_equal_source, with_parsed, fails_to_build};
#[test]
fn
|
() {
with_parsed("
clock {
source = \"main-oscillator\";
source_frequency = 12_000_000;
pll {
m = 50;
n = 3;
divisor = 4;
}
}", |cx, failed, pt| {
let mut builder = Builder::new(pt.clone());
super::build_clock(&mut builder, cx, pt.get_by_path("clock").unwrap());
assert!(unsafe{*failed} == false);
assert!(builder.main_stmts().len() == 1);
assert_equal_source(builder.main_stmts()[0],
"{
use zinc::hal::lpc17xx::system_clock;
system_clock::init_clock(
&system_clock::Clock {
source: system_clock::Main(12000000),
pll: core::option::Some(system_clock::PLL0 {
m: 50u8,
n: 3u8,
divisor: 4u8,
}),
}
);
};");
});
}
#[test]
fn clock_provides_out_frequency() {
with_parsed("
clock {
source = \"main-oscillator\";
source_frequency = 12_000_000;
pll {
m = 50;
n = 3;
divisor = 4;
}
}", |cx, _, pt| {
let mut builder = Builder::new(pt.clone());
let node = pt.get_by_path("clock").unwrap();
super::build_clock(&mut builder, cx, node.clone());
let out_freq = node.get_int_attr("system_frequency");
assert!(out_freq.is_some());
assert!(out_freq.unwrap() == 100_000_000);
});
}
#[test]
fn fails_to_parse_bad_clock_conf() {
fails_to_build("lpc17xx@mcu { clock {
no_source = 1;
source_frequency = 12_000_000;
}}");
fails_to_build("lpc17xx@mcu { clock {
source = \"missing\";
source_frequency = 12_000_000;
}}");
}
#[test]
fn fails_to_parse_no_pll_clock() {
fails_to_build("lpc17xx@mcu { clock {
source = \"main-oscillator\";
source_frequency = 12_000_000;
}}");
}
}
|
builds_clock_init
|
identifier_name
|
system_clock_pt.rs
|
// Zinc, the bare metal stack for rust.
// Copyright 2014 Vladimir "farcaller" Pouzanov <[email protected]>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::rc::Rc;
use syntax::ext::base::ExtCtxt;
use syntax::ext::build::AstBuilder;
use builder::{Builder, TokenString};
use node;
pub fn attach(_: &mut Builder, _: &mut ExtCtxt, node: Rc<node::Node>) {
node.materializer.set(Some(build_clock));
}
fn build_clock(builder: &mut Builder, cx: &mut ExtCtxt,
node: Rc<node::Node>) {
if!node.expect_attributes(cx, [("source", node::StrAttribute)]) {
return;
}
let source = node.get_string_attr("source").unwrap();
let source_freq: uint;
let clock_source = TokenString(match source.as_slice() {
"internal-oscillator" => {
source_freq = 4_000_000;
"system_clock::Internal".to_string()
},
"rtc-oscillator" => {
source_freq = 32_000;
"system_clock::RTC".to_string()
},
"main-oscillator" => {
let some_source_frequency =
node.get_required_int_attr(cx, "source_frequency");
if some_source_frequency == None {
source_freq = 0;
"BAD".to_string()
} else {
source_freq = some_source_frequency.unwrap();
format!("system_clock::Main({})", source_freq)
}
},
other => {
source_freq = 0;
cx.span_err(
node.get_attr("source").value_span,
format!("unknown oscillator value `{}`", other).as_slice());
"BAD".to_string()
},
});
let some_pll_conf = node.get_by_path("pll").and_then(|sub|
-> Option<(uint, uint, uint)> {
if!sub.expect_no_subnodes(cx) ||!sub.expect_attributes(cx, [
("m", node::IntAttribute),
("n", node::IntAttribute),
("divisor", node::IntAttribute)])
|
else {
let m = sub.get_int_attr("m").unwrap();
let n = sub.get_int_attr("n").unwrap();
let divisor = sub.get_int_attr("divisor").unwrap();
Some((m, n, divisor))
}
});
if some_pll_conf.is_none() {
cx.parse_sess().span_diagnostic.span_err(node.name_span,
"required subnode `pll` is missing");
return;
}
let (m, n, divisor) = some_pll_conf.unwrap();
let pll_m: u8 = m as u8;
let pll_n: u8 = n as u8;
let pll_divisor: u8 = divisor as u8;
let sysfreq = source_freq * 2 * pll_m as uint / pll_n as uint
/ pll_divisor as uint;
node.attributes.borrow_mut().insert("system_frequency".to_string(),
Rc::new(node::Attribute::new_nosp(node::IntValue(sysfreq))));
let ex = quote_expr!(&*cx,
{
use zinc::hal::lpc17xx::system_clock;
system_clock::init_clock(
&system_clock::Clock {
source: $clock_source,
pll: core::option::Some(system_clock::PLL0 {
m: $pll_m,
n: $pll_n,
divisor: $pll_divisor,
})
}
);
}
);
builder.add_main_statement(cx.stmt_expr(ex));
}
#[cfg(test)]
mod test {
use builder::Builder;
use test_helpers::{assert_equal_source, with_parsed, fails_to_build};
#[test]
fn builds_clock_init() {
with_parsed("
clock {
source = \"main-oscillator\";
source_frequency = 12_000_000;
pll {
m = 50;
n = 3;
divisor = 4;
}
}", |cx, failed, pt| {
let mut builder = Builder::new(pt.clone());
super::build_clock(&mut builder, cx, pt.get_by_path("clock").unwrap());
assert!(unsafe{*failed} == false);
assert!(builder.main_stmts().len() == 1);
assert_equal_source(builder.main_stmts()[0],
"{
use zinc::hal::lpc17xx::system_clock;
system_clock::init_clock(
&system_clock::Clock {
source: system_clock::Main(12000000),
pll: core::option::Some(system_clock::PLL0 {
m: 50u8,
n: 3u8,
divisor: 4u8,
}),
}
);
};");
});
}
#[test]
fn clock_provides_out_frequency() {
with_parsed("
clock {
source = \"main-oscillator\";
source_frequency = 12_000_000;
pll {
m = 50;
n = 3;
divisor = 4;
}
}", |cx, _, pt| {
let mut builder = Builder::new(pt.clone());
let node = pt.get_by_path("clock").unwrap();
super::build_clock(&mut builder, cx, node.clone());
let out_freq = node.get_int_attr("system_frequency");
assert!(out_freq.is_some());
assert!(out_freq.unwrap() == 100_000_000);
});
}
#[test]
fn fails_to_parse_bad_clock_conf() {
fails_to_build("lpc17xx@mcu { clock {
no_source = 1;
source_frequency = 12_000_000;
}}");
fails_to_build("lpc17xx@mcu { clock {
source = \"missing\";
source_frequency = 12_000_000;
}}");
}
#[test]
fn fails_to_parse_no_pll_clock() {
fails_to_build("lpc17xx@mcu { clock {
source = \"main-oscillator\";
source_frequency = 12_000_000;
}}");
}
}
|
{
None
}
|
conditional_block
|
build.rs
|
use std::env;
fn main() {
let target_os = env::var("CARGO_CFG_TARGET_OS").unwrap();
let weak_linkage = match env::var("CARGO_FEATURE_WEAK_LINKAGE") {
Ok(_) => true,
Err(_) => false,
};
if weak_linkage {
if target_os == "linux" {
println!("cargo:rustc-cdylib-link-arg=-Wl,-Bstatic");
println!("cargo:rustc-cdylib-link-arg=-lstdc++");
println!("cargo:rustc-cdylib-link-arg=-Wl,-Bdynamic");
} else if target_os == "macos" {
println!("cargo:rustc-cdylib-link-arg=-undefined");
println!("cargo:rustc-cdylib-link-arg=dynamic_lookup");
}
|
println!("cargo:rustc-cdylib-link-arg=-Wl,-rpath,{}/../lldb/lib", origin);
// Relative to target/debug/deps/ - for `cargo test`
println!("cargo:rustc-cdylib-link-arg=-Wl,-rpath,{}/../../../lldb/lib", origin);
}
}
}
|
} else {
if target_os == "linux" || target_os == "macos" {
#[rustfmt::skip]
let origin = if target_os == "linux" { "$ORIGIN" } else { "@loader_path" };
// Relative to adapter/
|
random_line_split
|
build.rs
|
use std::env;
fn
|
() {
let target_os = env::var("CARGO_CFG_TARGET_OS").unwrap();
let weak_linkage = match env::var("CARGO_FEATURE_WEAK_LINKAGE") {
Ok(_) => true,
Err(_) => false,
};
if weak_linkage {
if target_os == "linux" {
println!("cargo:rustc-cdylib-link-arg=-Wl,-Bstatic");
println!("cargo:rustc-cdylib-link-arg=-lstdc++");
println!("cargo:rustc-cdylib-link-arg=-Wl,-Bdynamic");
} else if target_os == "macos" {
println!("cargo:rustc-cdylib-link-arg=-undefined");
println!("cargo:rustc-cdylib-link-arg=dynamic_lookup");
}
} else {
if target_os == "linux" || target_os == "macos" {
#[rustfmt::skip]
let origin = if target_os == "linux" { "$ORIGIN" } else { "@loader_path" };
// Relative to adapter/
println!("cargo:rustc-cdylib-link-arg=-Wl,-rpath,{}/../lldb/lib", origin);
// Relative to target/debug/deps/ - for `cargo test`
println!("cargo:rustc-cdylib-link-arg=-Wl,-rpath,{}/../../../lldb/lib", origin);
}
}
}
|
main
|
identifier_name
|
build.rs
|
use std::env;
fn main()
|
// Relative to adapter/
println!("cargo:rustc-cdylib-link-arg=-Wl,-rpath,{}/../lldb/lib", origin);
// Relative to target/debug/deps/ - for `cargo test`
println!("cargo:rustc-cdylib-link-arg=-Wl,-rpath,{}/../../../lldb/lib", origin);
}
}
}
|
{
let target_os = env::var("CARGO_CFG_TARGET_OS").unwrap();
let weak_linkage = match env::var("CARGO_FEATURE_WEAK_LINKAGE") {
Ok(_) => true,
Err(_) => false,
};
if weak_linkage {
if target_os == "linux" {
println!("cargo:rustc-cdylib-link-arg=-Wl,-Bstatic");
println!("cargo:rustc-cdylib-link-arg=-lstdc++");
println!("cargo:rustc-cdylib-link-arg=-Wl,-Bdynamic");
} else if target_os == "macos" {
println!("cargo:rustc-cdylib-link-arg=-undefined");
println!("cargo:rustc-cdylib-link-arg=dynamic_lookup");
}
} else {
if target_os == "linux" || target_os == "macos" {
#[rustfmt::skip]
let origin = if target_os == "linux" { "$ORIGIN" } else { "@loader_path" };
|
identifier_body
|
main.rs
|
#![feature(iter_max_by, iter_min_by)]
use std::collections::HashMap;
use std::io;
use std::io::prelude::*;
enum DecodingMethod {
MostLikely,
LeastLikely,
}
fn decode_message(input: &str, method: DecodingMethod) -> String
|
}
}
.unwrap()
.0
})
.collect()
}
fn main() {
let mut message_str = String::new();
io::stdin().read_to_string(&mut message_str).expect("Invalid input string!");
println!("The initial decoded message is: {}",
decode_message(&message_str, DecodingMethod::MostLikely));
println!("The actual decoded message is: {}",
decode_message(&message_str, DecodingMethod::LeastLikely));
}
#[cfg(test)]
mod tests {
use super::decode_message;
use super::DecodingMethod;
const TEST_INPUT: &'static str = "eedadn\n\
drvtee\n\
eandsr\n\
raavrd\n\
atevrs\n\
tsrnev\n\
sdttsa\n\
rasrtv\n\
nssdts\n\
ntnada\n\
svetve\n\
tesnvt\n\
vntsnd\n\
vrdear\n\
dvrsen\n\
enarar";
#[test]
fn decode_message_test() {
assert_eq!(decode_message(TEST_INPUT, DecodingMethod::MostLikely),
"easter");
}
#[test]
fn decode_message_b_test() {
assert_eq!(decode_message(TEST_INPUT, DecodingMethod::LeastLikely),
"advent");
}
}
|
{
let len = input.lines().map(|line| line.chars().count()).max().unwrap();
let mut histograms = vec![HashMap::new(); len];
for line in input.lines() {
for (pos, ch) in line.chars().enumerate() {
let cnt = histograms[pos].entry(ch).or_insert(0);
*cnt += 1;
}
}
histograms.into_iter()
.map(|h| {
match method {
DecodingMethod::MostLikely => {
h.into_iter().max_by(|&(_, cnt_a), &(_, cnt_b)| cnt_a.cmp(&cnt_b))
}
DecodingMethod::LeastLikely => {
h.into_iter().min_by(|&(_, cnt_a), &(_, cnt_b)| cnt_a.cmp(&cnt_b))
|
identifier_body
|
main.rs
|
#![feature(iter_max_by, iter_min_by)]
use std::collections::HashMap;
use std::io;
use std::io::prelude::*;
enum
|
{
MostLikely,
LeastLikely,
}
fn decode_message(input: &str, method: DecodingMethod) -> String {
let len = input.lines().map(|line| line.chars().count()).max().unwrap();
let mut histograms = vec![HashMap::new(); len];
for line in input.lines() {
for (pos, ch) in line.chars().enumerate() {
let cnt = histograms[pos].entry(ch).or_insert(0);
*cnt += 1;
}
}
histograms.into_iter()
.map(|h| {
match method {
DecodingMethod::MostLikely => {
h.into_iter().max_by(|&(_, cnt_a), &(_, cnt_b)| cnt_a.cmp(&cnt_b))
}
DecodingMethod::LeastLikely => {
h.into_iter().min_by(|&(_, cnt_a), &(_, cnt_b)| cnt_a.cmp(&cnt_b))
}
}
.unwrap()
.0
})
.collect()
}
fn main() {
let mut message_str = String::new();
io::stdin().read_to_string(&mut message_str).expect("Invalid input string!");
println!("The initial decoded message is: {}",
decode_message(&message_str, DecodingMethod::MostLikely));
println!("The actual decoded message is: {}",
decode_message(&message_str, DecodingMethod::LeastLikely));
}
#[cfg(test)]
mod tests {
use super::decode_message;
use super::DecodingMethod;
const TEST_INPUT: &'static str = "eedadn\n\
drvtee\n\
eandsr\n\
raavrd\n\
atevrs\n\
tsrnev\n\
sdttsa\n\
rasrtv\n\
nssdts\n\
ntnada\n\
svetve\n\
tesnvt\n\
vntsnd\n\
vrdear\n\
dvrsen\n\
enarar";
#[test]
fn decode_message_test() {
assert_eq!(decode_message(TEST_INPUT, DecodingMethod::MostLikely),
"easter");
}
#[test]
fn decode_message_b_test() {
assert_eq!(decode_message(TEST_INPUT, DecodingMethod::LeastLikely),
"advent");
}
}
|
DecodingMethod
|
identifier_name
|
main.rs
|
#![feature(iter_max_by, iter_min_by)]
use std::collections::HashMap;
use std::io;
use std::io::prelude::*;
enum DecodingMethod {
MostLikely,
LeastLikely,
}
fn decode_message(input: &str, method: DecodingMethod) -> String {
let len = input.lines().map(|line| line.chars().count()).max().unwrap();
let mut histograms = vec![HashMap::new(); len];
for line in input.lines() {
for (pos, ch) in line.chars().enumerate() {
let cnt = histograms[pos].entry(ch).or_insert(0);
|
.map(|h| {
match method {
DecodingMethod::MostLikely => {
h.into_iter().max_by(|&(_, cnt_a), &(_, cnt_b)| cnt_a.cmp(&cnt_b))
}
DecodingMethod::LeastLikely => {
h.into_iter().min_by(|&(_, cnt_a), &(_, cnt_b)| cnt_a.cmp(&cnt_b))
}
}
.unwrap()
.0
})
.collect()
}
fn main() {
let mut message_str = String::new();
io::stdin().read_to_string(&mut message_str).expect("Invalid input string!");
println!("The initial decoded message is: {}",
decode_message(&message_str, DecodingMethod::MostLikely));
println!("The actual decoded message is: {}",
decode_message(&message_str, DecodingMethod::LeastLikely));
}
#[cfg(test)]
mod tests {
use super::decode_message;
use super::DecodingMethod;
const TEST_INPUT: &'static str = "eedadn\n\
drvtee\n\
eandsr\n\
raavrd\n\
atevrs\n\
tsrnev\n\
sdttsa\n\
rasrtv\n\
nssdts\n\
ntnada\n\
svetve\n\
tesnvt\n\
vntsnd\n\
vrdear\n\
dvrsen\n\
enarar";
#[test]
fn decode_message_test() {
assert_eq!(decode_message(TEST_INPUT, DecodingMethod::MostLikely),
"easter");
}
#[test]
fn decode_message_b_test() {
assert_eq!(decode_message(TEST_INPUT, DecodingMethod::LeastLikely),
"advent");
}
}
|
*cnt += 1;
}
}
histograms.into_iter()
|
random_line_split
|
vec-tail-matching.rs
|
// Copyright 2014 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.
struct Foo {
string: String
}
pub fn main() {
let x = [
Foo { string: "foo".to_string() },
Foo { string: "bar".to_string() },
Foo { string: "baz".to_string() }
];
match x {
[ref first,..tail] => {
assert!(first.string == "foo".to_string());
assert_eq!(tail.len(), 2);
assert!(tail[0].string == "bar".to_string());
assert!(tail[1].string == "baz".to_string());
|
match tail {
[Foo {.. }, _, Foo {.. },.. _tail] => {
unreachable!();
}
[Foo { string: ref a }, Foo { string: ref b }] => {
assert_eq!("bar", a.as_slice().slice(0, a.len()));
assert_eq!("baz", b.as_slice().slice(0, b.len()));
}
_ => {
unreachable!();
}
}
}
}
}
|
random_line_split
|
|
vec-tail-matching.rs
|
// Copyright 2014 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.
struct Foo {
string: String
}
pub fn
|
() {
let x = [
Foo { string: "foo".to_string() },
Foo { string: "bar".to_string() },
Foo { string: "baz".to_string() }
];
match x {
[ref first,..tail] => {
assert!(first.string == "foo".to_string());
assert_eq!(tail.len(), 2);
assert!(tail[0].string == "bar".to_string());
assert!(tail[1].string == "baz".to_string());
match tail {
[Foo {.. }, _, Foo {.. },.. _tail] => {
unreachable!();
}
[Foo { string: ref a }, Foo { string: ref b }] => {
assert_eq!("bar", a.as_slice().slice(0, a.len()));
assert_eq!("baz", b.as_slice().slice(0, b.len()));
}
_ => {
unreachable!();
}
}
}
}
}
|
main
|
identifier_name
|
vec-tail-matching.rs
|
// Copyright 2014 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.
struct Foo {
string: String
}
pub fn main() {
let x = [
Foo { string: "foo".to_string() },
Foo { string: "bar".to_string() },
Foo { string: "baz".to_string() }
];
match x {
[ref first,..tail] => {
assert!(first.string == "foo".to_string());
assert_eq!(tail.len(), 2);
assert!(tail[0].string == "bar".to_string());
assert!(tail[1].string == "baz".to_string());
match tail {
[Foo {.. }, _, Foo {.. },.. _tail] =>
|
[Foo { string: ref a }, Foo { string: ref b }] => {
assert_eq!("bar", a.as_slice().slice(0, a.len()));
assert_eq!("baz", b.as_slice().slice(0, b.len()));
}
_ => {
unreachable!();
}
}
}
}
}
|
{
unreachable!();
}
|
conditional_block
|
vec-tail-matching.rs
|
// Copyright 2014 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.
struct Foo {
string: String
}
pub fn main()
|
}
_ => {
unreachable!();
}
}
}
}
}
|
{
let x = [
Foo { string: "foo".to_string() },
Foo { string: "bar".to_string() },
Foo { string: "baz".to_string() }
];
match x {
[ref first, ..tail] => {
assert!(first.string == "foo".to_string());
assert_eq!(tail.len(), 2);
assert!(tail[0].string == "bar".to_string());
assert!(tail[1].string == "baz".to_string());
match tail {
[Foo { .. }, _, Foo { .. }, .. _tail] => {
unreachable!();
}
[Foo { string: ref a }, Foo { string: ref b }] => {
assert_eq!("bar", a.as_slice().slice(0, a.len()));
assert_eq!("baz", b.as_slice().slice(0, b.len()));
|
identifier_body
|
package_id.rs
|
// Copyright 2013 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 version::{try_getting_version, try_getting_local_version,
Version, NoVersion, split_version};
use std::rt::io::Writer;
use std::hash::Streaming;
use std::hash;
/// Path-fragment identifier of a package such as
/// 'github.com/graydon/test'; path must be a relative
/// path with >=1 component.
#[deriving(Clone)]
pub struct PkgId {
/// This is a path, on the local filesystem, referring to where the
/// files for this package live. For example:
/// github.com/mozilla/quux-whatever (it's assumed that if we're
/// working with a package ID of this form, rustpkg has already cloned
|
path: Path,
/// Short name. This is the path's filestem, but we store it
/// redundantly so as to not call get() everywhere (filestem() returns an
/// option)
/// The short name does not need to be a valid Rust identifier.
/// Users can write: `extern mod foo = "...";` to get around the issue
/// of package IDs whose short names aren't valid Rust identifiers.
short_name: ~str,
/// The requested package version.
version: Version
}
impl Eq for PkgId {
fn eq(&self, other: &PkgId) -> bool {
self.path == other.path && self.version == other.version
}
}
impl PkgId {
pub fn new(s: &str) -> PkgId {
use conditions::bad_pkg_id::cond;
let mut given_version = None;
// Did the user request a specific version?
let s = match split_version(s) {
Some((path, v)) => {
given_version = Some(v);
path
}
None => {
s
}
};
let path = Path(s);
if path.is_absolute {
return cond.raise((path, ~"absolute pkgid"));
}
if path.components.len() < 1 {
return cond.raise((path, ~"0-length pkgid"));
}
let short_name = path.filestem().expect(fmt!("Strange path! %s", s));
let version = match given_version {
Some(v) => v,
None => match try_getting_local_version(&path) {
Some(v) => v,
None => match try_getting_version(&path) {
Some(v) => v,
None => NoVersion
}
}
};
PkgId {
path: path.clone(),
short_name: short_name.to_owned(),
version: version
}
}
pub fn hash(&self) -> ~str {
fmt!("%s-%s-%s", self.path.to_str(),
hash(self.path.to_str() + self.version.to_str()),
self.version.to_str())
}
pub fn short_name_with_version(&self) -> ~str {
fmt!("%s%s", self.short_name, self.version.to_str())
}
/// True if the ID has multiple components
pub fn is_complex(&self) -> bool {
self.short_name!= self.path.to_str()
}
pub fn prefixes_iter(&self) -> Prefixes {
Prefixes {
components: self.path.components().to_owned(),
remaining: ~[]
}
}
// This is the workcache function name for the *installed*
// binaries for this package (as opposed to the built ones,
// which are per-crate).
pub fn install_tag(&self) -> ~str {
fmt!("install(%s)", self.to_str())
}
}
struct Prefixes {
priv components: ~[~str],
priv remaining: ~[~str]
}
impl Iterator<(Path, Path)> for Prefixes {
#[inline]
fn next(&mut self) -> Option<(Path, Path)> {
if self.components.len() <= 1 {
None
}
else {
let last = self.components.pop();
self.remaining.push(last);
// converting to str and then back is a little unfortunate
Some((Path(self.components.to_str()), Path(self.remaining.to_str())))
}
}
}
impl ToStr for PkgId {
fn to_str(&self) -> ~str {
// should probably use the filestem and not the whole path
fmt!("%s-%s", self.path.to_str(), self.version.to_str())
}
}
pub fn write<W: Writer>(writer: &mut W, string: &str) {
writer.write(string.as_bytes());
}
pub fn hash(data: ~str) -> ~str {
let hasher = &mut hash::default_state();
write(hasher, data);
hasher.result_str()
}
|
/// the sources into a local directory in the RUST_PATH).
|
random_line_split
|
package_id.rs
|
// Copyright 2013 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 version::{try_getting_version, try_getting_local_version,
Version, NoVersion, split_version};
use std::rt::io::Writer;
use std::hash::Streaming;
use std::hash;
/// Path-fragment identifier of a package such as
/// 'github.com/graydon/test'; path must be a relative
/// path with >=1 component.
#[deriving(Clone)]
pub struct PkgId {
/// This is a path, on the local filesystem, referring to where the
/// files for this package live. For example:
/// github.com/mozilla/quux-whatever (it's assumed that if we're
/// working with a package ID of this form, rustpkg has already cloned
/// the sources into a local directory in the RUST_PATH).
path: Path,
/// Short name. This is the path's filestem, but we store it
/// redundantly so as to not call get() everywhere (filestem() returns an
/// option)
/// The short name does not need to be a valid Rust identifier.
/// Users can write: `extern mod foo = "...";` to get around the issue
/// of package IDs whose short names aren't valid Rust identifiers.
short_name: ~str,
/// The requested package version.
version: Version
}
impl Eq for PkgId {
fn eq(&self, other: &PkgId) -> bool
|
}
impl PkgId {
pub fn new(s: &str) -> PkgId {
use conditions::bad_pkg_id::cond;
let mut given_version = None;
// Did the user request a specific version?
let s = match split_version(s) {
Some((path, v)) => {
given_version = Some(v);
path
}
None => {
s
}
};
let path = Path(s);
if path.is_absolute {
return cond.raise((path, ~"absolute pkgid"));
}
if path.components.len() < 1 {
return cond.raise((path, ~"0-length pkgid"));
}
let short_name = path.filestem().expect(fmt!("Strange path! %s", s));
let version = match given_version {
Some(v) => v,
None => match try_getting_local_version(&path) {
Some(v) => v,
None => match try_getting_version(&path) {
Some(v) => v,
None => NoVersion
}
}
};
PkgId {
path: path.clone(),
short_name: short_name.to_owned(),
version: version
}
}
pub fn hash(&self) -> ~str {
fmt!("%s-%s-%s", self.path.to_str(),
hash(self.path.to_str() + self.version.to_str()),
self.version.to_str())
}
pub fn short_name_with_version(&self) -> ~str {
fmt!("%s%s", self.short_name, self.version.to_str())
}
/// True if the ID has multiple components
pub fn is_complex(&self) -> bool {
self.short_name!= self.path.to_str()
}
pub fn prefixes_iter(&self) -> Prefixes {
Prefixes {
components: self.path.components().to_owned(),
remaining: ~[]
}
}
// This is the workcache function name for the *installed*
// binaries for this package (as opposed to the built ones,
// which are per-crate).
pub fn install_tag(&self) -> ~str {
fmt!("install(%s)", self.to_str())
}
}
struct Prefixes {
priv components: ~[~str],
priv remaining: ~[~str]
}
impl Iterator<(Path, Path)> for Prefixes {
#[inline]
fn next(&mut self) -> Option<(Path, Path)> {
if self.components.len() <= 1 {
None
}
else {
let last = self.components.pop();
self.remaining.push(last);
// converting to str and then back is a little unfortunate
Some((Path(self.components.to_str()), Path(self.remaining.to_str())))
}
}
}
impl ToStr for PkgId {
fn to_str(&self) -> ~str {
// should probably use the filestem and not the whole path
fmt!("%s-%s", self.path.to_str(), self.version.to_str())
}
}
pub fn write<W: Writer>(writer: &mut W, string: &str) {
writer.write(string.as_bytes());
}
pub fn hash(data: ~str) -> ~str {
let hasher = &mut hash::default_state();
write(hasher, data);
hasher.result_str()
}
|
{
self.path == other.path && self.version == other.version
}
|
identifier_body
|
package_id.rs
|
// Copyright 2013 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 version::{try_getting_version, try_getting_local_version,
Version, NoVersion, split_version};
use std::rt::io::Writer;
use std::hash::Streaming;
use std::hash;
/// Path-fragment identifier of a package such as
/// 'github.com/graydon/test'; path must be a relative
/// path with >=1 component.
#[deriving(Clone)]
pub struct PkgId {
/// This is a path, on the local filesystem, referring to where the
/// files for this package live. For example:
/// github.com/mozilla/quux-whatever (it's assumed that if we're
/// working with a package ID of this form, rustpkg has already cloned
/// the sources into a local directory in the RUST_PATH).
path: Path,
/// Short name. This is the path's filestem, but we store it
/// redundantly so as to not call get() everywhere (filestem() returns an
/// option)
/// The short name does not need to be a valid Rust identifier.
/// Users can write: `extern mod foo = "...";` to get around the issue
/// of package IDs whose short names aren't valid Rust identifiers.
short_name: ~str,
/// The requested package version.
version: Version
}
impl Eq for PkgId {
fn eq(&self, other: &PkgId) -> bool {
self.path == other.path && self.version == other.version
}
}
impl PkgId {
pub fn new(s: &str) -> PkgId {
use conditions::bad_pkg_id::cond;
let mut given_version = None;
// Did the user request a specific version?
let s = match split_version(s) {
Some((path, v)) => {
given_version = Some(v);
path
}
None => {
s
}
};
let path = Path(s);
if path.is_absolute {
return cond.raise((path, ~"absolute pkgid"));
}
if path.components.len() < 1
|
let short_name = path.filestem().expect(fmt!("Strange path! %s", s));
let version = match given_version {
Some(v) => v,
None => match try_getting_local_version(&path) {
Some(v) => v,
None => match try_getting_version(&path) {
Some(v) => v,
None => NoVersion
}
}
};
PkgId {
path: path.clone(),
short_name: short_name.to_owned(),
version: version
}
}
pub fn hash(&self) -> ~str {
fmt!("%s-%s-%s", self.path.to_str(),
hash(self.path.to_str() + self.version.to_str()),
self.version.to_str())
}
pub fn short_name_with_version(&self) -> ~str {
fmt!("%s%s", self.short_name, self.version.to_str())
}
/// True if the ID has multiple components
pub fn is_complex(&self) -> bool {
self.short_name!= self.path.to_str()
}
pub fn prefixes_iter(&self) -> Prefixes {
Prefixes {
components: self.path.components().to_owned(),
remaining: ~[]
}
}
// This is the workcache function name for the *installed*
// binaries for this package (as opposed to the built ones,
// which are per-crate).
pub fn install_tag(&self) -> ~str {
fmt!("install(%s)", self.to_str())
}
}
struct Prefixes {
priv components: ~[~str],
priv remaining: ~[~str]
}
impl Iterator<(Path, Path)> for Prefixes {
#[inline]
fn next(&mut self) -> Option<(Path, Path)> {
if self.components.len() <= 1 {
None
}
else {
let last = self.components.pop();
self.remaining.push(last);
// converting to str and then back is a little unfortunate
Some((Path(self.components.to_str()), Path(self.remaining.to_str())))
}
}
}
impl ToStr for PkgId {
fn to_str(&self) -> ~str {
// should probably use the filestem and not the whole path
fmt!("%s-%s", self.path.to_str(), self.version.to_str())
}
}
pub fn write<W: Writer>(writer: &mut W, string: &str) {
writer.write(string.as_bytes());
}
pub fn hash(data: ~str) -> ~str {
let hasher = &mut hash::default_state();
write(hasher, data);
hasher.result_str()
}
|
{
return cond.raise((path, ~"0-length pkgid"));
}
|
conditional_block
|
package_id.rs
|
// Copyright 2013 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 version::{try_getting_version, try_getting_local_version,
Version, NoVersion, split_version};
use std::rt::io::Writer;
use std::hash::Streaming;
use std::hash;
/// Path-fragment identifier of a package such as
/// 'github.com/graydon/test'; path must be a relative
/// path with >=1 component.
#[deriving(Clone)]
pub struct PkgId {
/// This is a path, on the local filesystem, referring to where the
/// files for this package live. For example:
/// github.com/mozilla/quux-whatever (it's assumed that if we're
/// working with a package ID of this form, rustpkg has already cloned
/// the sources into a local directory in the RUST_PATH).
path: Path,
/// Short name. This is the path's filestem, but we store it
/// redundantly so as to not call get() everywhere (filestem() returns an
/// option)
/// The short name does not need to be a valid Rust identifier.
/// Users can write: `extern mod foo = "...";` to get around the issue
/// of package IDs whose short names aren't valid Rust identifiers.
short_name: ~str,
/// The requested package version.
version: Version
}
impl Eq for PkgId {
fn eq(&self, other: &PkgId) -> bool {
self.path == other.path && self.version == other.version
}
}
impl PkgId {
pub fn new(s: &str) -> PkgId {
use conditions::bad_pkg_id::cond;
let mut given_version = None;
// Did the user request a specific version?
let s = match split_version(s) {
Some((path, v)) => {
given_version = Some(v);
path
}
None => {
s
}
};
let path = Path(s);
if path.is_absolute {
return cond.raise((path, ~"absolute pkgid"));
}
if path.components.len() < 1 {
return cond.raise((path, ~"0-length pkgid"));
}
let short_name = path.filestem().expect(fmt!("Strange path! %s", s));
let version = match given_version {
Some(v) => v,
None => match try_getting_local_version(&path) {
Some(v) => v,
None => match try_getting_version(&path) {
Some(v) => v,
None => NoVersion
}
}
};
PkgId {
path: path.clone(),
short_name: short_name.to_owned(),
version: version
}
}
pub fn hash(&self) -> ~str {
fmt!("%s-%s-%s", self.path.to_str(),
hash(self.path.to_str() + self.version.to_str()),
self.version.to_str())
}
pub fn short_name_with_version(&self) -> ~str {
fmt!("%s%s", self.short_name, self.version.to_str())
}
/// True if the ID has multiple components
pub fn is_complex(&self) -> bool {
self.short_name!= self.path.to_str()
}
pub fn prefixes_iter(&self) -> Prefixes {
Prefixes {
components: self.path.components().to_owned(),
remaining: ~[]
}
}
// This is the workcache function name for the *installed*
// binaries for this package (as opposed to the built ones,
// which are per-crate).
pub fn
|
(&self) -> ~str {
fmt!("install(%s)", self.to_str())
}
}
struct Prefixes {
priv components: ~[~str],
priv remaining: ~[~str]
}
impl Iterator<(Path, Path)> for Prefixes {
#[inline]
fn next(&mut self) -> Option<(Path, Path)> {
if self.components.len() <= 1 {
None
}
else {
let last = self.components.pop();
self.remaining.push(last);
// converting to str and then back is a little unfortunate
Some((Path(self.components.to_str()), Path(self.remaining.to_str())))
}
}
}
impl ToStr for PkgId {
fn to_str(&self) -> ~str {
// should probably use the filestem and not the whole path
fmt!("%s-%s", self.path.to_str(), self.version.to_str())
}
}
pub fn write<W: Writer>(writer: &mut W, string: &str) {
writer.write(string.as_bytes());
}
pub fn hash(data: ~str) -> ~str {
let hasher = &mut hash::default_state();
write(hasher, data);
hasher.result_str()
}
|
install_tag
|
identifier_name
|
leafmt.rs
|
//! Lea code formatter.
// FIXME This requires the parser to preserve comments to work properly
// This is blocked on an upstream issue: https://github.com/kevinmehall/rust-peg/issues/84
#[macro_use]
extern crate clap;
extern crate term;
extern crate rustc_serialize;
extern crate lea_parser as parser;
extern crate lea;
use parser::span::DummyTerm;
use parser::prettyprint::PrettyPrinter;
use std::io::{self, stdin, stderr, stdout, Read, Write};
use std::fs::File;
use std::path::Path;
/// Opens a terminal that writes to stderr. If stderr couldn't be opened as a terminal, creates a
/// `DummyTerm` that writes to stderr instead.
fn
|
() -> Box<term::StderrTerminal> {
term::stderr().unwrap_or_else(|| Box::new(DummyTerm(io::stderr())))
}
/// Parses the given source code and pretty-prints it
fn prettyprint<W: Write>(code: &str, source_name: &str, mut target: W) -> io::Result<()> {
match parser::block(code) {
Ok(main) => {
let mut pp = PrettyPrinter::new(&mut target);
try!(pp.print_block(&main));
}
Err(e) => {
try!(e.format(code, source_name, &mut *stderr_term()));
}
}
Ok(())
}
fn read_file(filename: &str) -> io::Result<String> {
let mut s = String::new();
let mut file = try!(File::open(&Path::new(filename)));
try!(file.read_to_string(&mut s));
Ok(s)
}
fn main() {
let matches = clap_app!(leafmt =>
(version: lea::version_str())
(about: "Lea source code formatter / pretty printer")
(@arg FILE: +required "The file to format (`-` to read from stdin)")
(@arg out: -o --out +takes_value "Write output to <out> (`-` to write to stdout).")
(after_help: "By default, leafmt will write the formatted code to stdout.\n")
).get_matches();
let file = matches.value_of("FILE").unwrap();
// Read input
let mut code = String::new();
let source_name;
if file == "-" {
stdin().read_to_string(&mut code).unwrap();
source_name = "<stdin>";
} else {
source_name = file;
code = match read_file(&source_name) {
Ok(content) => content,
Err(e) => {
writeln!(stderr(), "{}", e).unwrap();
return;
}
}
}
// Open output
let writer: Box<Write>;
match matches.value_of("out") {
None | Some("-") => {
writer = Box::new(stdout()) as Box<Write>;
}
Some(s) => {
let f = match File::create(&Path::new(s)) {
Ok(f) => f,
Err(e) => {
writeln!(stderr(), "{}", e).unwrap();
return;
}
};
writer = Box::new(f) as Box<Write>;
}
}
prettyprint(&code, &source_name, writer).unwrap();
}
|
stderr_term
|
identifier_name
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.