blob_id
stringlengths 40
40
| language
stringclasses 1
value | repo_name
stringlengths 5
140
| path
stringlengths 5
183
| src_encoding
stringclasses 6
values | length_bytes
int64 12
5.32M
| score
float64 2.52
4.94
| int_score
int64 3
5
| detected_licenses
listlengths 0
47
| license_type
stringclasses 2
values | text
stringlengths 12
5.32M
| download_success
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|
c22c0fff0e87367cb1173f9c9f1852e5959070b0
|
Rust
|
sriggin/pingcap-talent-plan
|
/src/bin/kvs.rs
|
UTF-8
| 2,212 | 2.9375 | 3 |
[] |
no_license
|
#[macro_use]
extern crate clap;
#[macro_use]
extern crate failure;
use clap::{App, Arg, SubCommand};
fn main() -> kvs::Result<()> {
let key_arg = Arg::with_name("key").required(true);
let matches = App::new(crate_name!())
.version(crate_version!())
.author(crate_authors!())
.about(crate_description!())
.subcommand(
SubCommand::with_name("set")
.about("Sets a value for a key")
.arg(key_arg.clone())
.arg(Arg::with_name("value").required(true)),
)
.subcommand(
SubCommand::with_name("get")
.about("Gets the value for a key")
.arg(key_arg.clone()),
)
.subcommand(
SubCommand::with_name("rm")
.about("Delete an entry")
.arg(key_arg.clone()),
)
.get_matches();
let mut kvs = kvs::KvStore::open(std::path::Path::new("."))?;
match matches.subcommand() {
("set", Some(set_matches)) => {
if let (Some(key), Some(value)) =
(set_matches.value_of("key"), set_matches.value_of("value"))
{
kvs.set(key.to_string(), value.to_string())?;
Ok(())
} else {
panic!("WTF: {:?}", set_matches);
}
}
("get", Some(get_matches)) => {
if let Some(key) = get_matches.value_of("key") {
match kvs.get(key.to_string())? {
Option::Some(value) => {
println!("{}", value);
Ok(())
}
Option::None => Err(format_err!("Key not found")),
}
} else {
panic!("WTF: {:?}", get_matches);
}
}
("rm", Some(rm_matches)) => {
if let Some(key) = rm_matches.value_of("key") {
kvs.remove(key.to_string())?;
Ok(())
} else {
panic!("WTF: {:?}", rm_matches);
}
}
("", None) => panic!("A valid subcommand is required"),
other => panic!("WTF {:?}", other),
}
}
| true |
e1e18dec6fdb5c243def558174b46b3ae5b7b093
|
Rust
|
evan-a-w/rustlib
|
/src/rope.rs
|
UTF-8
| 7,275 | 3.65625 | 4 |
[] |
no_license
|
use std::rc::Rc;
use std::fmt;
use std::mem::{replace, MaybeUninit};
pub struct FString {
rope: Rope
}
impl FString {
pub fn new(s: String) -> Self {
Self {
rope: Rope::new(s),
}
}
pub fn concat(&mut self, other: Self) {
// We are switching self.rope with an uninitialised value and immediately
// replacing it, therefore it is safe.
unsafe {
let nr = replace(&mut self.rope, MaybeUninit::zeroed().assume_init());
self.rope = nr.concat(other.rope);
}
}
pub fn nth(&self, i: usize) -> Option<char> {
self.rope.nth(i)
}
pub fn size(&self) -> usize {
self.rope.size()
}
pub fn split(&mut self, i: usize) -> Option<Self> {
// We are switching self.rope with an uninitialised value and immediately
// replacing it, therefore it is safe.
unsafe {
let nr = replace(&mut self.rope, MaybeUninit::zeroed().assume_init());
let (r, o) = nr.split(i);
self.rope = r;
match o {
None => None,
Some(x) => Some(Self {rope: x}),
}
}
}
pub fn insert(&mut self, i: usize, s: Self) {
unsafe {
let nr = replace(&mut self.rope, MaybeUninit::zeroed().assume_init());
let nr = nr.insert(i, s.rope);
self.rope = nr;
}
}
pub fn insert_rc_string(&mut self, i: usize, s: Rc<String>) {
unsafe {
let nr = replace(&mut self.rope, MaybeUninit::zeroed().assume_init());
let nr = nr.insert(i, Rope::Leaf(s));
self.rope = nr;
}
}
pub fn delete(&mut self, i: usize, j: usize) {
unsafe {
let nr = replace(&mut self.rope, MaybeUninit::zeroed().assume_init());
let nr = nr.delete(i, j);
self.rope = nr;
}
}
}
impl fmt::Display for FString {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.rope)
}
}
pub enum Rope {
Node(RopeNode),
Leaf(Rc<String>),
}
pub struct RopeNode {
left: Box<Rope>,
right: Box<Rope>,
size: usize,
size_left: usize,
}
impl fmt::Display for Rope {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.rec_display(f);
Ok(())
}
}
impl Rope {
pub fn new(s: String) -> Self {
Rope::Leaf(Rc::new(s))
}
pub fn nth(&self, i: usize) -> Option<char> {
match self {
Rope::Node(rn) => {
if rn.size_left <= i {
if i >= rn.size {
None
} else {
rn.right.nth(i - rn.size_left)
}
} else {
rn.left.nth(i)
}
}
Rope::Leaf(s) => s.chars().nth(i),
}
}
pub fn size(&self) -> usize {
match self {
Rope::Leaf(s) => s.len(),
Rope::Node(rn) => rn.size,
}
}
// TODO: make efficient for special cases like both leaves and such
pub fn concat(self, other: Self) -> Self {
Rope::Node(RopeNode {
size: Rope::size(&self) + Rope::size(&other),
size_left: Rope::size(&self),
left: Box::new(self),
right: Box::new(other),
})
}
pub fn construct_from_vec(v: Vec<Self>) -> Option<Self> {
let mut curr = None;
for i in v.into_iter() {
match curr {
None => { curr = Some(i); }
Some(x) => { curr = Some(x.concat(i)); }
};
}
curr
}
// TODO: instead of using a vector i think you can just keep a running
// thingy.
fn do_split(self, i: usize, mut v: Vec<Self>) -> (Self, Vec<Self>) {
match self {
Rope::Leaf(s) => {
// In this case, we perform the split on the string itself,
// then return the new node. We add the result thing to the vec
// which will later fold with concatenation.
if i >= s.len() {
return (Rope::Leaf(s), v);
}
let (a, b) = &s.split_at(i);
let ns = a.to_string();
let rs = b.to_string();
v.push(Rope::Leaf(Rc::new(rs)));
(Rope::Leaf(Rc::new(ns)), v)
}
Rope::Node(mut rn) => {
let res: Rope;
// Recursive thing + update.
if i < rn.size_left {
// splitting on the left means that the result we get from
// splitting left will be the thing we wish to return.
// We need to add the current node (once updated) to the
// vector.
let (tres, tv) = rn.left.do_split(i, v);
res = tres;
v = tv;
// new rn.left will come from assembling v
match v.len() {
0 => { v.push(*rn.right); },
_ => {
rn.left = Box::new(Rope::construct_from_vec(v).unwrap());
v = vec![];
v.push(Rope::Node(rn));
}
}
} else if i == rn.size_left {
// even split - we can just return the left and push the right
res = *rn.left;
v.push(*rn.right);
} else {
// splitting somewhere on the right - we want to update
// our right node and return the new thing.
let (tres, tv) = rn.right.do_split(i - rn.size_left, v);
v = tv;
rn.right = Box::new(tres);
if Rope::size(&rn.right) == 0 {
res = *rn.left;
} else {
rn.size = Rope::size(&rn.left) + Rope::size(&rn.right);
res = Rope::Node(rn);
}
}
(res, v)
}
}
}
pub fn split(self, i: usize) -> (Self, Option<Self>) {
let (left, v) = self.do_split(i, vec![]);
(left, Rope::construct_from_vec(v))
}
pub fn rec_display(&self, f: &mut fmt::Formatter<'_>) {
match self {
Rope::Node(rn) => {
rn.left.rec_display(f);
rn.right.rec_display(f);
}
Rope::Leaf(s) => { write!(f, "{}", s); }
}
}
pub fn insert(self, i: usize, s: Self) -> Self {
let (mut res, r) = self.split(i);
res = res.concat(s);
match r {
None => {},
Some(x) => {
res = res.concat(x);
}
}
res
}
pub fn delete(self, i: usize, j: usize) -> Self {
let (l, r) = self.split(i);
match r {
None => l,
Some(x) => match x.split(j + 1).1 {
None => l,
Some(p) => l.concat(p),
}
}
}
}
| true |
eaa9dc50b9c9f8208f58359ef5459fbb1c8cb7d5
|
Rust
|
NeoChow/rsbind
|
/tools-rsbind/src/config.rs
|
UTF-8
| 1,290 | 2.59375 | 3 |
[
"Apache-2.0"
] |
permissive
|
use std::fs::File;
use std::io::Read;
use std::path::PathBuf;
use toml;
#[derive(Clone, Deserialize, Debug)]
pub struct Config {
pub android: Option<Android>,
pub ios: Option<Ios>,
}
#[derive(Clone, Deserialize, Debug)]
pub struct Android {
pub ndk_stand_alone: Option<String>,
pub rustc_param: Option<String>,
pub arch: Option<Vec<String>>,
pub arch_64: Option<Vec<String>>,
pub arch_x86: Option<Vec<String>>,
pub release: Option<bool>,
pub namespace: Option<String>,
pub so_name: Option<String>,
pub ext_lib: Option<Vec<String>>,
pub features_def: Option<Vec<String>>,
}
#[derive(Clone, Deserialize, Debug)]
pub struct Ios {
pub rustc_param: Option<String>,
pub arch_phone: Option<Vec<String>>,
pub arch_simu: Option<Vec<String>>,
pub release: Option<bool>,
pub features_def: Option<Vec<String>>,
}
pub fn parse(prj_path: &PathBuf) -> Option<Config> {
let mut s = String::new();
let path = prj_path.join("Rsbind.toml");
if !path.exists() {
println!("Rsbind.toml didn't found, skip parsing.");
return None;
}
let mut f = File::open(&path).expect("open Rsbind.toml failed.");
f.read_to_string(&mut s).expect("read Rsbind.toml failed.");
toml::from_str::<Config>(&s).ok()
}
| true |
0cf9714e74ce9d628a125ed7382827ea3729b3b0
|
Rust
|
d-z-h/rust-guide
|
/examples/concurrency/parallel/examples/rayon-parallel-search.rs
|
UTF-8
| 330 | 3.078125 | 3 |
[
"MIT",
"Apache-2.0"
] |
permissive
|
use rayon::prelude::*;
fn main() {
let v = vec![6, 2, 1, 9, 3, 8, 11];
let f1 = v.par_iter().find_any(|&&x| x == 9);
let f2 = v.par_iter().find_any(|&&x| x % 2 == 0 && x > 6);
let f3 = v.par_iter().find_any(|&&x| x > 8);
assert_eq!(f1, Some(&9));
assert_eq!(f2, Some(&8));
assert!(f3 > Some(&8));
}
| true |
7ab4e20b893ddd5ff331eb833f0c6f3e481fe46a
|
Rust
|
mrozbarry/rust-meta-weather
|
/src/main.rs
|
UTF-8
| 5,548 | 2.8125 | 3 |
[] |
no_license
|
#[macro_use]
extern crate serde_derive;
extern crate reqwest;
use reqwest::Error;
#[derive(Deserialize, Debug)]
struct Location {
title: String,
location_type: String,
woeid: u32,
latt_long: String,
}
type LocationCollection = Vec<Location>;
#[derive(Deserialize, Debug)]
struct ConsolidatedWeather {
id: u64,
weather_state_name: String,
weather_state_abbr: String,
wind_direction_compass: String,
created: String,
applicable_date: String,
min_temp: f64,
max_temp: f64,
the_temp: f64,
wind_speed: f64,
wind_direction: f64,
air_pressure: f64,
humidity: u32,
visibility: f64,
predictability: u32,
}
#[derive(Deserialize, Debug)]
struct Weather {
consolidated_weather: Vec<ConsolidatedWeather>,
time: String,
sun_rise: String,
sun_set: String,
timezone_name: String,
parent: Location,
title: String,
location_type: String,
woeid: u32,
latt_long: String,
timezone: String,
}
fn main() -> Result<(), Error> {
// cargo run toronto
let search = "san";
let locations = get_locations(search)?;
let mut forecasts = get_weather_for_locations(locations)?;
while let Some(forecast) = forecasts.pop() {
println!("{:?}", weather_report(forecast));
}
return Ok(());
}
fn temperature(temp : f64) -> String {
return format!("{}°C", temp.round());
}
fn consolidated_weather_report(consolidated_weather : &ConsolidatedWeather) -> String {
return format!("high of {high} and low of {low}, currently sitting at {current} with {state}",
high = temperature(consolidated_weather.max_temp),
low = temperature(consolidated_weather.min_temp),
current = temperature(consolidated_weather.the_temp),
state = consolidated_weather.weather_state_name,
);
}
fn weather_report(forecast : Weather) -> String {
return format!("The weather today in {city} will have a {consolidated_weather}",
city = forecast.title,
consolidated_weather = consolidated_weather_report(&forecast.consolidated_weather[0]),
);
}
fn location_search_url(search : &str) -> String {
return format!("https://www.metaweather.com/api/location/search/?query={}", search);
}
fn get_locations(search : &str) -> Result<LocationCollection, Error> {
let url = location_search_url(search);
return reqwest::get(&url)?.json();
}
fn get_weather_for_locations(locations : LocationCollection) -> Result<Vec<Weather>, Error> {
return locations.into_iter().map(|location| get_weather_for_location(location)).collect();
}
fn location_weather_url(location : &Location) -> String {
return format!("https://www.metaweather.com/api/location/{}?speed=k", location.woeid);
}
fn get_weather_for_location(location : Location) -> Result<Weather, Error> {
let url = location_weather_url(&location);
return reqwest::get(&url)?.json();
}
#[cfg(test)]
mod tests {
use super::*;
fn weather_empty() -> Weather {
return Weather {
consolidated_weather: vec![],
time: "".to_string(),
sun_rise: "".to_string(),
sun_set: "".to_string(),
timezone_name: "".to_string(),
parent: Location {
title: "".to_string(),
location_type: "".to_string(),
woeid: 0,
latt_long: "".to_string(),
},
title: "".to_string(),
location_type: "".to_string(),
woeid: 0,
latt_long: "".to_string(),
timezone: "".to_string(),
};
}
fn weather_with_title(weather: Weather, title: &str) {
return Weather {
title: title.to_string(),
..weather
};
}
fn weather_with_temperatures(weather: Weather, min_temp: f64, max_temp: f64, the_temp: f64, weather_state_name : &str) -> Weather {
return Weather {
consolidated_weather: vec![
ConsolidatedWeather {
id: 0,
weather_state_name: weather_state_name.to_string(),
weather_state_abbr: "".to_string(),
wind_direction_compass: "".to_string(),
created: "".to_string(),
applicable_date: "".to_string(),
min_temp,
max_temp,
the_temp,
wind_speed: 0.0,
wind_direction: 0.0,
air_pressure: 0.0,
humidity: 0,
visibility: 0.0,
predictability: 0,
},
],
..weather
};
}
fn weather_builder(title: &str, min_temp: f64, max_temp: f64, the_temp: f64, weather_state_name : &str) -> Weather {
return weather_with_temperatures(
weather_with_title(
weather_empty(),
title,
),
min_temp,
max_temp,
the_temp,
weather_state_name,
);
}
#[test]
fn weather_report_renders_correct_data() {
let weather = weather_builder("Toronto", 0.0, 100.0, 50.0, "Light rain");
assert_eq!(
weather_report(weather),
"The weather today in Toronto will have a high of 100°C and low of 0°C, currently sitting at 50°C with Light rain",
)
}
}
| true |
52e41d3a64eefdbbef7e8a1ba1959f1ada8d7144
|
Rust
|
Kostassoid/lethe
|
/src/storage/windows/mod.rs
|
UTF-8
| 2,261 | 2.8125 | 3 |
[
"Apache-2.0"
] |
permissive
|
#![cfg(windows)]
extern crate winapi;
use crate::storage::*;
#[macro_use]
mod helpers;
mod meta;
use super::windows::meta::*;
mod access;
use access::*;
mod misc;
use misc::*;
use anyhow::{Context, Result};
impl System {
pub fn enumerate_storage_devices() -> Result<Vec<StorageRef>> {
let enumerator = DiskDeviceEnumerator::new().with_context(|| {
if !is_elevated() {
format!("Make sure you run the application with Administrator permissions!")
} else {
format!("") //todo: hints?
}
})?;
let mut devices: Vec<StorageRef> = enumerator.collect();
devices.sort_by(|a, b| a.id.cmp(&b.id));
Ok(devices)
}
}
impl StorageDevice for StorageRef {
fn access(&self) -> Result<Box<dyn StorageAccess>> {
CompositeStorageAccess::open(self).map(|a| Box::new(a) as Box<dyn StorageAccess>)
}
}
/// On Windows, to work with a low level PhysicalDrive, we have to acquire locks to all partitions/volumes
/// located on this drive and we have to keep these locks for the duration of wiping process.
/// In terms of implementation we just open the whole tree of devices for write which effectively
/// locks and dismounts every volume in that tree.
struct CompositeStorageAccess {
device: DeviceFile,
_children: Vec<DeviceFile>,
}
impl CompositeStorageAccess {
fn open(device: &StorageRef) -> Result<Self> {
let children: Result<Vec<DeviceFile>> = device
.children
.iter()
.map(|c| DeviceFile::open(&c.id, true))
.collect();
let device = DeviceFile::open(&device.id, true)?;
Ok(Self {
device,
_children: children?,
})
}
}
impl StorageAccess for CompositeStorageAccess {
fn position(&mut self) -> Result<u64> {
self.device.position()
}
fn seek(&mut self, position: u64) -> Result<u64> {
self.device.seek(position)
}
fn read(&mut self, buffer: &mut [u8]) -> Result<usize> {
self.device.read(buffer)
}
fn write(&mut self, data: &[u8]) -> Result<()> {
self.device.write(data)
}
fn flush(&mut self) -> Result<()> {
self.device.flush()
}
}
| true |
bc2c95344b2bbcbc45f2741367a0abca9880c10b
|
Rust
|
Matthias-Fauconneau/iced
|
/wgpu/src/image/atlas/entry.rs
|
UTF-8
| 531 | 2.71875 | 3 |
[
"MIT"
] |
permissive
|
use crate::image::atlas;
#[derive(Debug)]
pub enum Entry {
Contiguous(atlas::Allocation),
Fragmented {
size: (u32, u32),
fragments: Vec<Fragment>,
},
}
impl Entry {
#[cfg(feature = "image")]
pub fn size(&self) -> (u32, u32) {
match self {
Entry::Contiguous(allocation) => allocation.size(),
Entry::Fragmented { size, .. } => *size,
}
}
}
#[derive(Debug)]
pub struct Fragment {
pub position: (u32, u32),
pub allocation: atlas::Allocation,
}
| true |
be69a21ed984a3d4db15a7b8c1b2c3abfae74755
|
Rust
|
leontoeides/google_maps
|
/src/places/business_status.rs
|
UTF-8
| 5,849 | 3.359375 | 3 |
[
"MIT",
"Apache-2.0"
] |
permissive
|
//! The `business_status` field within the _Places API_ _Place_ response
//! object indicates the operational status of the place, if it is a business.
use crate::error::Error as GoogleMapsError;
use crate::places::error::Error as PlacesError;
use phf::phf_map;
use serde::{Deserialize, Deserializer, Serialize, Serializer};
// -----------------------------------------------------------------------------
//
/// Indicates the operational status of the place, if it is a business. If no
/// data exists, business_status is not returned. The allowed values include:
/// `OPERATIONAL`, `CLOSED_TEMPORARILY`, and `CLOSED_PERMANENTLY`.
#[derive(Clone, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub enum BusinessStatus {
#[default] Operational,
ClosedTemporarily,
ClosedPermanently,
} // struct
// -----------------------------------------------------------------------------
impl<'de> Deserialize<'de> for BusinessStatus {
/// Manual implementation of `Deserialize` for `serde`. This will take
/// advantage of the `phf`-powered `TryFrom` implementation for this type.
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
let string = String::deserialize(deserializer)?;
match BusinessStatus::try_from(string.as_str()) {
Ok(variant) => Ok(variant),
Err(error) => Err(serde::de::Error::custom(error.to_string()))
} // match
} // fn
} // impl
// -----------------------------------------------------------------------------
impl Serialize for BusinessStatus {
/// Manual implementation of `Serialize` for `serde`.
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where S: Serializer {
serializer.serialize_str(std::convert::Into::<&str>::into(self))
} // fn
} // impl
// -----------------------------------------------------------------------------
impl std::convert::From<&BusinessStatus> for &str {
/// Converts a `BusinessStatus` enum to a `String` that contains a
/// [business status](https://developers.google.com/maps/documentation/places/web-service/search-text#Place-business_status)
/// code.
fn from(status: &BusinessStatus) -> Self {
match status {
BusinessStatus::Operational => "OPERATIONAL",
BusinessStatus::ClosedTemporarily => "CLOSED_TEMPORARILY",
BusinessStatus::ClosedPermanently => "CLOSED_PERMANENTLY",
} // match
} // fn
} // impl
// -----------------------------------------------------------------------------
impl std::fmt::Display for BusinessStatus {
/// Converts a `BusinessStatus` enum to a `String` that contains a
/// [business status](https://developers.google.com/maps/documentation/places/web-service/search-text#Place-business_status)
/// code.
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", std::convert::Into::<&str>::into(self))
} // fmt
} // impl
// -----------------------------------------------------------------------------
impl std::convert::From<&BusinessStatus> for String {
/// Converts a `BusinessStatus` enum to a `String` that contains a
/// [business status](https://developers.google.com/maps/documentation/places/web-service/search-text#Place-business_status)
/// code.
fn from(business_status: &BusinessStatus) -> Self {
std::convert::Into::<&str>::into(business_status).to_string()
} // fn
} // impl
// -----------------------------------------------------------------------------
static STATUSES_BY_CODE: phf::Map<&'static str, BusinessStatus> = phf_map! {
"OPERATIONAL" => BusinessStatus::Operational,
"CLOSED_TEMPORARILY" => BusinessStatus::ClosedTemporarily,
"CLOSED_PERMANENTLY" => BusinessStatus::ClosedPermanently,
};
// -----------------------------------------------------------------------------
impl std::convert::TryFrom<&str> for BusinessStatus {
// Error definitions are contained in the
// `google_maps\src\places\place_autocomplete\error.rs` module.
type Error = GoogleMapsError;
/// Gets a `BusinessStatus` enum from a `String` that contains a valid
/// [status](https://developers.google.com/maps/documentation/places/web-service/autocomplete#PlacesAutocompleteBusinessStatus)
/// code.
fn try_from(status_code: &str) -> Result<Self, Self::Error> {
Ok(STATUSES_BY_CODE
.get(status_code)
.cloned()
.ok_or_else(|| PlacesError::InvalidBusinessStatusCode(status_code.to_string()))?)
} // fn
} // impl
// -----------------------------------------------------------------------------
impl std::str::FromStr for BusinessStatus {
// Error definitions are contained in the
// `google_maps\src\places\place_autocomplete\error.rs` module.
type Err = GoogleMapsError;
/// Gets a `BusinessStatus` enum from a `String` that contains a valid
/// [status](https://developers.google.com/maps/documentation/places/web-service/autocomplete#PlacesAutocompleteBusinessStatus)
/// code.
fn from_str(status_code: &str) -> Result<Self, Self::Err> {
Ok(STATUSES_BY_CODE
.get(status_code)
.cloned()
.ok_or_else(|| PlacesError::InvalidBusinessStatusCode(status_code.to_string()))?)
} // fn
} // impl
// -----------------------------------------------------------------------------
impl BusinessStatus {
/// Formats a `BusinessStatus` enum into a string that is presentable to the
/// end user.
pub fn display(&self) -> &str {
match self {
BusinessStatus::Operational => "Operational",
BusinessStatus::ClosedTemporarily => "Closed Temporarily",
BusinessStatus::ClosedPermanently => "Closed Permanently",
} // match
} // fn
} // impl
| true |
606a5da40d932847b0c2f37f1a5d04bd57c27e34
|
Rust
|
aticu/nuefil
|
/src/loaded_image.rs
|
UTF-8
| 2,585 | 3.203125 | 3 |
[
"MIT"
] |
permissive
|
//! Can be used on any image handle to obtain information about the loaded image.
use crate::{memory::MemoryType, status::Status, system::SystemTable, Handle};
use core::fmt;
/// Each loaded image has an image handle that supports EFI_LOADED_IMAGE_PROTOCOL. When an
/// image is started, it is passed the image handle for itself. The image can use the handle to obtain its
/// relevant image data stored in the EFI_LOADED_IMAGE_PROTOCOL structure, such as its load options.
#[repr(C)]
pub struct LoadedImage {
/// Defines the revision of the EFI_LOADED_IMAGE_PROTOCOL
/// structure. All future revisions will be backward compatible
/// to the current revision.
pub Revision: u32,
/// Parent image’s image handle. NULL if the image is loaded
/// directly from the firmware’s boot manager.
pub ParentHandle: Handle,
/// The image’s EFI system table pointer.
pub SystemTable: &'static mut SystemTable,
/// The device handle that the EFI Image was loaded from.
pub DeviceHandle: Handle,
/// A pointer to the file path portion specific to DeviceHandle
/// that the EFI Image was loaded from.
pub FilePath: usize,
/// Reserved. DO NOT USE.
pub Reserved: usize,
/// The size in bytes of LoadOptions.
pub LoadOptionsSize: u32,
/// A pointer to the image’s binary load options.
pub LoadOptions: *const u16,
/// The base address at which the image was loaded.
pub ImageBase: usize,
/// The size in bytes of the loaded image.
pub ImageSize: u64,
/// The memory type that the code sections were loaded as.
pub ImageCodeType: MemoryType,
/// The memory type that the data sections were loaded as.
pub ImageDataType: MemoryType,
/// Function that unloads the image.
pub Unload: extern "win64" fn(ImageHandle: Handle) -> Status,
}
impl fmt::Debug for LoadedImage {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.debug_struct("LoadedImage")
.field("Revision", &self.Revision)
.field("ParentHandle", &self.ParentHandle)
.field("DeviceHandle", &self.DeviceHandle)
.field("FilePath", &self.FilePath)
.field("Reserved", &self.Reserved)
.field("LoadOptionsSize", &self.LoadOptionsSize)
.field("LoadOptions", &self.LoadOptions)
.field("ImageBase", &self.ImageBase)
.field("ImageSize", &self.ImageSize)
.field("ImageCodeType", &self.ImageCodeType)
.field("ImageDataType", &self.ImageDataType)
.finish()
}
}
| true |
5bb476b8e97d18be75edea7ec841c8b52e569469
|
Rust
|
asandst/aoc_2020
|
/src/bin/day6_2.rs
|
UTF-8
| 421 | 2.59375 | 3 |
[] |
no_license
|
extern crate itertools;
use std::collections::HashSet;
use std::fs;
use std::io;
use itertools::Itertools;
fn main() -> io::Result<()> {
let input = fs::read_to_string("input_day6").unwrap();
println!("{:?}", input.split("\r\n\r\n").map(|g| g.split("\r\n").map(|p| p.chars().collect::<HashSet<char>>()).fold1(|x, y| x.intersection(&y).cloned().collect())).map(|s| s.unwrap().len()).sum::<usize>());
Ok(())
}
| true |
bc152d579a4f57900fb04fba5cbb71ae7928b3ed
|
Rust
|
grievejia/rpcomb
|
/src/combinator/token_parser.rs
|
UTF-8
| 1,341 | 3.1875 | 3 |
[
"MIT"
] |
permissive
|
use internal::{ParseOutput, InputStream};
use parser::Parser;
pub struct TokenParser<P> {
parser: P
}
impl<'t, P> Parser<'t> for TokenParser<P> where P: Parser<'t> {
type OutputType = P::OutputType;
fn parse<T: InputStream<'t, T>>(&self, input: T) -> ParseOutput<T, Self::OutputType> {
let mut i = 0;
for ch in input.get_input().chars() {
match ch {
' ' | '\n' | '\t' => i += 1,
_ => break
}
}
let new_input = input.consume(i);
self.parser.parse(new_input)
}
}
pub fn tokenp<'t, P: Parser<'t>>(p: P) -> TokenParser<P> {
TokenParser { parser: p }
}
#[test]
fn token_parser_test() {
use internal::StringInputStream;
use parser::strp;
let input = StringInputStream::new(" abcde");
let parser = tokenp(strp("abc"));
match parser.parse(input) {
ParseOutput::Success(i, o) => {
assert_eq!(o, "abc");
assert_eq!(i.get_input(), "de");
assert_eq!(i.get_position().get_line_number(), 1);
assert_eq!(i.get_position().get_column_number(), 6);
},
_ => {
panic!("Parsing should succeed");
}
}
let input2 = StringInputStream::new(" abdce");
match parser.parse(input2) {
ParseOutput::Failure(err) => {
assert_eq!(err.get_error_position().get_line_number(), 1);
assert_eq!(err.get_error_position().get_column_number(), 3);
},
_ => {
panic!("Parsing should fail");
}
}
}
| true |
c1258c93aa98e4496a458a0494b8bf101114fb69
|
Rust
|
Noah2610/fsmus
|
/src/config.rs
|
UTF-8
| 2,708 | 3.21875 | 3 |
[
"MIT"
] |
permissive
|
use std::fs::File;
use std::net::IpAddr;
use std::path::PathBuf;
#[derive(Deserialize, Debug)]
pub struct Config {
/// The root directory from which to check for music and playlist directories.
/// Can use "~", which expands to the user's home directory.
pub music_dir: PathBuf,
/// The host IP address to use for hosting the app with the "start" command.
pub host: IpAddr,
/// The port number to use for hosting the app with the "start" command.
pub port: u16,
/// The default playback behavior when the app starts.
/// Defaults to `Random`.
#[serde(default)]
pub playback_behavior: PlaybackBehavior,
/// The default selected playlist when the app starts.
/// Specify a playlist name, which is the path to the playlist directory,
/// relative to the `music_dir`.
#[serde(default)]
pub default_playlist: Option<String>,
}
#[derive(Deserialize, Clone, Debug)]
pub enum PlaybackBehavior {
Random,
Sequential,
}
impl Default for PlaybackBehavior {
fn default() -> Self {
Self::Random
}
}
impl Config {
pub fn load() -> Result<Self, String> {
let file = Self::get_config_file()?;
let reader = File::open(file).map_err(|e| e.to_string())?;
let mut config: Self =
ron::de::from_reader(reader).map_err(|e| e.to_string())?;
let base_dirs = directories::BaseDirs::new()
.ok_or_else(|| String::from("No base directories"))?;
let home_dir = base_dirs.home_dir().to_str().ok_or_else(|| {
String::from("Can't convert HOME directory path to string")
})?;
let music_dir_s = config.music_dir.to_str().ok_or_else(|| {
String::from("Can't convert music_dir path to string")
})?;
config.music_dir = PathBuf::from(music_dir_s.replace("~", home_dir));
Ok(config)
}
fn get_config_file() -> Result<PathBuf, String> {
let file = PathBuf::from("./config.ron");
if file.is_file() {
Ok(file)
} else {
let project_dirs =
directories::ProjectDirs::from("", "", env!("CARGO_PKG_NAME"))
.ok_or_else(|| {
String::from("No project config directory")
})?;
let config_dir = project_dirs.config_dir();
let config_file = config_dir.join("config.ron");
if config_file.is_file() {
Ok(config_file)
} else {
Err(format!(
"No config.ron file in config directory {:?}",
&config_dir
))
}
}
}
}
| true |
c81697cc48cb43ac2d4db145a3a7838301e77b2a
|
Rust
|
ivanceras/balisong
|
/src/lod.rs
|
UTF-8
| 1,388 | 3.40625 | 3 |
[
"MIT"
] |
permissive
|
//computes the limit and volumes of based on LOD
//lod can not be greater than 9
use std::fmt;
use constants;
pub struct LOD{
pub lod:u8,
pub limit:u32,
pub volume:u64,
}
impl LOD{
pub fn new(lod:u8)->LOD{
if lod > constants::MAX_LOD{
panic!("LOD can not be greater than {}", constants::MAX_LOD);
}
let base = constants::BASE as u32;
let limit = base.pow(lod as u32);
let volume = limit as u64 * limit as u64 * limit as u64;
LOD{lod:lod, limit:limit, volume:volume}
}
pub fn inc(&mut self, inc:u8){
let lod = self.lod + inc;
let base = constants::BASE as u32;
let limit = base.pow(lod as u32);
println!("limit: {}", limit);
let volume = limit as u64 * limit as u64 * limit as u64;
self.lod = lod;
self.limit = limit;
self.volume = volume;
}
pub fn from_volume(volume:u64)->LOD{
let limit = (volume as f64).cbrt();
let lod = limit.log(constants::BASE as f64) as u8;
LOD::new(lod)
}
}
impl Clone for LOD {
fn clone(&self) -> LOD {
LOD{
lod:self.lod,
limit:self.limit,
volume:self.volume,
}
}
}
impl fmt::Display for LOD {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.lod)
}
}
| true |
d6ca89a3b0c8de7837da2f25fa512f898fb08cb5
|
Rust
|
GrossBetruger/RustPlaygound
|
/oop/src/lib.rs
|
UTF-8
| 1,029 | 3.6875 | 4 |
[] |
no_license
|
pub struct AveragedCollection {
list: Vec<f32>,
average: f64,
}
impl AveragedCollection {
pub fn new() -> AveragedCollection {
AveragedCollection {
list: vec![],
average: 0.,
}
}
pub fn add(&mut self, item: f32) {
self.list.push(item);
self.update_average();
}
pub fn remove(&mut self) -> Option<f32> {
match self.list.pop() {
Some(val) => {
self.update_average();
Some(val)
}
None => None,
}
}
pub fn average(&self) -> f64 {
self.average
}
fn update_average(&mut self) {
self.average =
self.list.iter().map(|item| *item as f64).sum::<f64>() / self.list.len() as f64;
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_average() {
let mut avg_lst = AveragedCollection::new();
avg_lst.add(3.);
avg_lst.add(2.);
assert_eq!(avg_lst.average(), 2.5)
}
}
| true |
933f2f9b3301f044142ba7c76ed33ad62b97df09
|
Rust
|
topliceanu/learn
|
/rust/guessing-game-api/src/main.rs
|
UTF-8
| 1,686 | 3.3125 | 3 |
[
"MIT"
] |
permissive
|
#[macro_use] extern crate rocket;
#[get("/")]
fn index() -> &'static str {
"Hi"
}
#[launch]
fn rocket() -> _ {
rocket::build().mount("/", routes![index])
}
/*
use std::io::{Read, Write, BufReader, BufRead};
use std::net::{TcpListener, TcpStream};
fn main() {
// bind allows us to create a connection on the port
// and gets it ready to accept connections.
let listener = TcpListener::bind("0.0.0.0:3000").unwrap();
// The listener's accept method waits or 'blocks' until
// we have a connection and then returns a new TcpStream
// that we can read and write data to.
let stream = listener.accept().unwrap().0;
read_request(stream);
}
// This function takes the stream we just got from the
// listener and then reads some data from it.
fn read_request(mut stream: TcpStream) {
//let mut request_data = String::new();
let mut reader = BufReader::new(stream);
// lines until you hit an empty line, which means that the body is next.
for line in reader.by_ref().lines() {
if line.unwrap() == "" {
break;
}
}
let mut line = String::new();
reader.read_line(&mut line);
send_response(line, reader.into_inner());
// The read_to_string method uses the string we pass
// in and fills it up with the data from the stream.
//stream.read_to_string(&mut request_data);
// Finally we print the data
//println!("{}", request_data);
}
fn send_response(line: String, mut stream: TcpStream) {
let num: i32 = line.parse().unwrap();
println!("{}", num);
let response = format!("HTTP/1.1 200 OK\n\n{}", num);
stream.write_all(response.as_bytes()).unwrap();
}
*/
| true |
457b95aa95bf629b22e362b09db09f25c9ce3913
|
Rust
|
ocadaruma/redis-nativemsgpack
|
/src/msgpack/format.rs
|
UTF-8
| 1,136 | 3.171875 | 3 |
[
"Apache-2.0"
] |
permissive
|
use super::ByteVector;
use std::mem::size_of;
/// Represents msgpack primitive
pub trait Primitive
where
Self: Sized + Ord,
{
const FIRST_BYTE: u8;
const SIZE: usize;
fn read<T: ByteVector>(bytes: &T, from: usize) -> Option<Self>;
fn write<T: ByteVector>(bytes: &mut T, from: usize, value: Self);
}
#[derive(Debug, Ord, PartialOrd, Eq, PartialEq)]
pub struct Int64(pub i64);
impl Primitive for Int64 {
const FIRST_BYTE: u8 = 0xd3;
const SIZE: usize = size_of::<i64>();
fn read<T: ByteVector>(bytes: &T, from: usize) -> Option<Self> {
if bytes[from] != Self::FIRST_BYTE {
None
} else {
let n = (0..Self::SIZE).fold(0i64, |a, i| {
a | (bytes[from + i + 1] as i64) << ((Self::SIZE - 1 - i) * 8) as i64
});
Some(Int64(n))
}
}
fn write<T: ByteVector>(bytes: &mut T, from: usize, value: Self) {
bytes[from] = Self::FIRST_BYTE;
let Self(n) = value;
for i in 0..Self::SIZE {
bytes[from + i + 1] = ((n >> ((Self::SIZE - 1 - i) as i64 * 8)) & 0xff) as u8;
}
}
}
| true |
fe8c307dc0509d0a8a2c256c52666e4157ad3ae1
|
Rust
|
Jaxii/dorker
|
/src/dork.rs
|
UTF-8
| 5,306 | 2.578125 | 3 |
[] |
no_license
|
extern crate reqwest;
extern crate select;
use futures::executor::block_on;
use reqwest::blocking::Client;
use reqwest::header::USER_AGENT;
use select::document::Document;
use select::node::Node;
use select::predicate::{Attr, Class, Element, Name, Predicate, Text};
use std::collections::HashMap;
use std::error::Error;
use std::str;
struct BoxedPred(Box<dyn Predicate>);
impl Predicate for BoxedPred {
fn matches(&self, node: &Node) -> bool {
self.0.matches(node)
}
}
pub async fn get_body(url: &str) -> String {
Client::new()
.get(url)
.header(
USER_AGENT,
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10.13; rv:72.0) Gecko/20100101 Firefox/72.0",
//"Mozilla/5.0 (Macintosh; Intel Mac OS X 10.10; rv:34.0) Gecko/20100101 Firefox/34.0",
)
.send()
.unwrap()
.text()
.unwrap()
}
pub fn find_links(
engine: &str,
dorks: HashMap<String, String>,
extra: Option<String>,
) -> Result<Vec<QueryItem>, Box<dyn Error>> {
let mut request_string = format!("https://{}/search?q=", engine);
for (dork, content) in dorks {
request_string.push_str(dork.as_str());
request_string.push(':');
request_string.push_str(content.as_str());
request_string.push_str("%20");
}
if let Some(x) = extra {
request_string.push_str(&x);
}
// If the engine is not found, we just use google's predicate
let pred: BoxedPred = match engine {
"google.com" => BoxedPred(Box::new(
Attr("id", "rso")
.descendant(Attr("class", "bkWMgd"))
.descendant(Attr("class", "r"))
.descendant(Name("a")),
)),
// I Think this one works, needs more testing
"www.bing.com" => BoxedPred(Box::new(
Attr("id", "b_content")
.descendant(Attr("id", "b_results"))
.descendant(Attr("class", "b_algo"))
.descendant(Name("a")),
)),
// These currently don't work
/* "duckduckgo.com" => BoxedPred(Box::new(
Attr("id", "links_wrapper")
.descendant(Attr("class", "results"))
.descendant(Attr("class", "result__a"))
.descendant(Name("a")),
)),
"www.ecosia.org" => BoxedPred(Box::new(
Attr("class", "mainline-results")
.descendant(Attr("class", "result"))
.descendant(Attr("class", "result-url"))
.descendant(Name("a")),
)), */
_ => BoxedPred(Box::new(
Attr("id", "rso")
.descendant(Attr("class", "bkWMgd"))
.descendant(Attr("class", "r"))
.descendant(Name("a")),
)),
};
let body = block_on(get_body(request_string.as_str()));
let document = Document::from(body.as_str());
let mut link_items: Vec<QueryItem> = Vec::new();
for node in document.find(pred) {
let title_pred: BoxedPred = match engine {
"google.com" => BoxedPred(Box::new(Class("LC20lb"))),
"www.bing.com" => BoxedPred(Box::new(Text)),
// These don't work right now
/* "duckduckgo.com" => BoxedPred(Box::new(Element)),
"www.ecosia.org" => BoxedPred(Box::new(Element)), */
_ => BoxedPred(Box::new(Class("LC20lb"))),
};
let link = node.attr("href").unwrap();
for title in node.find(title_pred) {
link_items.push(QueryItem::new(title.text(), link.to_string()))
/* println!(
"Debug: {}: found title {} for link {}",
engine,
title.text(),
link.to_string()
); */
}
}
Ok(link_items)
}
#[derive(Debug)]
pub struct DorkResults {
accumulated: Vec<DorkResult>,
}
impl DorkResults {
pub fn new() -> DorkResults {
let res = DorkResults {
accumulated: vec![],
};
res
}
pub fn add(&mut self,
result: DorkResult) -> Result<(), Box<dyn Error>> {
self.accumulated.push(result);
Ok(())
}
}
#[derive(Debug)]
pub struct DorkResult {
engine: String,
urls: Vec<String>,
}
impl DorkResult {
pub fn new() -> DorkResult {
DorkResult {
engine: String::from(""),
urls: vec![],
}
}
pub fn set_engine(&mut self, engine: String) {
self.engine = engine;
}
pub fn add_url(&mut self, url: String) {
self.urls.push(url)
}
}
#[derive(Debug, Default)]
pub struct Dork {
engine: String,
dorks: HashMap<String, String>,
extra: Option<String>,
}
impl Dork {
pub fn from(engine: String,
dorks: HashMap<String, String>,
extra: String) -> Dork {
Dork {
engine,
dorks,
extra: Some(extra.to_string()),
}
}
pub fn get_scrape(&self) {
find_links(&self.engine, self.dorks.clone(), self.extra.clone());
}
}
#[derive(Debug, Clone)]
pub struct QueryItem {
pub link: String,
pub title: String,
}
impl QueryItem {
pub fn new(title: String, link: String) -> QueryItem {
QueryItem { title, link }
}
}
| true |
3afb4b2e2db866d69e321ca5994f8e792f036d41
|
Rust
|
kubo/rust-oracle
|
/src/conn.rs
|
UTF-8
| 1,780 | 2.5625 | 3 |
[
"UPL-1.0",
"Apache-2.0"
] |
permissive
|
// Rust-oracle - Rust binding for Oracle database
//
// URL: https://github.com/kubo/rust-oracle
//
//-----------------------------------------------------------------------------
// Copyright (c) 2017-2021 Kubo Takehiro <[email protected]>. All rights reserved.
// This program is free software: you can modify it and/or redistribute it
// under the terms of:
//
// (i) the Universal Permissive License v 1.0 or at your option, any
// later version (http://oss.oracle.com/licenses/upl); and/or
//
// (ii) the Apache License v 2.0. (http://www.apache.org/licenses/LICENSE-2.0)
//-----------------------------------------------------------------------------
//! Type definitions for connection
//!
//! Some types at the top-level module will move here in future.
use crate::binding::*;
#[cfg(doc)]
use crate::Connection;
/// The mode to use when closing connections to the database
///
/// See [`Connection::close_with_mode`].
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub enum CloseMode<'a> {
/// The connection is returned to the connection pool for
/// future use.
Default,
/// Causes the connection to be dropped from the connection
/// pool.
Drop,
/// Causes the connection to be tagged with the tag information.
/// An empty tag `""` will cause the tag to be cleared.
Retag(&'a str),
}
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
/// [Session Purity](https://www.oracle.com/pls/topic/lookup?ctx=dblatest&id=GUID-12410EEC-FE79-42E2-8F6B-EAA9EDA59665)
pub enum Purity {
/// Must use a new session
New,
/// Reuse a pooled session
Self_,
}
impl Purity {
pub(crate) fn to_dpi(self) -> dpiPurity {
match self {
Purity::New => DPI_PURITY_NEW,
Purity::Self_ => DPI_PURITY_SELF,
}
}
}
| true |
80fe0fb2335c536ec14455842f2b8febb1023d32
|
Rust
|
planet0104/art_pattern
|
/src/chapter2/sample5.rs
|
UTF-8
| 1,218 | 2.734375 | 3 |
[
"BSD-2-Clause"
] |
permissive
|
use stdweb::web::CanvasRenderingContext2d;
/*顶点 */
const VERTEXS: [(f64, f64); 3] = [(100.0, 100.0), (220.0, 100.0), (160.0, 50.0)];
pub fn draw(context: &CanvasRenderingContext2d) {
/*画原三角形 */
draw_triangle(&VERTEXS, context, "#000");
let angle = 0.3;
/*画旋转后的三角形 */
let rotate = |x: f64, y: f64, a: f64, x0: f64, y0: f64| -> (f64, f64) {
(
x0 + (x - x0) * a.cos() + (y - y0) * a.sin(),
y0 + (y - y0) * a.cos() - (x - x0) * a.sin(),
)
};
draw_triangle(
&[
rotate(VERTEXS[0].0, VERTEXS[0].1, angle, 160.0, 75.0),
rotate(VERTEXS[1].0, VERTEXS[1].1, angle, 160.0, 75.0),
rotate(VERTEXS[2].0, VERTEXS[2].1, angle, 160.0, 75.0),
],
context,
"#00f",
);
}
/*画三角形 */
fn draw_triangle(points: &[(f64, f64); 3], context: &CanvasRenderingContext2d, color: &str) {
context.set_stroke_style_color(color);
context.begin_path();
context.move_to(points[0].0, points[0].1);
context.line_to(points[1].0, points[1].1);
context.line_to(points[2].0, points[2].1);
context.line_to(points[0].0, points[0].1);
context.stroke();
}
| true |
945cf62bf082a599c19d99119184505fb1c44925
|
Rust
|
TheAdnan/hrdja
|
/schrust/src/main.rs
|
UTF-8
| 1,652 | 3.546875 | 4 |
[
"Apache-2.0"
] |
permissive
|
struct User {
name: String,
id: u32
}
//printing function for User struct
impl User {
fn print_me(&self){
println!("User id: {:?} \nUsername: {:?}", &self.id, &self.name);
}
}
//constructor equivalent
impl User {
fn new(name: String, id: u32) -> Self{
Self{ name: name, id: id }
}
}
pub trait UID{
fn createUID(&self);
}
impl UID for User {
fn createUID(&self){
println!("____Test trait____");
&self.print_me();
println!("____trait works____");
}
}
fn printing_stuff<T: PartialOrd>(a: T, b: T) -> bool{
a > b
}
mod some_modules{
pub fn module_function(){
println!("This is a test function");
}
}
fn main() {
let u = User{
name: String::from("Ramo"),
id: 2
};
let u2 = User::new(String::from("Zulfo"), 3);
u.print_me();
u2.print_me();
u.createUID();
let tr = printing_stuff(2, 5);
println!("{:?}", tr);
let value1: &'static str = "Selam";
let mut value2 = value1.to_string();
value2.push_str(" alejk");
let value3 = value2.replace("Selam alejk", "merhaba");
let value4 = replace_with_merhaba(&value2);
some_modules::module_function();
//Arrays and vectors
let someArray = ["This", "is", "an", "array"];
let mut aVector: Vec<&str> = vec!["This", "is", "a", "Vector"];
aVector.pop();
aVector.push("also a Vector");
for a in aVector{
println!("{:?}", a);
}
}
#[cfg(target_os = "linux")]
fn abs(x: i32) -> i32 {
if x > 0 {
x
} else {
-x
}
}
#[cfg(target_os = "linux")]
fn replace_with_merhaba(s: &str) -> String {
s.replace(s, "Merhaba")
}
#[cfg(target_os = "android")]
fn abs(x: i32){
println!("Syyyyke");
}
| true |
1424d035487d4acfb87c022f71d60cb0a023c66b
|
Rust
|
faraazahmad/loop
|
/src/row.rs
|
UTF-8
| 4,309 | 2.828125 | 3 |
[
"MIT"
] |
permissive
|
use crate::highlighting;
use std::cmp;
use termion::color;
use unicode_segmentation::UnicodeSegmentation;
#[derive(Default)]
pub struct Row {
string: String,
highlighting: Vec<highlighting::Type>,
len: usize,
}
impl From<&str> for Row {
fn from(slice: &str) -> Self {
let mut row = Self {
string: String::from(slice),
highlighting: Vec::new(),
len: 0,
};
row.update_len();
row
}
}
impl Row {
pub fn render(&self, start: usize, end: usize) -> String {
let end = cmp::min(end, self.string.len());
let start = cmp::min(start, end);
// self.string.get(start..end).unwrap_or_default().to_string()
let mut result = String::new();
// loop over graphemes instead of ascii characters (Unicode support)
for grapheme in self.string[..]
.graphemes(true)
.skip(start)
.take(end - start)
{
if let Some(c) = grapheme.chars().next() {
if c == '\t' {
result.push_str(" ");
} else if c.is_ascii_digit() {
result.push_str(
&format!(
"{}{}{}",
color::Fg(color::Rgb(220, 163, 163)),
c,
color::Fg(color::Reset),
)[..],
);
} else {
result.push(c);
}
}
}
result
}
pub fn len(&self) -> usize {
self.len
}
pub fn is_empty(&self) -> bool {
self.len == 0
}
// count graphemes in row and store length of row
pub fn update_len(&mut self) {
self.len = self.string[..].graphemes(true).count();
}
pub fn insert(&mut self, at: usize, c: char) {
// push character at end of string
if at >= self.len() {
self.string.push(c);
} else {
let mut result: String = self.string[..].graphemes(true).take(at).collect();
let remainder: String = self.string[..].graphemes(true).skip(at).collect();
result.push(c);
result.push_str(&remainder);
self.string = result;
}
self.update_len();
}
pub fn delete(&mut self, at: usize) {
if at >= self.len() {
return;
} else {
let mut result: String = self.string[..].graphemes(true).take(at).collect();
let remainder: String = self.string[..].graphemes(true).skip(at + 1).collect();
result.push_str(&remainder);
self.string = result;
}
self.update_len();
}
pub fn append(&mut self, new: &Self) {
self.string = format!("{}{}", self.string, new.string);
self.update_len();
}
pub fn split(&mut self, at: usize) -> Self {
let beginning: String = self.string[..].graphemes(true).take(at).collect();
let remainder: String = self.string[..].graphemes(true).skip(at).collect();
self.string = beginning;
self.update_len();
Self::from(&remainder[..])
}
pub fn as_bytes(&self) -> &[u8] {
self.string.as_bytes()
}
pub fn find(&self, query: &str, after: usize) -> Option<usize> {
let substring: String = self.string[..].graphemes(true).skip(after).collect();
let matching_byte_index = self.string.find(query);
if let Some(matching_byte_index) = matching_byte_index {
for (grapheme_index, (byte_index, _)) in
substring[..].grapheme_indices(true).enumerate()
{
if matching_byte_index == byte_index {
#[allow(clippy::integer_arithmetic)]
return Some(grapheme_index);
}
}
}
None
}
pub fn highlight(&mut self) {
let mut highlighting = Vec::new();
for c in self.string.chars() {
if c.is_ascii_digit() {
highlighting.push(highlighting::Type::Number);
} else {
highlighting.push(highlighting::Type::None);
}
}
self.highlighting = highlighting;
}
}
| true |
19e7916ec853270cb372e77a6b8fc8c610082a05
|
Rust
|
oknowles/advent-of-code
|
/rust/aoc2022/src/days/day04.rs
|
UTF-8
| 1,638 | 3.328125 | 3 |
[] |
no_license
|
fn read_input(input: &str) -> Vec<((u32,u32), (u32,u32))> {
input.lines()
.map(|l| {
let pairs = l.split(',').collect::<Vec<&str>>();
let i1 = pairs[0].split('-').map(|c| c.parse::<u32>().unwrap()).collect::<Vec<u32>>();
let i2 = pairs[1].split('-').map(|c| c.parse::<u32>().unwrap()).collect::<Vec<u32>>();
((i1[0], i1[1]), (i2[0], i2[1]))
})
.collect()
}
fn part_one(input: Vec<((u32,u32), (u32,u32))>) -> u32 {
input.iter()
.filter(|(i1, i2)| completely_overlap(i1, i2))
.count() as u32
}
fn part_two(input: Vec<((u32,u32), (u32,u32))>) -> u32 {
input.iter()
.filter(|(i1, i2)| partially_overlap(i1, i2))
.count() as u32
}
fn completely_overlap(i1: &(u32, u32), i2: &(u32, u32)) -> bool {
(i1.0 <= i2.0 && i2.1 <= i1.1) || (i2.0 <= i1.0 && i1.1 <= i2.1)
}
fn partially_overlap(i1: &(u32, u32), i2: &(u32, u32)) -> bool {
(i1.0 <= i2.0 && i2.0 <= i1.1) || (i2.0 <= i1.0 && i1.0 <= i2.1)
}
pub fn main() {
let input = read_input(include_str!("../../input/day04.txt"));
let part_one = part_one(input.clone());
let part_two = part_two(input.clone());
println!("[Day 04] Part One: {}\tPart Two: {}", part_one, part_two);
}
mod tests {
use crate::days::day04::{part_one, part_two, read_input};
#[test]
fn examples() {
let input = read_input(include_str!("../../input/day04_example.txt"));
let part_one_res = part_one(input.clone());
assert_eq!(part_one_res, 2);
let part_two_res = part_two(input.clone());
assert_eq!(part_two_res, 4);
}
}
| true |
9068d1e23634a15415e26a05a7eb6262ae7ad301
|
Rust
|
hashedone/rust-tutorial
|
/1-hello/echo/src/main.rs
|
UTF-8
| 175 | 2.53125 | 3 |
[
"MIT"
] |
permissive
|
use std::io::{stdin, BufReader, BufRead};
fn main() {
let lines = BufReader::new(stdin()).lines();
for line in lines {
println!("{}", line.unwrap());
}
}
| true |
5f0829c00030a1678bbe673519f9c71b7cc46d72
|
Rust
|
IThawk/rust-project
|
/rust-master/src/test/ui/macros/macro-at-most-once-rep-2015-rpass.rs
|
UTF-8
| 999 | 3.453125 | 3 |
[
"MIT",
"LicenseRef-scancode-other-permissive",
"Apache-2.0",
"BSD-3-Clause",
"BSD-2-Clause",
"NCSA"
] |
permissive
|
// run-pass
#![allow(unused_mut)]
// Check that when `?` is followed by what looks like a Kleene operator (?, +, and *)
// then that `?` is not interpreted as a separator. In other words, `$(pat)?+` matches `pat +`
// or `+` but does not match `pat` or `pat ? pat`.
// edition:2015
macro_rules! foo {
// Check for `?`.
($($a:ident)? ? $num:expr) => {
foo!($($a)? ; $num);
};
// Check for `+`.
($($a:ident)? + $num:expr) => {
foo!($($a)? ; $num);
};
// Check for `*`.
($($a:ident)? * $num:expr) => {
foo!($($a)? ; $num);
};
// Check for `;`, not a kleene operator.
($($a:ident)? ; $num:expr) => {
let mut x = 0;
$(
x += $a;
)?
assert_eq!(x, $num);
};
}
pub fn main() {
let a = 1;
// Accept 0 repetitions.
foo!( ; 0);
foo!( + 0);
foo!( * 0);
foo!( ? 0);
// Accept 1 repetition.
foo!(a ; 1);
foo!(a + 1);
foo!(a * 1);
foo!(a ? 1);
}
| true |
50a0f52b2244653c57476e9b49fbef72b08ae239
|
Rust
|
mrsun-97/SYXrepo
|
/rs_projects/HBTlib/src/lib.rs
|
UTF-8
| 568 | 2.71875 | 3 |
[] |
no_license
|
#[no_mangle]
use std::cmp::Ordering;
pub extern fn concu(p_stam:Vec<f64>, p_chan:Vec<f64>, num: usize, step: f64) -> i32 {
let len = p_stam.len();
if len <= num {
return -1;
}
let count: i32 = 0;
let mut arr: Vec<(f64,f64)> = Vec::with_capacity(num);
for i in 0..num {
arr.push((p_stam[i], p_chan[i]));
}
arr.sort_by(
|a1, a2| a1.partial_cmp(a2).unwrap_or(Ordering::Greater)
);
//未完待续
count
}
#[cfg(test)]
mod tests {
#[test]
fn it_works() {
assert_eq!(2 + 2, 4);
}
}
| true |
5587acc7eec8557ff79e806e0e55b0b9f6af4e4a
|
Rust
|
akiles/embassy
|
/embassy-stm32/src/subghz/fallback_mode.rs
|
UTF-8
| 938 | 3.09375 | 3 |
[
"Apache-2.0",
"MIT"
] |
permissive
|
/// Fallback mode after successful packet transmission or packet reception.
///
/// Argument of [`set_tx_rx_fallback_mode`].
///
/// [`set_tx_rx_fallback_mode`]: crate::subghz::SubGhz::set_tx_rx_fallback_mode.
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
#[repr(u8)]
pub enum FallbackMode {
/// Standby mode entry.
Standby = 0x20,
/// Standby with HSE32 enabled.
StandbyHse = 0x30,
/// Frequency synthesizer entry.
Fs = 0x40,
}
impl From<FallbackMode> for u8 {
fn from(fm: FallbackMode) -> Self {
fm as u8
}
}
impl Default for FallbackMode {
/// Default fallback mode after power-on reset.
///
/// # Example
///
/// ```
/// use stm32wlxx_hal::subghz::FallbackMode;
///
/// assert_eq!(FallbackMode::default(), FallbackMode::Standby);
/// ```
fn default() -> Self {
FallbackMode::Standby
}
}
| true |
9a0890ce7ff9a3669568d80001e2d3ef2cc9e70e
|
Rust
|
mm304321141/rush
|
/src/xlib/rs64/double.rs
|
UTF-8
| 2,904 | 2.765625 | 3 |
[
"MIT"
] |
permissive
|
class double
{
rd64 m_in
~double()
{
}
double()
{
}
double(double a)
{
mov64 rsi,this
mov64 [rsi],a
}
double(double& a)
{
mov64 rdi,this
mov64 rsi,a
mov64 [rdi],[rsi]
}
//这个整数转浮点很慢
double(int a)
{
rstr s(a)
xf.sscanf(s.cstr,"%lf",&this)
}
double(uint a)
{
rstr s(a)
xf.sscanf(s.cstr,"%lf",&this)
}
double(float a)
{
push this
push a
calle "f_to_d",8
add esp,8
}
TYPE to<TYPE>()
{
xf.error
}
template<>
double to<double>()
{
return todouble()
}
template<>
float to<float>()
{
return tofloat()
}
template<>
int to<int>()
{
return toint()
}
double todouble()
{
mov64 rsi,this
mov64 s_ret,[rsi]
}
int toint()
{
rbuf<char> buf(128)
xf.sprintf64(buf.begin,"%.0lf",this)
return rstr(buf.begin).toint
}
rstr torstr()
{
rstr ret(this)
return ret
}
float tofloat()
{
lea esi,[ebp+s_off s_ret]
push esi
push this
calle "d_to_f",8
add esp,8
}
friend double operator neg(double a)
{
return 0.0-a;
}
void operator=(double a)
{
mov64 rsi,this
mov64 [rsi],a
}
void operator=(double& a)
{
mov64 rdi,this
mov64 rsi,a
mov64 [rdi],[rsi]
}
friend void operator<->(double& a,double& b)
{
c=a
a=b
b=c
}
void operator+=(double a)
{
sub rsp,40
mov64 rcx,this
lea rdx,a
calle "faddl"
add rsp,40
}
void operator-=(double a)
{
sub rsp,40
mov64 rcx,this
lea rdx,a
calle "fsubl"
add rsp,40
}
void operator*=(double a)
{
sub rsp,40
mov64 rcx,this
lea rdx,a
calle "fmull"
add rsp,40
}
void operator/=(double a)
{
sub rsp,40
mov64 rcx,this
lea rdx,a
calle "fdivl"
add rsp,40
}
friend double operator+(double a,double b)
{
a+=b
return a
}
friend double operator-(double a,double b)
{
a-=b
return a
}
friend double operator*(double a,double b)
{
a*=b
return a
}
friend double operator/(double a,double b)
{
a/=b
return a
}
friend bool operator<(double a,double b)
{
sub rsp,40
lea rcx,a
lea rdx,b
calle "fclsbl"
mov s_ret,eax
add rsp,40
}
friend bool operator<=(double a,double b)
{
return a<b||a==b;
}
friend bool operator==(double a,double b)
{
cesb a,b
if (ebx)
{
cesb [ebp+(s_off a+4)],[ebp+(s_off b+4)]
}
mov s_ret,ebx
}
friend bool operator!=(double a,double b)
{
return !(a==b)
}
friend bool operator>(double a,double b)
{
return b<a;
}
friend bool operator>=(double a,double b)
{
return a>b||a==b;
}
static double infinity()
{
xf.memcpy(&s_ret,"\x7F\xF0\x00\x00\x00\x00\x00\x00",8);
}
double abs()
{
if this<0.0
return 0.0-this
return this
}
}
| true |
56287ed1b3d10f89aa48654f1dbac33451dee0f9
|
Rust
|
rgambee/advent-of-code
|
/2021/src/day02/solution02.rs
|
UTF-8
| 1,746 | 3.140625 | 3 |
[] |
no_license
|
use crate::util;
use std::fs;
use std::iter::FromIterator;
use std::path;
pub fn solve(input_path: path::PathBuf) -> util::Solution {
let contents = fs::read_to_string(&input_path)
.unwrap_or_else(|_| panic!("Failed to read input file {:?}", input_path));
let line_iter = contents.lines();
let mut horizontal = 0;
let mut depth_part1 = 0;
let mut depth_part2 = 0;
for line in line_iter {
let words = Vec::from_iter(line.split_whitespace());
if words.len() != 2 {
println!("Failed to parse line, skipping: {}", line);
continue;
}
let dir = words[0];
let dist = words[1].parse();
if dist.is_err() {
println!("Failed to parse distance, skipping: {}", line);
continue;
}
let dist: i64 = dist.unwrap();
match dir {
"forward" => {
horizontal += dist;
// aim is equivalent to part 1's notion of depth
depth_part2 += depth_part1 * dist;
}
"up" => depth_part1 -= dist,
"down" => depth_part1 += dist,
_ => {
println!("Failed to parse direction, skipping: {}", line);
continue;
}
};
}
let part1_product = depth_part1 * horizontal;
let part2_product = depth_part2 * horizontal;
util::Solution(
Some(util::PartialSolution {
message: String::from("Product of depth and horizontal distance"),
answer: part1_product,
}),
Some(util::PartialSolution {
message: String::from("Product of depth and horizontal distance"),
answer: part2_product,
}),
)
}
| true |
82855c8dc7368bc6b7a4dbf268c1f4532fd9e680
|
Rust
|
jkordish/shouji
|
/src/main.rs
|
UTF-8
| 3,170 | 2.765625 | 3 |
[
"MIT"
] |
permissive
|
#![cfg_attr(feature="clippy", plugin(clippy))]
#![feature(custom_derive, plugin, custom_attribute, type_macros)]
#![plugin(serde_macros, docopt_macros)]
extern crate serde;
extern crate serde_json;
extern crate rustc_serialize;
extern crate docopt;
mod actions;
use self::actions::*;
docopt!(Args derive, "
shouji -- interface with consul
Usage:
shouji [options] list [<key>]
shouji [options] get [<key>]
shouji [options] put [<key>] [<data>]
shouji [options] rm [<key>]
shouji [options] export [<key>] <file>
shouji [options] import [<file>]
shouji (-h)
Options:
-h, --help show this screen
-v, --verbose be verbose
-s, --server <host> consul server to connect [default: localhost]
-p, --port <port> consul server port to connect [default: 8500]
Action:
list list recursively from location
get get raw value from location
put put data into location
export export to json
import import from json
");
fn main() {
// Decode docopts
let args: Args = Args::docopt()
.decode()
.unwrap_or_else(|e| e.exit());
if args.cmd_get {
// Error conditions
if &args.arg_key == "" {
panic!("Please supply a key to get.");
}
get::new(&args.flag_server,
&args.flag_port,
&args.arg_key,
args.flag_verbose);
} else if args.cmd_put {
// Error conditions
if &args.arg_key == "" {
panic!("Please supply a key to get.");
}
if &args.arg_data == "" {
panic!("Please supply data to put.");
}
put::new(&args.flag_server,
&args.flag_port,
&args.arg_key,
&args.arg_data,
args.flag_verbose);
} else if args.cmd_rm {
// Error conditions
if &args.arg_key == "" {
panic!("Please supply a key to rm.");
}
remove::new(&args.flag_server,
&args.flag_port,
&args.arg_key,
args.flag_verbose);
} else if args.cmd_list {
// Error conditions
// if args.arg_key == None { let Some = String::new(); };
list::new(&args.flag_server,
&args.flag_port,
&args.arg_key,
args.flag_verbose);
} else if args.cmd_export {
// Error conditions
if &args.arg_file == "" {
panic!("Please supply a file to export to.");
}
export::new(&args.flag_server,
&args.flag_port,
&args.arg_key,
&args.arg_file,
args.flag_verbose);
} else if args.cmd_import {
// Error conditions
if &args.arg_file == "" {
panic!("Please supply a file to import.");
}
import::new(&args.flag_server,
&args.flag_port,
&args.arg_file,
args.flag_verbose);
} else {
println!("Not sure what to do");
}
}
| true |
ca8cde43cd959ce6b1e91247156b1c6919c07750
|
Rust
|
DorianListens/advent2017
|
/src/day_one/mod.rs
|
UTF-8
| 639 | 2.859375 | 3 |
[] |
no_license
|
#[cfg(test)]
mod tests;
pub mod input;
pub fn rotated_inverse_captcha(input: &str) -> u32 {
let advanced_by_half = input
.chars()
.cycle()
.skip(input.len() / 2)
.take(input.len());
input
.chars()
.zip(advanced_by_half)
.filter(|x| x.0 == x.1)
.filter_map(|x| x.0.to_digit(10))
.sum()
}
pub fn inverse_captcha(input: &str) -> u32 {
let advanced_by_one = input.chars().cycle().skip(1).take(input.len());
input
.chars()
.zip(advanced_by_one)
.filter(|x| x.0 == x.1)
.filter_map(|x| x.0.to_digit(10))
.sum()
}
| true |
74c88c9177e86bc7b72fb4fc47dd4dedbb51f5b5
|
Rust
|
sailingchannels/crawler
|
/src/repos/additional_channel_repo.rs
|
UTF-8
| 1,225 | 2.84375 | 3 |
[] |
no_license
|
use anyhow::Error;
use futures::stream::TryStreamExt;
use mongodb::bson::{doc, Document};
use mongodb::{Client, Collection};
use crate::utils::db::get_db_name;
pub struct AdditionalChannelRepository {
collection: Collection<Document>,
}
impl AdditionalChannelRepository {
pub fn new(client: &Client, environment: &str) -> AdditionalChannelRepository {
let db = client.database(&get_db_name(&environment));
let feeds = db.collection::<Document>("additional");
AdditionalChannelRepository { collection: feeds }
}
pub async fn exists(&self, channel_id: &str) -> Result<bool, Error> {
let result = self
.collection
.count_documents(doc! { "_id": channel_id }, None)
.await?;
Ok(result > 0)
}
pub async fn get_all(&self) -> Result<Vec<Document>, Error> {
let cursor = self.collection.find(None, None).await?;
let additional_channels: Vec<Document> = cursor.try_collect().await?;
Ok(additional_channels)
}
pub async fn delete_one(&self, id: &str) -> Result<(), Error> {
let filter = doc! {"_id": id};
self.collection.delete_one(filter, None).await?;
Ok(())
}
}
| true |
fd2a097449c6909ebb21ee4fd7829dc37ca4fd14
|
Rust
|
katyo/literium
|
/rust/backend/src/auth/method/native.rs
|
UTF-8
| 2,188 | 2.796875 | 3 |
[
"MIT"
] |
permissive
|
/*!
### Native auth
This method provides classic authorization with *username* and *password*.
*/
use auth::{AuthError, IsAuthMethod};
use base::BoxFuture;
use futures::Future;
use user::{verify_password, HasPasswordHash, HasUserStorage, IsUserStorage};
/// Native auth method information
#[derive(Debug, Serialize)]
pub struct AuthInfo {
pub native: bool,
}
/// Native auth user identification
#[derive(Debug, Deserialize)]
pub enum UserIdent {
#[serde(rename = "native")]
Native { name: String, pass: String },
}
/// Native auth method
#[derive(Clone, Copy)]
pub struct NativeAuth;
impl<S> IsAuthMethod<S> for NativeAuth
where
S: HasUserStorage,
<S::UserStorage as IsUserStorage>::User: HasPasswordHash,
{
type AuthInfo = AuthInfo;
type UserIdent = UserIdent;
fn get_auth_info(&self, _state: &S) -> Self::AuthInfo {
AuthInfo { native: true }
}
fn try_user_auth(
&self,
state: &S,
ident: &Self::UserIdent,
) -> BoxFuture<<S::UserStorage as IsUserStorage>::User, AuthError> {
match ident {
UserIdent::Native { name, pass } => {
let pass = pass.clone();
Box::new(
(state.as_ref() as &S::UserStorage)
.find_user_data(name)
.map_err(|error| {
error!("Error on find_user_data(): {}", error);
AuthError::BackendError
}).and_then(move |user| {
user.and_then(|user| {
let res = if let Some(hash) = user.get_password_hash() {
verify_password(&pass, &hash)
} else {
false
};
if res {
Some(user)
} else {
None
}
}).ok_or(AuthError::BadIdent)
}),
)
}
}
}
}
| true |
a6119b6ef76f4fdace169b9f327038fcca2321a4
|
Rust
|
zhangf911/swiboe
|
/src/ipc.rs
|
UTF-8
| 3,038 | 2.71875 | 3 |
[
"Apache-2.0"
] |
permissive
|
// Copyright (c) The Swiboe development team. All rights reserved.
// Licensed under the Apache License, Version 2.0. See LICENSE.txt
// in the project root for license information.
use ::Result;
use ::rpc;
use mio::{TryRead, TryWrite};
use serde_json;
use std::error::Error;
use std::io::{Read, Write};
#[derive(Serialize, Deserialize, Debug, Clone)]
pub enum Message {
RpcCall(rpc::Call),
RpcResponse(rpc::Response),
RpcCancel(rpc::Cancel),
}
pub struct Reader<T: Read> {
pub socket: T,
read_buffer: Vec<u8>,
}
impl<T: Read> Reader<T> {
pub fn new(socket: T) -> Self {
Reader {
socket: socket,
read_buffer: Vec::with_capacity(1024),
}
}
pub fn read_message(&mut self) -> Result<Option<Message>> {
// This might reallocate 'read_buffer' if it is too small.
try!(self.socket.try_read_buf(&mut self.read_buffer));
// We have read less than 4 bytes. We have to wait for more data to arrive.
if self.read_buffer.len() < 4 {
return Ok(None);
}
let msg_len =
((self.read_buffer[3] as usize) << 24) |
((self.read_buffer[2] as usize) << 16) |
((self.read_buffer[1] as usize) << 8) |
((self.read_buffer[0] as usize) << 0);
if self.read_buffer.len() < msg_len + 4 {
return Ok(None);
}
// NOCOM(#sirver): this should not unwrap.
let msg = String::from_utf8(self.read_buffer.drain(..4+msg_len).skip(4).collect()).unwrap();
let message: Message = try!(serde_json::from_str(&msg));
return Ok(Some(message))
}
}
pub struct Writer<T: Write> {
// The number of bytes already written in to_write[0]. Once all are written, to_write[0] is
// popped.
num_written: usize,
to_write: Vec<Vec<u8>>,
pub socket: T,
}
pub enum WriterState {
MoreToWrite,
AllWritten,
}
impl<T: Write> Writer<T> {
pub fn new(socket: T) -> Self {
Writer {
socket: socket,
num_written: 0,
to_write: Vec::new(),
}
}
pub fn queue_message(&mut self, message: &Message) {
let buffer = serde_json::to_vec(message).unwrap();
let len = vec![
(buffer.len() >> 0) as u8,
(buffer.len() >> 8) as u8,
(buffer.len() >> 16) as u8,
(buffer.len() >> 24) as u8 ];
self.to_write.push(len);
self.to_write.push(buffer);
}
pub fn try_write(&mut self) -> Result<WriterState> {
if self.to_write.is_empty() {
return Ok(WriterState::AllWritten);
}
if let Some(num_written) = try!(self.socket.try_write(&self.to_write[0][self.num_written..])) {
self.num_written += num_written;
}
if self.num_written == self.to_write[0].len() {
self.to_write.remove(0);
self.num_written = 0;
self.try_write()
} else {
Ok(WriterState::MoreToWrite)
}
}
}
| true |
18fb9cbdfea40d41d5ffd86e64e3ffb5cfe093f4
|
Rust
|
KristonCosta/five-am
|
/src/server/map_builders/shop_builder.rs
|
UTF-8
| 1,037 | 2.75 | 3 |
[] |
no_license
|
use crate::geom::Rect;
use crate::map::{Map, TileType};
use crate::server::map_builders::{BaseMapBuilder, BuiltMap};
use rand::prelude::ThreadRng;
pub struct ShopBuilder;
impl BaseMapBuilder for ShopBuilder {
fn build(&mut self, _: &mut ThreadRng, build_data: &mut BuiltMap) {
let size: (i32, i32) = build_data.map.size.to_tuple();
let map = &mut build_data.map;
create_room(
map,
&Rect::new((1, 1).into(), (size.0 - 2, size.1 - 2).into()),
);
build_data.starting_position = Some((size.0 / 2, size.1 / 2).into());
}
}
pub fn create_room(map: &mut Map, room: &Rect) {
let (x_start, y_start) = room.origin.to_tuple();
let (x_end, y_end) = (
(room.origin.x + room.size.width),
(room.origin.y + room.size.height),
);
for x in x_start..x_end {
for y in y_start..y_end {
let index = map.coord_to_index(x, y);
map.tiles[index] = TileType::Floor;
map.blocked[index] = false;
}
}
}
| true |
bb66804b36426234d178b6feef197520639d8e7d
|
Rust
|
Ogeon/palette
|
/palette/src/yxy.rs
|
UTF-8
| 15,961 | 2.59375 | 3 |
[
"Apache-2.0",
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
//! Types for the CIE 1931 Yxy (xyY) color space.
use core::{
marker::PhantomData,
ops::{Add, AddAssign, BitAnd, Div, DivAssign, Mul, MulAssign, Sub, SubAssign},
};
#[cfg(feature = "approx")]
use approx::{AbsDiffEq, RelativeEq, UlpsEq};
#[cfg(feature = "random")]
use rand::{
distributions::{
uniform::{SampleBorrow, SampleUniform, Uniform, UniformSampler},
Distribution, Standard,
},
Rng,
};
use crate::{
blend::{PreAlpha, Premultiply},
bool_mask::{HasBoolMask, LazySelect},
clamp, clamp_assign,
convert::{FromColorUnclamped, IntoColorUnclamped},
encoding::IntoLinear,
luma::LumaStandard,
num::{
self, Arithmetics, FromScalarArray, IntoScalarArray, IsValidDivisor, MinMax, One,
PartialCmp, Real, Zero,
},
stimulus::Stimulus,
white_point::{WhitePoint, D65},
Alpha, Clamp, ClampAssign, IsWithinBounds, Lighten, LightenAssign, Luma, Mix, MixAssign, Xyz,
};
/// CIE 1931 Yxy (xyY) with an alpha component. See the [`Yxya` implementation
/// in `Alpha`](crate::Alpha#Yxya).
pub type Yxya<Wp = D65, T = f32> = Alpha<Yxy<Wp, T>, T>;
/// The CIE 1931 Yxy (xyY) color space.
///
/// Yxy is a luminance-chromaticity color space derived from the CIE XYZ
/// color space. It is widely used to define colors. The chromaticity diagrams
/// for the color spaces are a plot of this color space's x and y coordinates.
///
/// Conversions and operations on this color space depend on the white point.
#[derive(Debug, ArrayCast, FromColorUnclamped, WithAlpha)]
#[cfg_attr(feature = "serializing", derive(Serialize, Deserialize))]
#[palette(
palette_internal,
white_point = "Wp",
component = "T",
skip_derives(Xyz, Yxy, Luma)
)]
#[repr(C)]
#[doc(alias = "xyY")]
pub struct Yxy<Wp = D65, T = f32> {
/// x chromaticity co-ordinate derived from XYZ color space as X/(X+Y+Z).
/// Typical range is between 0 and 1
pub x: T,
/// y chromaticity co-ordinate derived from XYZ color space as Y/(X+Y+Z).
/// Typical range is between 0 and 1
pub y: T,
/// luma (Y) was a measure of the brightness or luminance of a color.
/// It is the same as the Y from the XYZ color space. Its range is from
///0 to 1, where 0 is black and 1 is white.
pub luma: T,
/// The white point associated with the color's illuminant and observer.
/// D65 for 2 degree observer is used by default.
#[cfg_attr(feature = "serializing", serde(skip))]
#[palette(unsafe_zero_sized)]
pub white_point: PhantomData<Wp>,
}
impl<Wp, T> Copy for Yxy<Wp, T> where T: Copy {}
impl<Wp, T> Clone for Yxy<Wp, T>
where
T: Clone,
{
fn clone(&self) -> Yxy<Wp, T> {
Yxy {
x: self.x.clone(),
y: self.y.clone(),
luma: self.luma.clone(),
white_point: PhantomData,
}
}
}
impl<Wp, T> Yxy<Wp, T> {
/// Create a CIE Yxy color.
pub const fn new(x: T, y: T, luma: T) -> Yxy<Wp, T> {
Yxy {
x,
y,
luma,
white_point: PhantomData,
}
}
/// Convert to a `(x, y, luma)`, a.k.a. `(x, y, Y)` tuple.
pub fn into_components(self) -> (T, T, T) {
(self.x, self.y, self.luma)
}
/// Convert from a `(x, y, luma)`, a.k.a. `(x, y, Y)` tuple.
pub fn from_components((x, y, luma): (T, T, T)) -> Self {
Self::new(x, y, luma)
}
/// Changes the reference white point without changing the color value.
///
/// This function doesn't change the numerical values, and thus the color it
/// represents in an absolute sense. However, the appearance of the color
/// may not be the same when observed with the new white point. The effect
/// would be similar to taking a photo with an incorrect white balance.
///
/// See [chromatic_adaptation](crate::chromatic_adaptation) for operations
/// that can change the white point while preserving the color's appearance.
#[inline]
pub fn with_white_point<NewWp>(self) -> Yxy<NewWp, T> {
Yxy::new(self.x, self.y, self.luma)
}
}
impl<Wp, T> Yxy<Wp, T>
where
T: Zero + One,
{
/// Return the `x` value minimum.
pub fn min_x() -> T {
T::zero()
}
/// Return the `x` value maximum.
pub fn max_x() -> T {
T::one()
}
/// Return the `y` value minimum.
pub fn min_y() -> T {
T::zero()
}
/// Return the `y` value maximum.
pub fn max_y() -> T {
T::one()
}
/// Return the `luma` value minimum.
pub fn min_luma() -> T {
T::zero()
}
/// Return the `luma` value maximum.
pub fn max_luma() -> T {
T::one()
}
}
///<span id="Yxya"></span>[`Yxya`](crate::Yxya) implementations.
impl<Wp, T, A> Alpha<Yxy<Wp, T>, A> {
/// Create a CIE Yxy color with transparency.
pub const fn new(x: T, y: T, luma: T, alpha: A) -> Self {
Alpha {
color: Yxy::new(x, y, luma),
alpha,
}
}
/// Convert to a `(x, y, luma)`, a.k.a. `(x, y, Y)` tuple.
pub fn into_components(self) -> (T, T, T, A) {
(self.color.x, self.color.y, self.color.luma, self.alpha)
}
/// Convert from a `(x, y, luma)`, a.k.a. `(x, y, Y)` tuple.
pub fn from_components((x, y, luma, alpha): (T, T, T, A)) -> Self {
Self::new(x, y, luma, alpha)
}
/// Changes the reference white point without changing the color value.
///
/// This function doesn't change the numerical values, and thus the color it
/// represents in an absolute sense. However, the appearance of the color
/// may not be the same when observed with the new white point. The effect
/// would be similar to taking a photo with an incorrect white balance.
///
/// See [chromatic_adaptation](crate::chromatic_adaptation) for operations
/// that can change the white point while preserving the color's appearance.
#[inline]
pub fn with_white_point<NewWp>(self) -> Alpha<Yxy<NewWp, T>, A> {
Alpha::<Yxy<NewWp, T>, A>::new(self.color.x, self.color.y, self.color.luma, self.alpha)
}
}
impl_reference_component_methods!(Yxy<Wp>, [x, y, luma], white_point);
impl_struct_of_arrays_methods!(Yxy<Wp>, [x, y, luma], white_point);
impl<Wp, T> From<(T, T, T)> for Yxy<Wp, T> {
fn from(components: (T, T, T)) -> Self {
Self::from_components(components)
}
}
impl<Wp, T> From<Yxy<Wp, T>> for (T, T, T) {
fn from(color: Yxy<Wp, T>) -> (T, T, T) {
color.into_components()
}
}
impl<Wp, T, A> From<(T, T, T, A)> for Alpha<Yxy<Wp, T>, A> {
fn from(components: (T, T, T, A)) -> Self {
Self::from_components(components)
}
}
impl<Wp, T, A> From<Alpha<Yxy<Wp, T>, A>> for (T, T, T, A) {
fn from(color: Alpha<Yxy<Wp, T>, A>) -> (T, T, T, A) {
color.into_components()
}
}
impl<Wp, T> FromColorUnclamped<Yxy<Wp, T>> for Yxy<Wp, T> {
fn from_color_unclamped(color: Yxy<Wp, T>) -> Self {
color
}
}
impl<Wp, T> FromColorUnclamped<Xyz<Wp, T>> for Yxy<Wp, T>
where
T: Zero + IsValidDivisor + Arithmetics + Clone,
T::Mask: LazySelect<T> + Clone,
{
fn from_color_unclamped(xyz: Xyz<Wp, T>) -> Self {
let Xyz { x, y, z, .. } = xyz;
let sum = x.clone() + &y + z;
// If denominator is zero, NAN or INFINITE leave x and y at the default 0
let mask = sum.is_valid_divisor();
Yxy {
x: lazy_select! {
if mask.clone() => x / &sum,
else => T::zero(),
},
y: lazy_select! {
if mask => y.clone() / sum,
else => T::zero()
},
luma: y,
white_point: PhantomData,
}
}
}
impl<T, S> FromColorUnclamped<Luma<S, T>> for Yxy<S::WhitePoint, T>
where
S: LumaStandard,
S::TransferFn: IntoLinear<T, T>,
Self: Default,
{
fn from_color_unclamped(luma: Luma<S, T>) -> Self {
Yxy {
luma: luma.into_linear().luma,
..Default::default()
}
}
}
impl_is_within_bounds! {
Yxy<Wp> {
x => [Self::min_x(), Self::max_x()],
y => [Self::min_y(), Self::max_y()],
luma => [Self::min_luma(), Self::max_luma()]
}
where T: Zero + One
}
impl<Wp, T> Clamp for Yxy<Wp, T>
where
T: Zero + One + num::Clamp,
{
#[inline]
fn clamp(self) -> Self {
Self::new(
clamp(self.x, Self::min_x(), Self::max_x()),
clamp(self.y, Self::min_y(), Self::max_y()),
clamp(self.luma, Self::min_luma(), Self::max_luma()),
)
}
}
impl<Wp, T> ClampAssign for Yxy<Wp, T>
where
T: Zero + One + num::ClampAssign,
{
#[inline]
fn clamp_assign(&mut self) {
clamp_assign(&mut self.x, Self::min_x(), Self::max_x());
clamp_assign(&mut self.y, Self::min_y(), Self::max_y());
clamp_assign(&mut self.luma, Self::min_luma(), Self::max_luma());
}
}
impl_mix!(Yxy<Wp>);
impl_lighten!(Yxy<Wp> increase {luma => [Self::min_luma(), Self::max_luma()]} other {x, y} phantom: white_point where T: One);
impl_premultiply!(Yxy<Wp> {x, y, luma} phantom: white_point);
impl_euclidean_distance!(Yxy<Wp> {x, y, luma});
impl<Wp, T> HasBoolMask for Yxy<Wp, T>
where
T: HasBoolMask,
{
type Mask = T::Mask;
}
impl<Wp, T> Default for Yxy<Wp, T>
where
T: Zero,
Wp: WhitePoint<T>,
Xyz<Wp, T>: IntoColorUnclamped<Self>,
{
fn default() -> Yxy<Wp, T> {
// The default for x and y are the white point x and y ( from the default D65).
// Since Y (luma) is 0.0, this makes the default color black just like for
// other colors. The reason for not using 0 for x and y is that this
// outside the usual color gamut and might cause scaling issues.
Yxy {
luma: T::zero(),
..Wp::get_xyz().with_white_point().into_color_unclamped()
}
}
}
impl_color_add!(Yxy<Wp, T>, [x, y, luma], white_point);
impl_color_sub!(Yxy<Wp, T>, [x, y, luma], white_point);
impl_color_mul!(Yxy<Wp, T>, [x, y, luma], white_point);
impl_color_div!(Yxy<Wp, T>, [x, y, luma], white_point);
impl_array_casts!(Yxy<Wp, T>, [T; 3]);
impl_simd_array_conversion!(Yxy<Wp>, [x, y, luma], white_point);
impl_struct_of_array_traits!(Yxy<Wp>, [x, y, luma], white_point);
impl_eq!(Yxy<Wp>, [y, x, luma]);
#[allow(deprecated)]
impl<Wp, T> crate::RelativeContrast for Yxy<Wp, T>
where
T: Real + Arithmetics + PartialCmp,
T::Mask: LazySelect<T>,
{
type Scalar = T;
#[inline]
fn get_contrast_ratio(self, other: Self) -> T {
crate::contrast_ratio(self.luma, other.luma)
}
}
#[cfg(feature = "random")]
impl<Wp, T> Distribution<Yxy<Wp, T>> for Standard
where
Standard: Distribution<T>,
{
fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> Yxy<Wp, T> {
Yxy {
x: rng.gen(),
y: rng.gen(),
luma: rng.gen(),
white_point: PhantomData,
}
}
}
/// Sample CIE 1931 Yxy (xyY) colors uniformly.
#[cfg(feature = "random")]
pub struct UniformYxy<Wp, T>
where
T: SampleUniform,
{
x: Uniform<T>,
y: Uniform<T>,
luma: Uniform<T>,
white_point: PhantomData<Wp>,
}
#[cfg(feature = "random")]
impl<Wp, T> SampleUniform for Yxy<Wp, T>
where
T: Clone + SampleUniform,
{
type Sampler = UniformYxy<Wp, T>;
}
#[cfg(feature = "random")]
impl<Wp, T> UniformSampler for UniformYxy<Wp, T>
where
T: Clone + SampleUniform,
{
type X = Yxy<Wp, T>;
fn new<B1, B2>(low_b: B1, high_b: B2) -> Self
where
B1: SampleBorrow<Self::X> + Sized,
B2: SampleBorrow<Self::X> + Sized,
{
let low = low_b.borrow();
let high = high_b.borrow();
UniformYxy {
x: Uniform::new::<_, T>(low.x.clone(), high.x.clone()),
y: Uniform::new::<_, T>(low.y.clone(), high.y.clone()),
luma: Uniform::new::<_, T>(low.luma.clone(), high.luma.clone()),
white_point: PhantomData,
}
}
fn new_inclusive<B1, B2>(low_b: B1, high_b: B2) -> Self
where
B1: SampleBorrow<Self::X> + Sized,
B2: SampleBorrow<Self::X> + Sized,
{
let low = low_b.borrow();
let high = high_b.borrow();
UniformYxy {
x: Uniform::new_inclusive::<_, T>(low.x.clone(), high.x.clone()),
y: Uniform::new_inclusive::<_, T>(low.y.clone(), high.y.clone()),
luma: Uniform::new_inclusive::<_, T>(low.luma.clone(), high.luma.clone()),
white_point: PhantomData,
}
}
fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> Yxy<Wp, T> {
Yxy {
x: self.x.sample(rng),
y: self.y.sample(rng),
luma: self.luma.sample(rng),
white_point: PhantomData,
}
}
}
#[cfg(feature = "bytemuck")]
unsafe impl<Wp, T> bytemuck::Zeroable for Yxy<Wp, T> where T: bytemuck::Zeroable {}
#[cfg(feature = "bytemuck")]
unsafe impl<Wp: 'static, T> bytemuck::Pod for Yxy<Wp, T> where T: bytemuck::Pod {}
#[cfg(test)]
mod test {
use super::Yxy;
use crate::white_point::D65;
use crate::{FromColor, LinLuma, LinSrgb};
test_convert_into_from_xyz!(Yxy);
#[test]
fn luma() {
let a = Yxy::<D65>::from_color(LinLuma::new(0.5));
let b = Yxy::new(0.312727, 0.329023, 0.5);
assert_relative_eq!(a, b, epsilon = 0.000001);
}
#[test]
fn red() {
let a = Yxy::from_color(LinSrgb::new(1.0, 0.0, 0.0));
let b = Yxy::new(0.64, 0.33, 0.212673);
assert_relative_eq!(a, b, epsilon = 0.000001);
}
#[test]
fn green() {
let a = Yxy::from_color(LinSrgb::new(0.0, 1.0, 0.0));
let b = Yxy::new(0.3, 0.6, 0.715152);
assert_relative_eq!(a, b, epsilon = 0.000001);
}
#[test]
fn blue() {
let a = Yxy::from_color(LinSrgb::new(0.0, 0.0, 1.0));
let b = Yxy::new(0.15, 0.06, 0.072175);
assert_relative_eq!(a, b, epsilon = 0.000001);
}
#[test]
fn ranges() {
assert_ranges! {
Yxy<D65, f64>;
clamped {
x: 0.0 => 1.0,
y: 0.0 => 1.0,
luma: 0.0 => 1.0
}
clamped_min {}
unclamped {}
}
}
raw_pixel_conversion_tests!(Yxy<D65>: x, y, luma);
raw_pixel_conversion_fail_tests!(Yxy<D65>: x, y, luma);
#[test]
fn check_min_max_components() {
assert_relative_eq!(Yxy::<D65>::min_x(), 0.0);
assert_relative_eq!(Yxy::<D65>::min_y(), 0.0);
assert_relative_eq!(Yxy::<D65>::min_luma(), 0.0);
assert_relative_eq!(Yxy::<D65>::max_x(), 1.0);
assert_relative_eq!(Yxy::<D65>::max_y(), 1.0);
assert_relative_eq!(Yxy::<D65>::max_luma(), 1.0);
}
struct_of_arrays_tests!(
Yxy<D65>,
Yxy::new(0.1f32, 0.2, 0.3),
Yxy::new(0.2, 0.3, 0.4),
Yxy::new(0.3, 0.4, 0.5)
);
mod alpha {
use crate::{white_point::D65, yxy::Yxya};
struct_of_arrays_tests!(
Yxya<D65>,
Yxya::new(0.1f32, 0.2, 0.3, 0.4),
Yxya::new(0.2, 0.3, 0.4, 0.5),
Yxya::new(0.3, 0.4, 0.5, 0.6)
);
}
#[cfg(feature = "serializing")]
#[test]
fn serialize() {
let serialized = ::serde_json::to_string(&Yxy::<D65>::new(0.3, 0.8, 0.1)).unwrap();
assert_eq!(serialized, r#"{"x":0.3,"y":0.8,"luma":0.1}"#);
}
#[cfg(feature = "serializing")]
#[test]
fn deserialize() {
let deserialized: Yxy = ::serde_json::from_str(r#"{"x":0.3,"y":0.8,"luma":0.1}"#).unwrap();
assert_eq!(deserialized, Yxy::new(0.3, 0.8, 0.1));
}
#[cfg(feature = "random")]
test_uniform_distribution! {
Yxy<D65, f32> {
x: (0.0, 1.0),
y: (0.0, 1.0),
luma: (0.0, 1.0)
},
min: Yxy::new(0.0f32, 0.0, 0.0),
max: Yxy::new(1.0, 1.0, 1.0),
}
}
| true |
c23ca69b25f13d03e5b8e5bde1c41ce70c71f29d
|
Rust
|
jeffrey-xiao/neso-gui
|
/src/config.rs
|
UTF-8
| 16,071 | 3.015625 | 3 |
[
"MIT",
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] |
permissive
|
use log::warn;
use sdl2::controller::Button;
use sdl2::keyboard::Keycode;
use serde::de::{Deserialize, Deserializer, Error, SeqAccess, Unexpected, Visitor};
use serde_derive::Deserialize;
use std::collections::HashMap;
use std::fmt;
use std::fs;
use std::marker::PhantomData;
use std::path::{Path, PathBuf};
use std::str;
use toml::{value, Value};
const CONTROLLER_FIELDS: [&str; 8] = ["a", "b", "select", "start", "up", "down", "left", "right"];
#[derive(Clone, Copy, Eq, Hash, PartialEq)]
pub enum KeybindingValue {
ButtonValue(Button),
KeycodeValue(Keycode),
}
impl KeybindingValue {
pub fn from_string(controller_type: &ControllerType, value: &str) -> Option<KeybindingValue> {
if *controller_type == ControllerType::Keyboard {
Keycode::from_name(value).map(KeybindingValue::KeycodeValue)
} else {
Button::from_string(value).map(KeybindingValue::ButtonValue)
}
}
}
struct RawKeybindingValues(Vec<String>);
struct RawKeybindingValuesVisitor(PhantomData<RawKeybindingValues>);
impl<'de> Visitor<'de> for RawKeybindingValuesVisitor {
type Value = RawKeybindingValues;
fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str("keycode string or list of keycode strings")
}
fn visit_str<E>(self, keycode_name: &str) -> Result<Self::Value, E>
where
E: Error,
{
Ok(RawKeybindingValues(vec![keycode_name.to_owned()]))
}
fn visit_seq<S>(self, mut visitor: S) -> Result<Self::Value, S::Error>
where
S: SeqAccess<'de>,
{
let mut value = visitor.next_element::<String>()?;
let mut keycodes = Vec::new();
while let Some(keycode_name) = value {
keycodes.push(keycode_name);
value = visitor.next_element::<String>()?;
}
Ok(RawKeybindingValues(keycodes))
}
}
impl<'de> Deserialize<'de> for RawKeybindingValues {
fn deserialize<D>(deserializer: D) -> Result<RawKeybindingValues, D::Error>
where
D: Deserializer<'de>,
{
deserializer.deserialize_any(RawKeybindingValuesVisitor(PhantomData))
}
}
#[derive(Deserialize, PartialEq)]
pub enum ControllerType {
Controller,
Keyboard,
}
#[derive(Deserialize)]
struct RawKeybindingConfig {
#[serde(rename = "type")]
controller_type: ControllerType,
#[serde(flatten)]
raw_keybindings: HashMap<String, RawKeybindingValues>,
}
impl RawKeybindingConfig {
fn default_keyboard() -> Self {
RawKeybindingConfig {
controller_type: ControllerType::Keyboard,
raw_keybindings: vec![
("a".to_string(), RawKeybindingValues(vec!["P".to_owned()])),
("b".to_string(), RawKeybindingValues(vec!["O".to_owned()])),
(
"select".to_string(),
RawKeybindingValues(vec!["Left Shift".to_owned(), "Right Shift".to_owned()]),
),
(
"start".to_string(),
RawKeybindingValues(vec!["Return".to_owned()]),
),
("up".to_string(), RawKeybindingValues(vec!["W".to_owned()])),
(
"down".to_string(),
RawKeybindingValues(vec!["S".to_owned()]),
),
(
"left".to_string(),
RawKeybindingValues(vec!["A".to_owned()]),
),
(
"right".to_string(),
RawKeybindingValues(vec!["D".to_owned()]),
),
]
.into_iter()
.collect(),
}
}
fn default_controller() -> Self {
RawKeybindingConfig {
controller_type: ControllerType::Controller,
raw_keybindings: vec![
("a".to_string(), RawKeybindingValues(vec!["a".to_owned()])),
("b".to_string(), RawKeybindingValues(vec!["b".to_owned()])),
(
"select".to_string(),
RawKeybindingValues(vec!["back".to_owned()]),
),
(
"start".to_string(),
RawKeybindingValues(vec!["start".to_owned()]),
),
(
"up".to_string(),
RawKeybindingValues(vec!["dpup".to_owned()]),
),
(
"down".to_string(),
RawKeybindingValues(vec!["dpdown".to_owned()]),
),
(
"left".to_string(),
RawKeybindingValues(vec!["dpleft".to_owned()]),
),
(
"right".to_string(),
RawKeybindingValues(vec!["dpright".to_owned()]),
),
]
.into_iter()
.collect(),
}
}
}
pub struct ControllerConfig {
pub keybinding_map: HashMap<KeybindingValue, usize>,
}
impl ControllerConfig {
fn new(keybinding_map: HashMap<KeybindingValue, usize>) -> Self {
ControllerConfig { keybinding_map }
}
}
impl<'de> Deserialize<'de> for ControllerConfig {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
let mut controller_config = ControllerConfig::new(HashMap::new());
let parsed_raw_config = RawKeybindingConfig::deserialize(deserializer)?;
let mut raw_config = if parsed_raw_config.controller_type == ControllerType::Keyboard {
RawKeybindingConfig::default_keyboard()
} else {
RawKeybindingConfig::default_controller()
};
raw_config
.raw_keybindings
.extend(parsed_raw_config.raw_keybindings.into_iter());
let controller_type = raw_config.controller_type;
for entry in raw_config.raw_keybindings {
match CONTROLLER_FIELDS
.iter()
.position(|field| **field == entry.0)
{
Some(index) => {
for raw_keybinding_str in (entry.1).0 {
let keybinding =
KeybindingValue::from_string(&controller_type, &raw_keybinding_str)
.ok_or_else(|| {
let err_msg = if controller_type == ControllerType::Keyboard {
&"a string as a keycode string."
} else {
&"a string as a button name."
};
Error::invalid_value(
Unexpected::Str(&raw_keybinding_str),
err_msg,
)
})?;
controller_config.keybinding_map.insert(keybinding, index);
}
}
None => {
return Err(Error::invalid_value(
Unexpected::Str(&entry.0),
&"a valid controller field",
));
}
}
}
Ok(controller_config)
}
}
impl Default for ControllerConfig {
fn default() -> Self {
ControllerConfig {
keybinding_map: vec![
(KeybindingValue::KeycodeValue(Keycode::P), 0),
(KeybindingValue::KeycodeValue(Keycode::O), 1),
(KeybindingValue::KeycodeValue(Keycode::RShift), 2),
(KeybindingValue::KeycodeValue(Keycode::LShift), 2),
(KeybindingValue::KeycodeValue(Keycode::Return), 3),
(KeybindingValue::KeycodeValue(Keycode::W), 4),
(KeybindingValue::KeycodeValue(Keycode::S), 5),
(KeybindingValue::KeycodeValue(Keycode::A), 6),
(KeybindingValue::KeycodeValue(Keycode::D), 7),
]
.into_iter()
.collect(),
}
}
}
pub struct KeybindingsConfig {
pub mute: Vec<KeybindingValue>,
pub pause: Vec<KeybindingValue>,
pub reset: Vec<KeybindingValue>,
pub exit: Vec<KeybindingValue>,
pub save_state: Vec<KeybindingValue>,
pub load_state: Vec<KeybindingValue>,
pub increase_speed: Vec<KeybindingValue>,
pub decrease_speed: Vec<KeybindingValue>,
}
impl<'de> Deserialize<'de> for KeybindingsConfig {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
let mut keybindings_config = KeybindingsConfig::default();
let raw_config = RawKeybindingConfig::deserialize(deserializer)?;
let controller_type = raw_config.controller_type;
for entry in raw_config.raw_keybindings {
let mut keybindings = Vec::new();
for raw_keybinding_str in (entry.1).0.iter() {
let keybinding =
KeybindingValue::from_string(&controller_type, &raw_keybinding_str)
.ok_or_else(|| {
let err_msg = if controller_type == ControllerType::Keyboard {
&"a string as a keycode string."
} else {
&"a string as a button name."
};
Error::invalid_value(Unexpected::Str(&raw_keybinding_str), err_msg)
})?;
keybindings.push(keybinding);
}
match entry.0.as_ref() {
"mute" => keybindings_config.mute = keybindings,
"pause" => keybindings_config.pause = keybindings,
"reset" => keybindings_config.reset = keybindings,
"exit" => keybindings_config.exit = keybindings,
"save_state" => keybindings_config.save_state = keybindings,
"load_state" => keybindings_config.load_state = keybindings,
"increase_speed" => keybindings_config.increase_speed = keybindings,
"decrease_speed" => keybindings_config.decrease_speed = keybindings,
_ => {
return Err(Error::invalid_value(
Unexpected::Str(&entry.0),
&"a valid controller field",
));
}
}
}
Ok(keybindings_config)
}
}
impl Default for KeybindingsConfig {
fn default() -> Self {
KeybindingsConfig {
mute: vec![KeybindingValue::KeycodeValue(Keycode::M)],
pause: vec![KeybindingValue::KeycodeValue(Keycode::Space)],
reset: vec![KeybindingValue::KeycodeValue(Keycode::R)],
exit: vec![KeybindingValue::KeycodeValue(Keycode::Escape)],
save_state: vec![KeybindingValue::KeycodeValue(Keycode::F1)],
load_state: vec![KeybindingValue::KeycodeValue(Keycode::F2)],
increase_speed: vec![KeybindingValue::KeycodeValue(Keycode::RightBracket)],
decrease_speed: vec![KeybindingValue::KeycodeValue(Keycode::LeftBracket)],
}
}
}
fn get_default_data_path() -> PathBuf {
let xdg_config_home = option_env!("XDG_DATA_HOME");
let config_home_dir = format!("{}/{}", env!("HOME"), ".local/share");
Path::new(xdg_config_home.unwrap_or(&config_home_dir)).join(env!("CARGO_PKG_NAME"))
}
fn parse_table(toml_value: Value, details: &str) -> super::Result<value::Table> {
match toml_value {
toml::Value::Table(table) => Ok(table),
_ => Err(super::Error::from_description("parsing config", details)),
}
}
fn parse_general_config(config: &mut Config, toml_value: Value) -> super::Result<()> {
let toml_table = parse_table(toml_value, "Expected `general` to be a table.")?;
for toml_entry in toml_table {
match toml_entry.0.as_ref() {
"data_path" => {
config.data_path = Path::new(toml_entry.1.as_str().ok_or_else(|| {
super::Error::from_description(
"parsing config",
"Expected `data_path` to be a string.",
)
})?)
.to_owned();
}
_ => {
return Err(super::Error::from_description(
"parsing config",
format!("Unexpected value in `general` table: {}.", toml_entry.0),
));
}
}
}
Ok(())
}
pub fn get_config_path<P>(config_path_opt: Option<P>) -> PathBuf
where
P: AsRef<Path>,
{
match config_path_opt {
Some(config_path) => PathBuf::from(config_path.as_ref()),
None => {
let xdg_config_home = option_env!("XDG_CONFIG_HOME");
let config_home_dir = format!("{}/{}", env!("HOME"), ".config");
Path::new(xdg_config_home.unwrap_or(&config_home_dir))
.join(env!("CARGO_PKG_NAME"))
.join(format!("{}.toml", env!("CARGO_PKG_NAME")))
}
}
}
pub struct Config {
pub data_path: PathBuf,
pub keybindings_config: KeybindingsConfig,
pub controller_configs: [ControllerConfig; 2],
}
impl Config {
pub fn get_save_file<P>(&self, rom_path: P) -> PathBuf
where
P: AsRef<Path>,
{
let save_file_name = rom_path.as_ref().with_extension("sav");
self.data_path.join(
save_file_name
.file_name()
.expect("Expected valid file name."),
)
}
pub fn get_save_state_file<P>(&self, rom_path: P) -> PathBuf
where
P: AsRef<Path>,
{
let save_state_file_name = rom_path.as_ref().with_extension("state");
self.data_path.join(
save_state_file_name
.file_name()
.expect("Expected valid file name."),
)
}
pub fn parse_config<P>(config_path: P) -> super::Result<Config>
where
P: AsRef<Path>,
{
let mut config = Config {
data_path: get_default_data_path(),
keybindings_config: KeybindingsConfig::default(),
controller_configs: [ControllerConfig::default(), ControllerConfig::default()],
};
if !config_path.as_ref().exists() {
return Ok(config);
}
let config_file_buffer =
fs::read(&config_path).map_err(|err| super::Error::new("reading config", &err))?;
let toml_value = str::from_utf8(&config_file_buffer)
.map_err(|err| super::Error::new("reading config", &err))?
.parse::<toml::Value>()
.map_err(|err| super::Error::new("parsing config", &err))?;
let toml_table = parse_table(toml_value, "Expected table at root of config.")?;
for toml_entry in toml_table {
let (toml_key, toml_value) = toml_entry;
match toml_key.as_ref() {
"general" => parse_general_config(&mut config, toml_value)?,
"keybindings" => {
config.keybindings_config = toml_value
.try_into::<KeybindingsConfig>()
.map_err(|err| super::Error::new("parsing keybindings config", &err))?;
}
"port-1" => {
config.controller_configs[0] = toml_value
.try_into::<ControllerConfig>()
.map_err(|err| super::Error::new("parsing port-1 config", &err))?
}
"port-2" => {
config.controller_configs[0] = toml_value
.try_into::<ControllerConfig>()
.map_err(|err| super::Error::new("parsing port-2 config", &err))?
}
_ => warn!("Unexpected value in root of config: {}.", toml_key),
}
}
Ok(config)
}
}
| true |
a2e55a1d0b90785f84576ff23e980d2c85157e17
|
Rust
|
CheaterCodes/AoC2020
|
/day13/src/main.rs
|
UTF-8
| 3,176 | 3.5625 | 4 |
[
"MIT"
] |
permissive
|
use std::{env, error::Error};
use std::fs::File;
use std::io::BufReader;
use std::io::prelude::*;
// Convenience macro for generating errors
macro_rules! error {
($($arg:tt)*) => {{
let res = format!($($arg)*);
Box::<dyn Error>::from(res)
}};
}
// Build and run with `cargo run -- ./input.txt` from the day1 base dir
fn main() -> Result<(), Box<dyn Error>> {
// Get commandline arguments
let args: Vec<String> = env::args().collect();
// Open file
let path = args.get(1).ok_or(error!("Usage: cargo run -- <input file>"))?;
let file = File::open(path)?;
// Read file
let mut lines = BufReader::new(file).lines();
let start_time: i32 = lines.next().ok_or(error!("Missing input!"))??.parse()?;
let intervals: Vec<Option<i32>> = lines.next().ok_or(error!("Missing input!"))??.split(',').map(|s| s.parse().ok()).collect();
let existing_intervals: Vec<i32> = intervals.iter().filter_map(|&i| i).collect();
let wait_time: Vec<i32> = existing_intervals.iter().map(|&i| i - (start_time - (start_time - 1) / i * i)).collect();
let earliest = wait_time.iter().zip(existing_intervals.iter()).min_by_key(|&(&wait, &_interval)| wait).unwrap();
println!("Bus line {} departs after {} minutes.", earliest.1, earliest.0);
println!("Result: {}", earliest.0 * earliest.1);
/* Part Two
Given a list of numbers 13,x,x,41,x,x,x,37,...
Find a number t so that
13 * k13 - 0 = t
41 * k41 - 3 = t
37 * k37 - 7 = t
...
Or as modulo arithmetic:
t = 0 mod 1
t = 13 - 0 mod 13
t = 41 - 3 mod 41
t = 37 - 7 mod 37
...
Note: The numbers appear to all be prime!
Idea:
- Increment until first equation is satisfied
- Now increment by 'line 1' until second equation is satisfied.
- Incrementing this way makes sure equation one stays satisfied
- This way you need to invrement at most "line 2' times"
- Now increment by 'line 1' * 'line 2' until third equation is satisfied.
- Incrementing this way makes sure equation one and two stay satisfied
- This way you need to invrement at most "line 3' times"
- Rinse and repeat
Complexity: O(n*m) where
- n is the number of lines
- m is the value of the biggest/average line
Possible Improvement:
The inner loop could probably be sped up by the extended euclidean algorithm
*/
let line_and_offset: Vec<(usize, usize)> = intervals.iter().enumerate().filter_map(|(i, &line)| line.map(|line| (line as usize, ((line - (i as i32 % line)) % line) as usize))).collect();
let mut t: u128 = 1;
let mut increment: u128 = 1;
for &(line, offset) in &line_and_offset {
while t % line as u128 != offset as u128 {
t += increment;
}
increment *= line as u128;
println!("Checked line {}\n- Current t = {}\n- Current increment = {}", line, t, increment);
}
println!("Solution: {}", t);
// Everything ok!
Ok(())
}
| true |
7dbc1d99475c52b60a205c11cac331f95b783d1a
|
Rust
|
dakom/awsm-renderer
|
/crate/src/image.rs
|
UTF-8
| 4,850 | 2.53125 | 3 |
[
"MIT",
"Apache-2.0",
"BSD-2-Clause"
] |
permissive
|
use std::io::Cursor;
use crate::prelude::*;
use awsm_web::{loaders::{fetch::fetch_url, image::load as fetch_image}, data::{ArrayBufferExt, TypedData}, webgl::{TextureTarget, TextureOptions, PixelInternalFormat, DataType, PixelDataFormat, TextureWrapTarget, TextureWrapMode, TextureMinFilter, TextureMagFilter, WebGlTextureSource, PartialWebGlTextures}};
use exr::prelude::{ReadChannels, ReadLayers, ChannelDescription};
use js_sys::Float32Array;
use web_sys::{ImageData, HtmlImageElement, WebGl2RenderingContext};
pub enum ImageLoader {
Exr(ExrImage),
HtmlImage(HtmlImageElement)
}
impl ImageLoader {
pub async fn load_url(url:&str) -> Result<Self> {
if url.contains(".exr") {
let exr_image = ExrImage::load_url(url).await?;
Ok(Self::Exr(exr_image))
} else {
let image = fetch_image(url.to_string()).await?;
Ok(Self::HtmlImage(image))
}
}
pub fn size(&self) -> (usize, usize) {
match self {
Self::Exr(exr) => (exr.width, exr.height),
Self::HtmlImage(img) => (img.width() as usize, img.height() as usize)
}
}
pub fn to_texture(&self, renderer: &mut AwsmRenderer) -> Result<Id> {
let gl = &mut renderer.gl;
let id = gl.create_texture()?;
match self {
Self::Exr(exr) => {
let data:Float32Array = TypedData::new(&exr.data).into();
gl.assign_texture(
id,
TextureTarget::Texture2d,
&TextureOptions{
internal_format: PixelInternalFormat::Rgba32f,
data_type: DataType::Float,
data_format: PixelDataFormat::Rgba,
cube_face: None
},
Some(|gl:&WebGl2RenderingContext| {
//gl.pixel_storei(WebGlSpecific::UnpackFlipY as u32, 1);
//gl.pixel_storei(WebGlSpecific::UnpackColorspaceConversion as u32, 0);
gl.awsm_texture_set_wrap(TextureTarget::Texture2d, TextureWrapTarget::S, TextureWrapMode::MirroredRepeat);
gl.awsm_texture_set_wrap(TextureTarget::Texture2d, TextureWrapTarget::T, TextureWrapMode::MirroredRepeat);
gl.awsm_texture_set_min_filter(TextureTarget::Texture2d, TextureMinFilter::Linear);
gl.awsm_texture_set_mag_filter(TextureTarget::Texture2d, TextureMagFilter::Linear);
}),
&WebGlTextureSource::ArrayBufferView(&data, exr.width as u32, exr.height as u32, 1)
)?;
},
Self::HtmlImage(_) => todo!("html image to texture")
}
Ok(id)
}
}
pub struct ExrImage {
pub data: Vec<f32>,
pub width: usize,
pub height: usize,
pub channel_info: (ChannelDescription, ChannelDescription, ChannelDescription, Option<ChannelDescription>),
}
impl ExrImage {
pub async fn load_url(url: &str) -> Result<Self> {
log::info!("loading exr image from url: {}", url);
let bytes = fetch_url(url).await?.array_buffer().await?.to_vec_u8();
let cursor = Cursor::new(bytes);
log::info!("converting exr from url: {}", url);
// https://github.com/johannesvollmer/exrs/blob/master/GUIDE.md
let result = exr::image::read::read()
.no_deep_data()
.largest_resolution_level()
.rgba_channels(
|resolution, channel_info| {
Self {
data: vec![0.0; (resolution.0 * resolution.1 * 4) as usize],
width: resolution.0 as usize,
height: resolution.1 as usize,
channel_info: channel_info.clone(),
}
},
|img, pos, (r,g,b,a): (f32, f32, f32, exr::prelude::f16)| {
//data: ImageData::new_with_sw(resolution.0 as u32, resolution.1 as u32).unwrap(),
// let width = img.data.width() as usize;
// let data = &mut img.data.data();
let x = pos.0 as usize;
let y = pos.1 as usize;
let offset = (y * img.width + x) * 4;
img.data[offset] = r;
img.data[offset + 1] = g;
img.data[offset + 2] = b;
img.data[offset + 3] = a.to_f32();
}
)
.first_valid_layer()
.all_attributes()
.on_progress(|progress| {
log::info!("progress: {:?}", progress);
})
.non_parallel()
.from_buffered(cursor)?;
Ok(result.layer_data.channel_data.pixels)
}
}
| true |
b20efd53e85d9b19696e7ebfff1d2ee8b061673a
|
Rust
|
polarislee1984/wifi-connect
|
/src/orientation.rs
|
UTF-8
| 1,030 | 3.15625 | 3 |
[
"Apache-2.0"
] |
permissive
|
use std::fs::File;
use std::io::Read;
use std::fs;
pub fn SetOrientation(orientation:String) {
let mut file = File::open("/boot/config.txt").expect("unable to read");
let mut contents = String::new();
file.read_to_string(&mut contents);
if contents.find("display_rotate=") == None {
// add display_rotate
contents = format!("{}\n{}{}", contents, "display_rotate=", orientation);
} else {
// update display_rotate
let lines = contents.lines();
let mut newContents = String::new();
for line in lines {
let mut lineStr = format!("{}", line);
if lineStr.find("display_rotate=") != None {
lineStr = format!("{}{}", "display_rotate=", orientation);
}
newContents.push_str(&lineStr);
newContents.push_str("\n");
}
contents = newContents
}
print!("{}\n", contents);
//replace content
fs::write("/boot/config.txt", contents).expect("Unable to write file");
}
| true |
e33db74d61260d7bbdbd944639aac51937877c04
|
Rust
|
pizzamig/structopt-flags
|
/examples/hostip.rs
|
UTF-8
| 513 | 2.65625 | 3 |
[
"BSD-3-Clause"
] |
permissive
|
use std::net::{IpAddr, Ipv6Addr};
use structopt::StructOpt;
use structopt_flags::GetWithDefault;
#[derive(Debug, StructOpt)]
#[structopt(name = "hostip", about = "An example using HostOpt option")]
struct Opt {
#[structopt(flatten)]
hostip: structopt_flags::HostOpt,
}
fn main() -> Result<(), Box<dyn std::error::Error>> {
let opt = Opt::from_args();
let ip = opt
.hostip
.get_with_default(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1)));
println!("{}", ip);
Ok(())
}
| true |
29186b5aef81b325bff660067c086eff7c8e4a43
|
Rust
|
ernestyalumni/HrdwCCppCUDA
|
/Constructicon/Mixmaster/projects/package_collections_etc/src/oop/gui.rs
|
UTF-8
| 4,926 | 3.6875 | 4 |
[
"MIT"
] |
permissive
|
//-------------------------------------------------------------------------------------------------
/// \url https://doc.rust-lang.org/book/ch17-02-trait-objects.html#defining-a-trait-for-common-behavior
/// \details A trait object points to both an instance of a type implementing our specified trait
/// and a table used to look up trait methods on that type at runtime.
/// Create a trait object by specifying some sort of pointer, such as a & reference or a Box<T>
/// smart pointer, then dyn keyword, and then specifying the relevant trait.
/// Use trait objects in place of a generic or concrete type.
//-------------------------------------------------------------------------------------------------
pub struct MutableStruct
{
pub is_drawn_: bool,
pub test_message_: String,
pub test_value_: i32,
}
pub trait Draw
{
fn draw(&self, input: &mut MutableStruct);
}
pub struct Screen
{
// A trait object is an object that can contain objects of different types at the same time; the
// dyn keyword is used when declaring a trait object.
pub components_: Vec<Box<dyn Draw>>,
}
impl Screen
{
pub fn run(&self, input: &mut MutableStruct)
{
for component in self.components_.iter()
{
component.draw(input);
}
}
}
//-------------------------------------------------------------------------------------------------
/// Generic type parameter can only be substituted with 1 concrete type at a time, whereas trait
/// objects allow multiple concrete types to fill in for trait object at runtime.
/// This restricts us to a GenericScreen instance that has a list of components all of type
/// StructThatDraw1 or StructThatDraw2.
/// If you'll only ever have homogeneous collections, using generic and trait bounds is preferable
/// because definitions will be monomorphized at compile time to use concrete types.
//-------------------------------------------------------------------------------------------------
pub struct GenericScreen<T: Draw>
{
pub components_: Vec<T>,
}
impl<T> GenericScreen<T>
where
T: Draw,
{
pub fn run(&self, input: &mut MutableStruct)
{
for component in self.components_.iter()
{
component.draw(input);
}
}
}
#[cfg(test)]
mod tests
{
// The tests module is a regular module that follows the usual visibility rules in Ch. 7,
// "Paths for Referring to an Item in the Module Tree" of Rust book.
// Because tests module is an inner module, we need to bring the code under test in the outer
// module into scope of inner module.
use super::*;
// cf. https://www.educative.io/answers/what-is-the-dyn-keyword-in-rust
struct StructThatDraw1;
struct StructThatDraw2;
impl Draw for StructThatDraw1
{
fn draw(&self, input: &mut MutableStruct)
{
input.is_drawn_ = true;
input.test_message_ = String::from("draw 1 writes on it");
}
}
impl Draw for StructThatDraw2
{
fn draw(&self, input: &mut MutableStruct)
{
input.is_drawn_ = true;
input.test_value_ = 42;
}
}
#[test]
fn call_draw_on_instances()
{
let mut test_input = MutableStruct {
is_drawn_: false,
test_message_: String::from(""),
test_value_: 0};
// Make this mutable since we need to mutate the Vec<Box<dyn Type>> instance.
let mut screen = Screen { components_: Vec::new()};
let instance_1 = StructThatDraw1 {};
let instance_2 = StructThatDraw2 {};
screen.components_.push(Box::new(instance_1));
screen.components_.push(Box::new(instance_2));
screen.run(&mut test_input);
assert_eq!(test_input.is_drawn_, true);
assert_eq!(test_input.test_message_, "draw 1 writes on it");
assert_eq!(test_input.test_value_, 42);
}
#[test]
fn call_draw_on_generic_type_parameter_struct()
{
let mut test_input = MutableStruct {
is_drawn_: false,
test_message_: String::from(""),
test_value_: 0};
{
let mut screen = GenericScreen::<StructThatDraw1> { components_: Vec::new()};
let instance_1 = StructThatDraw1 {};
let instance_2 = StructThatDraw1 {};
screen.components_.push(instance_1);
screen.components_.push(instance_2);
screen.run(&mut test_input);
assert_eq!(test_input.is_drawn_, true);
assert_eq!(test_input.test_message_, "draw 1 writes on it");
assert_eq!(test_input.test_value_, 0);
}
{
let mut screen = GenericScreen::<StructThatDraw2> { components_: Vec::new()};
let instance_1 = StructThatDraw2 {};
let instance_2 = StructThatDraw2 {};
let instance_3 = StructThatDraw2 {};
screen.components_.push(instance_1);
screen.components_.push(instance_2);
screen.components_.push(instance_3);
screen.run(&mut test_input);
assert_eq!(test_input.is_drawn_, true);
assert_eq!(test_input.test_message_, "draw 1 writes on it");
assert_eq!(test_input.test_value_, 42);
}
}
}
| true |
e48c632fd98c2c323e4d16d5a0bbad2c17950ee3
|
Rust
|
matklad/quadheap
|
/src/quad_heap.rs
|
UTF-8
| 2,460 | 3.453125 | 3 |
[] |
no_license
|
pub struct QuadHeap<T> {
pub(crate) vec: Vec<T>,
}
impl<T: Ord + std::fmt::Debug> QuadHeap<T> {
pub fn with_capacity(cap: usize) -> QuadHeap<T> {
QuadHeap {
vec: Vec::with_capacity(cap),
}
}
pub fn push(&mut self, value: T) {
self.vec.push(value);
self.sift_up(self.vec.len() - 1)
}
pub fn pop_min(&mut self) -> Option<T> {
match self.vec.len() {
0 => None,
1 => self.vec.pop(),
2 => {
if self.vec[0] < self.vec[1] {
self.vec.swap(0, 1)
}
self.vec.pop()
}
_ => {
let mut c_idx = 1 + (self.vec[2] < self.vec[1]) as usize;
if self.vec[0] < self.vec[c_idx] {
c_idx = 0;
}
let res = self.vec.swap_remove(c_idx);
self.sift_down(c_idx);
Some(res)
}
}
}
fn sift_up(&mut self, mut idx: usize) {
while idx > 2 {
let p_idx = (idx - 3) / 4;
if self.vec[p_idx] <= self.vec[idx] {
break;
}
self.vec.swap(p_idx, idx);
idx = p_idx;
}
}
fn sift_down(&mut self, mut idx: usize) {
loop {
let (c1_idx, c2_idx, c3_idx, c4_idx) =
(4 * idx + 3, 4 * idx + 4, 4 * idx + 5, 4 * idx + 6);
if !(c4_idx < self.vec.len()) {
if let Some((c_idx, _)) = self
.vec
.get(c1_idx..)
.unwrap_or_default()
.iter()
.enumerate()
.min_by_key(|(_, it)| *it)
{
if !(self.vec[idx] <= self.vec[c1_idx + c_idx]) {
self.vec.swap(idx, c1_idx + c_idx);
}
}
break;
}
let c12_idx = c1_idx + (self.vec[c2_idx] < self.vec[c1_idx]) as usize;
let c34_idx = c3_idx + (self.vec[c4_idx] < self.vec[c3_idx]) as usize;
let c_idx = if self.vec[c12_idx] < self.vec[c34_idx] {
c12_idx
} else {
c34_idx
};
if self.vec[idx] <= self.vec[c_idx] {
break;
}
self.vec.swap(idx, c_idx);
idx = c_idx;
}
}
}
| true |
15d2615e497a82afaa473d9e128d83d6638b313a
|
Rust
|
doytsujin/yew
|
/examples/function_todomvc/src/components/filter.rs
|
UTF-8
| 768 | 2.640625 | 3 |
[
"Apache-2.0",
"MIT"
] |
permissive
|
use yew::prelude::*;
use crate::state::Filter as FilterEnum;
#[derive(PartialEq, Properties)]
pub struct FilterProps {
pub filter: FilterEnum,
pub selected: bool,
pub onset_filter: Callback<FilterEnum>,
}
#[function_component]
pub fn Filter(props: &FilterProps) -> Html {
let filter = props.filter;
let cls = if props.selected {
"selected"
} else {
"not-selected"
};
let onset_filter = {
let onset_filter = props.onset_filter.clone();
move |_| onset_filter.emit(filter)
};
html! {
<li>
<a class={cls}
href={props.filter.as_href()}
onclick={onset_filter}
>
{ props.filter }
</a>
</li>
}
}
| true |
348f6ae13a4bd1deac512da647059922c570f4fb
|
Rust
|
heymind/note-app-one-hour-a-day
|
/crates/sqlxorm/src/generator/column_def.rs
|
UTF-8
| 2,092 | 2.6875 | 3 |
[] |
no_license
|
use super::FieldDataType;
use anyhow::Result;
use sqlx::{FromRow, PgConnection};
#[derive(Debug, FromRow)]
pub struct ColumnDef {
pub table_name: String,
pub column_name: String,
pub is_nullable: String,
pub udt_name: String,
pub constraint_type: Option<String>,
}
impl ColumnDef {
pub async fn find_by_schema(conn: &mut PgConnection, schema: &str) -> Result<Vec<Self>> {
Ok(sqlx::query_as(
r#"
SELECT
table_name,
column_name,
is_nullable,
udt_name,
constraint_name,
constraint_type
FROM
information_schema.columns
NATURAL LEFT JOIN information_schema.constraint_column_usage
NATURAL LEFT JOIN information_schema.table_constraints WHERE
table_schema = $1
;"#,
)
.bind(schema)
.fetch_all(conn)
.await?)
}
pub fn nullable(&self) -> bool {
self.is_nullable == "YES"
}
pub fn is_primary(&self) -> bool {
if let Some(t) = &self.constraint_type {
t == "PRIMARY KEY"
} else {
false
}
}
pub fn data_type(&self) -> Result<FieldDataType> {
fn parse_dt(dt: &str) -> Result<FieldDataType> {
Ok(match dt {
"int8" => FieldDataType::I64,
"int4" => FieldDataType::I32,
"int2" => FieldDataType::I16,
"text" | "varchar" | "bpchar" => FieldDataType::String,
"bool" => FieldDataType::Bool,
"jsonb" => FieldDataType::JsonValue,
"timestamptz" | "date" => FieldDataType::Instant,
"interval" => FieldDataType::Duration,
other if other.starts_with('_') => {
FieldDataType::Array(Box::new(parse_dt(&other[1..])?))
}
others => unimplemented!("unsupport datatype {}", others),
})
}
Ok(parse_dt(&self.udt_name)?)
}
}
| true |
2d89cfb7d8dd4bc91c871fb7a953331d1cc56f35
|
Rust
|
youngqqcn/RustNotes
|
/examples/ch16/rust_channel_1.rs
|
UTF-8
| 2,341 | 3.734375 | 4 |
[] |
no_license
|
use std::thread;
use std::sync::mpsc::{
channel
};
use std::time::Duration;
fn foo1(){
let (tx, rx) = channel();
thread::spawn(move||{
let msg = String::from("goood");
tx.send(msg).expect("send error");
});
let recv_msg = rx.recv().expect("receive error");
println!("receive msg: {}", recv_msg);
}
fn foo2() {
//异步通道,即发送方不需要等待,可以不停地向通道中发送数据
// 因为存在 "infinite buffer" (无限buffer)
let (tx, rx) = channel();
let handle = std::thread::spawn(move || {
let vals = vec![
String::from("1"),
String::from("2"),
String::from("3"),
];
//不阻塞, 一次性全部发完, 不必等待消费者消费
for v in vals {
println!("send {:?}", v);
tx.send(v).expect("send error");
}
println!("sender thread is finished");
});//发送线程结束, 离开作用域, tx将释放, channel关闭.
for recv in rx {
//接收方阻塞等待消息到达, 此时发送方线程可能已经结束,
//但是, buffer中还有消息, 继续读取, 知道buffer为空了之后,
//接收才会退出
thread::sleep(Duration::from_secs(1));
println!("got: {:?}", recv);
}
//阻塞等待子线程退出
handle.join().expect("thread panicked");
}
// 多个发送方
fn foo3() {
let (tx, rx) = channel();
let tx_copy = tx.clone();
std::thread::spawn(move || {
let vals = vec![
String::from("A:1"),
String::from("A:2"),
String::from("A:3"),
];
for val in vals { //move
tx_copy.send(val).expect("send error");
thread::sleep(Duration::from_secs(1));
}
});
std::thread::spawn(move || {
let vals = vec![
String::from("B:1"),
String::from("B:2"),
String::from("B:3"),
];
for val in vals { //move
tx.send(val).expect("send error");
thread::sleep(Duration::from_secs(1));
}
});
//接收方
for rev in rx {//move
println!("{:?}", rev);
thread::sleep(Duration::from_secs(3));
}
}
fn main() {
// foo1();
// foo2();
foo3();
}
| true |
3423a58f205b16e497f3e1792a4136b9c4d44f89
|
Rust
|
asg0451/nbor
|
/src/planet.rs
|
UTF-8
| 1,350 | 3.125 | 3 |
[] |
no_license
|
use crate::vec2::*;
use std::cmp::PartialEq;
static mut NEXT_ID: i32 = 0;
// TODO should this be copy?
#[derive(Clone, Copy, Debug)]
pub struct Planet {
id: i32,
mass: f64,
loc: Vec2<f64>,
vel: Vec2<f64>,
}
impl Planet {
pub fn id(&self) -> i32 {
self.id
}
pub fn mass(&self) -> f64 {
self.mass
}
pub fn loc(&self) -> Vec2<f64> {
self.loc
}
pub fn accel_by(&mut self, accel: Vec2<f64>) {
self.vel += accel
}
pub fn vel_tick(&mut self, dt: f64) {
self.loc += self.vel * dt;
}
pub fn distance(&self, other: &Planet) -> f64 {
self.loc.distance(&other.loc)
}
// newton
pub fn force_between(&self, other: &Planet, g: f64) -> f64 {
use num::traits::pow;
let dist = other.distance(&self);
g * self.mass * other.mass / pow(dist, 2)
}
pub fn vector_between(&self, other: &Planet) -> Vec2<f64> {
other.loc - self.loc
}
pub fn new(mass: f64, loc: Vec2<f64>, vel: Vec2<f64>) -> Planet {
let id = unsafe { Planet::next_id() };
Planet { mass, loc, vel, id }
}
unsafe fn next_id() -> i32 {
let id = NEXT_ID;
NEXT_ID += 1;
id
}
}
impl PartialEq for Planet {
fn eq(&self, other: &Self) -> bool {
self.id == other.id
}
}
| true |
4d12937225c723482c753f6b8ddceb7374b04647
|
Rust
|
Walker-os/delay-timer
|
/examples/demo.rs
|
UTF-8
| 5,279 | 2.671875 | 3 |
[
"MIT",
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
use anyhow::Result;
use delay_timer::prelude::*;
use smol::Timer;
use std::thread::{current, park, sleep, Thread};
use std::time::Duration;
use surf;
// cargo run --package delay_timer --example demo --features=full
fn main() {
let delay_timer = DelayTimerBuilder::default().enable_status_report().build();
let task_builder = TaskBuilder::default();
delay_timer.add_task(build_task1(task_builder)).unwrap();
delay_timer.add_task(build_task2(task_builder)).unwrap();
delay_timer.add_task(build_task3(task_builder)).unwrap();
delay_timer.add_task(build_task5(task_builder)).unwrap();
delay_timer.add_task(build_task7(task_builder)).unwrap();
// Let's do someting about 2s.
sleep(Duration::new(2, 1_000_000));
let task1_record_id = filter_task_recodeid(&delay_timer, |&x| x.get_task_id() == 1).unwrap();
delay_timer.cancel_task(1, task1_record_id).unwrap();
delay_timer.remove_task(1).unwrap();
delay_timer.add_task(build_wake_task(task_builder)).unwrap();
park();
delay_timer.stop_delay_timer().unwrap();
}
fn build_task1(mut task_builder: TaskBuilder) -> Task {
let body = create_async_fn_body!({
println!("create_async_fn_body!");
Timer::after(Duration::from_secs(3)).await;
println!("create_async_fn_body:i'success");
});
task_builder
.set_task_id(1)
.set_frequency_by_candy(CandyFrequency::Repeated(CandyCron::Secondly))
.set_maximun_parallel_runable_num(2)
.spawn(body)
.unwrap()
}
fn build_task2(mut task_builder: TaskBuilder) -> Task {
let body = create_async_fn_body!({
let mut res = surf::get("https://httpbin.org/get").await.unwrap();
dbg!(res.body_string().await.unwrap());
Timer::after(Duration::from_secs(3)).await;
dbg!("Task2 is done.");
});
task_builder
.set_frequency_by_candy(CandyFrequency::Repeated(AuspiciousTime::PerEightSeconds))
.set_task_id(2)
.set_maximum_running_time(5)
.spawn(body)
.unwrap()
}
fn build_task3(mut task_builder: TaskBuilder) -> Task {
let body = unblock_process_task_fn("php /home/open/project/rust/repo/myself/delay_timer/examples/try_spawn.php >> ./try_spawn.txt".into());
task_builder
.set_frequency_by_candy(CandyFrequency::Repeated(CandyCron::Minutely))
.set_task_id(3)
.set_maximum_running_time(5)
.spawn(body)
.unwrap()
}
fn build_task5(mut task_builder: TaskBuilder) -> Task {
let body = generate_closure_template("delay_timer is easy to use. .".into());
task_builder
.set_frequency_by_candy(CandyFrequency::Repeated(AuspiciousTime::LoveTime))
.set_task_id(5)
.set_maximum_running_time(5)
.spawn(body)
.unwrap()
}
fn build_task7(mut task_builder: TaskBuilder) -> Task {
let body = create_async_fn_body!({
dbg!(get_timestamp());
Timer::after(Duration::from_secs(3)).await;
});
task_builder
.set_task_id(7)
.set_frequency_by_candy(CandyFrequency::Repeated(AuspiciousTime::PerDayFiveAclock))
.set_maximun_parallel_runable_num(2)
.spawn(body)
.unwrap()
}
pub fn generate_closure_template(
name: String,
) -> impl Fn(TaskContext) -> Box<dyn DelayTaskHandler> + 'static + Send + Sync {
move |context| {
let future_inner = async_template(get_timestamp() as i32, name.clone());
let future = async move {
future_inner.await.unwrap();
context.finishe_task().await;
};
create_delay_task_handler(async_spawn(future))
}
}
pub async fn async_template(id: i32, name: String) -> Result<()> {
let url = format!("https://httpbin.org/get?id={}&name={}", id, name);
let mut res = surf::get(url).await.unwrap();
dbg!(res.body_string().await.unwrap());
Ok(())
}
fn build_wake_task(mut task_builder: TaskBuilder) -> Task {
let thread: Thread = current();
let body = move |_| {
println!("bye bye");
thread.unpark();
create_default_delay_task_handler()
};
task_builder
.set_frequency_by_candy(CandyFrequency::Repeated(CandyCron::Minutely))
.set_task_id(700)
.set_maximum_running_time(50)
.spawn(body)
.unwrap()
}
fn filter_task_recodeid<P>(delay_timer: &DelayTimer, predicate: P) -> Option<i64>
where
P: FnMut(&PublicEvent) -> bool,
{
let mut public_events = Vec::<PublicEvent>::new();
while let Ok(public_event) = delay_timer.get_public_event() {
public_events.push(public_event);
}
let public_event = public_events.into_iter().find(predicate)?;
public_event.get_record_id()
}
enum AuspiciousTime {
PerSevenSeconds,
PerEightSeconds,
LoveTime,
PerDayFiveAclock,
}
impl Into<CandyCronStr> for AuspiciousTime {
fn into(self) -> CandyCronStr {
match self {
Self::PerSevenSeconds => CandyCronStr("0/7 * * * * * *".to_string()),
Self::PerEightSeconds => CandyCronStr("0/8 * * * * * *".to_string()),
Self::LoveTime => CandyCronStr("0,10,15,25,50 0/1 * * Jan-Dec * 2020-2100".to_string()),
Self::PerDayFiveAclock => CandyCronStr("01 00 1 * * * *".to_string()),
}
}
}
| true |
7fdf43daa42db9df27e11313fc1332631c30ed9a
|
Rust
|
paulkirkwood/rs.parcoursdb
|
/tests/test_tour_de_france.rs
|
UTF-8
| 192,206 | 2.78125 | 3 |
[] |
no_license
|
extern crate parcoursdb;
extern crate chrono;
#[cfg(test)]
mod test {
use parcoursdb::tour_de_france::repository::*;
#[test]
fn test_tour_de_france_1903() {
let route = [
"1,1 July,Paris to Lyon,467.0 km,Road stage",
"2,5 July,Lyon to Marseille,374.0 km,Road stage",
"3,8 July,Marseille to Toulouse,423.0 km,Road stage",
"4,12 July,Toulouse to Bordeaux,268.0 km,Road stage",
"5,13 July,Bordeaux to Nantes,425.0 km,Road stage",
"6,18 July,Nantes to Paris,471.0 km,Road stage"
];
let edition = tour_de_france_1903();
assert_eq!(edition.route(), route);
assert_eq!(edition.stage_summary(), "6 stages");
}
#[test]
fn test_tour_de_france_1904() {
let route = [
"1,2 July,Montgeron to Lyon,467.0 km,Road stage",
"2,9 July,Lyon to Marseille,374.0 km,Road stage",
"3,13 July,Marseille to Toulouse,424.0 km,Road stage",
"4,17 July,Toulouse to Bordeaux,268.0 km,Road stage",
"5,20 July,Bordeaux to Nantes,425.0 km,Road stage",
"6,23 July,Nantes to Paris,471.0 km,Road stage"
];
let edition = tour_de_france_1904();
assert_eq!(edition.route(), route);
assert_eq!(edition.stage_summary(), "6 stages");
}
#[test]
fn test_tour_de_france_1905() {
let route = [
"1,9 July,Paris to Nancy,340.0 km,Road stage",
"2,11 July,Nancy to Besançon,299.0 km,Road stage",
"3,14 July,Besançon to Grenoble,327.0 km,Road stage",
"4,16 July,Grenoble to Toulon,348.0 km,Road stage",
"5,18 July,Toulon to Nîmes,192.0 km,Road stage",
"6,20 July,Nîmes to Toulouse,307.0 km,Road stage",
"7,22 July,Toulouse to Bordeaux,268.0 km,Road stage",
"8,24 July,Bordeaux to La Rochelle,257.0 km,Road stage",
"9,26 July,La Rochelle to Rennes,263.0 km,Road stage",
"10,28 July,Rennes to Caen,167.0 km,Road stage",
"11,29 July,Caen to Paris,253.0 km,Road stage"
];
let edition = tour_de_france_1905();
assert_eq!(edition.route(), route);
assert_eq!(edition.stage_summary(), "11 stages");
}
#[test]
fn test_tour_de_france_1906() {
let route = [
"1,4 July,Paris to Lille,275.0 km,Road stage",
"2,6 July,Douai to Nancy,400.0 km,Road stage",
"3,8 July,Nancy to Dijon,416.0 km,Road stage",
"4,10 July,Dijon to Grenoble,311.0 km,Road stage",
"5,12 July,Grenoble to Nice,345.0 km,Road stage",
"6,14 July,Nice to Marseille,292.0 km,Road stage",
"7,16 July,Marseille to Toulouse,480.0 km,Road stage",
"8,18 July,Toulouse to Bayonne,300.0 km,Road stage",
"9,20 July,Bayonne to Bordeaux,338.0 km,Road stage",
"10,22 July,Bordeaux to Nantes,391.0 km,Road stage",
"11,24 July,Nantes to Brest,321.0 km,Road stage",
"12,26 July,Brest to Caen,415.0 km,Road stage",
"13,29 July,Caen to Paris,259.0 km,Road stage"
];
let edition = tour_de_france_1906();
assert_eq!(edition.route(), route);
assert_eq!(edition.stage_summary(), "13 stages");
}
#[test]
fn test_tour_de_france_1907() {
let route = [
"1,8 July,Paris to Roubaix,272.0 km,Road stage",
"2,10 July,Roubaix to Metz,398.0 km,Road stage",
"3,12 July,Metz to Belfort,259.0 km,Road stage",
"4,14 July,Belfort to Lyon,309.0 km,Road stage",
"5,16 July,Lyon to Grenoble,311.0 km,Road stage",
"6,18 July,Grenoble to Nice,345.0 km,Road stage",
"7,20 July,Nice to Nîmes,345.0 km,Road stage",
"8,22 July,Nîmes to Toulouse,303.0 km,Road stage",
"9,24 July,Toulouse to Bayonne,299.0 km,Road stage",
"10,26 July,Bayonne to Bordeaux,269.0 km,Road stage",
"11,28 July,Bordeaux to Nantes,391.0 km,Road stage",
"12,30 July,Nantes to Brest,321.0 km,Road stage",
"13,1 August,Brest to Caen,415.0 km,Road stage",
"14,4 August,Caen to Paris,251.0 km,Road stage"
];
let edition = tour_de_france_1907();
assert_eq!(edition.route(), route);
assert_eq!(edition.stage_summary(), "14 stages");
}
#[test]
fn test_tour_de_france_1908() {
let route = [
"1,13 July,Paris to Roubaix,272.0 km,Road stage",
"2,15 July,Roubaix to Metz,398.0 km,Road stage",
"3,17 July,Metz to Belfort,259.0 km,Road stage",
"4,19 July,Belfort to Lyon,309.0 km,Road stage",
"5,21 July,Lyon to Grenoble,311.0 km,Road stage",
"6,23 July,Grenoble to Nice,345.0 km,Road stage",
"7,25 July,Nice to Nîmes,354.0 km,Road stage",
"8,27 July,Nîmes to Toulouse,303.0 km,Road stage",
"9,29 July,Toulouse to Bayonne,299.0 km,Road stage",
"10,31 July,Bayonne to Bordeaux,269.0 km,Road stage",
"11,2 August,Bordeaux to Nantes,391.0 km,Road stage",
"12,4 August,Nantes to Brest,321.0 km,Road stage",
"13,6 August,Brest to Caen,415.0 km,Road stage",
"14,9 August,Caen to Paris,251.0 km,Road stage"
];
let edition = tour_de_france_1908();
assert_eq!(edition.route(), route);
assert_eq!(edition.stage_summary(), "14 stages");
}
#[test]
fn test_tour_de_france_1909() {
let route = [
"1,5 July,Paris to Roubaix,272.0 km,Road stage",
"2,7 July,Roubaix to Metz,398.0 km,Road stage",
"3,9 July,Metz to Belfort,259.0 km,Road stage",
"4,11 July,Belfort to Lyon,309.0 km,Road stage",
"5,13 July,Lyon to Grenoble,311.0 km,Road stage",
"6,15 July,Grenoble to Nice,346.0 km,Road stage",
"7,17 July,Nice to Nîmes,345.0 km,Road stage",
"8,19 July,Nîmes to Toulouse,303.0 km,Road stage",
"9,21 July,Toulouse to Bayonne,299.0 km,Road stage",
"10,23 July,Bayonne to Bordeaux,269.0 km,Road stage",
"11,25 July,Bordeaux to Nantes,391.0 km,Road stage",
"12,27 July,Nantes to Brest,321.0 km,Road stage",
"13,29 July,Brest to Caen,424.0 km,Road stage",
"14,1 August,Caen to Paris,250.0 km,Road stage"
];
let edition = tour_de_france_1909();
assert_eq!(edition.route(), route);
assert_eq!(edition.stage_summary(), "14 stages");
}
#[test]
fn test_tour_de_france_1910() {
let route = [
"1,3 July,Paris to Roubaix,269.0 km,Road stage",
"2,5 July,Roubaix to Metz,398.0 km,Road stage",
"3,7 July,Metz to Belfort,259.0 km,Road stage",
"4,9 July,Belfort to Lyon,309.0 km,Road stage",
"5,11 July,Lyon to Grenoble,311.0 km,Road stage",
"6,13 July,Grenoble to Nice,345.0 km,Road stage",
"7,17 July,Nice to Nîmes,345.0 km,Road stage",
"8,19 July,Nîmes to Perpignan,216.0 km,Road stage",
"9,21 July,Perpignan to Luchon,289.0 km,Road stage",
"10,23 July,Bayonne to Bordeaux,269.0 km,Road stage",
"11,25 July,Bordeaux to Nantes,391.0 km,Road stage",
"12,27 July,Nantes to Brest,321.0 km,Road stage",
"13,29 July,Brest to Caen,424.0 km,Road stage",
"14,31 July,Caen to Paris,262.0 km,Road stage"
];
let edition = tour_de_france_1910();
assert_eq!(edition.route(), route);
assert_eq!(edition.stage_summary(), "14 stages");
}
#[test]
fn test_tour_de_france_1911() {
let route = [
"1,2 July,Paris to Dunkerque,351.0 km,Road stage",
"2,4 July,Dunkerque to Longwy,388.0 km,Road stage",
"3,6 July,Longwy to Belfort,331.0 km,Road stage",
"4,8 July,Belfort to Chamonix,344.0 km,Road stage",
"5,10 July,Chamonix to Grenoble,366.0 km,Road stage",
"6,12 July,Grenoble to Nice,348.0 km,Road stage",
"7,14 July,Nice to Marseille,334.0 km,Road stage",
"8,16 July,Marseille to Perpignan,335.0 km,Road stage",
"9,18 July,Perpignan to Luchon,289.0 km,Road stage",
"10,20 July,Luchon to Bayonne,326.0 km,Road stage",
"11,22 July,Bayonne to La Rochelle,379.0 km,Road stage",
"12,23 July,La Rochelle to Brest,470.0 km,Road stage",
"13,26 July,Brest to Cherbourg,405.0 km,Road stage",
"14,28 July,Cherbourg to Le Havre,361.0 km,Road stage",
"15,30 July,Le Havre to Paris,317.0 km,Road stage"
];
let edition = tour_de_france_1911();
assert_eq!(edition.route(), route);
assert_eq!(edition.stage_summary(), "15 stages");
}
#[test]
fn test_tour_de_france_1912() {
let route = [
"1,30 June,Paris to Dunkerque,351.0 km,Road stage",
"2,2 July,Dunkerque to Longwy,388.0 km,Road stage",
"3,4 July,Longwy to Belfort,331.0 km,Road stage",
"4,6 July,Belfort to Chamonix,344.0 km,Road stage",
"5,8 July,Chamonix to Grenoble,366.0 km,Road stage",
"6,10 July,Grenoble to Nice,323.0 km,Road stage",
"7,12 July,Nice to Marseille,334.0 km,Road stage",
"8,14 July,Marseille to Perpignan,335.0 km,Road stage",
"9,16 July,Perpignan to Luchon,289.0 km,Road stage",
"10,18 July,Luchon to Bayonne,326.0 km,Road stage",
"11,20 July,Bayonne to La Rochelle,379.0 km,Road stage",
"12,21 July,La Rochelle to Brest,470.0 km,Road stage",
"13,24 July,Brest to Cherbourg,405.0 km,Road stage",
"14,26 July,Cherbourg to Le Havre,361.0 km,Road stage",
"15,28 July,Le Havre to Paris,317.0 km,Road stage"
];
let edition = tour_de_france_1912();
assert_eq!(edition.route(), route);
assert_eq!(edition.stage_summary(), "15 stages");
}
#[test]
fn test_tour_de_france_1913() {
let route = [
"1,29 June,Paris to Le Havre,388.0 km,Road stage",
"2,1 July,Le Havre to Cherbourg,364.0 km,Road stage",
"3,3 July,Cherbourg to Brest,405.0 km,Road stage",
"4,5 July,Brest to La Rochelle,470.0 km,Road stage",
"5,7 July,La Rochelle to Bayonne,379.0 km,Road stage",
"6,9 July,Bayonne to Luchon,326.0 km,Road stage",
"7,11 July,Luchon to Perpignan,324.0 km,Road stage",
"8,13 July,Perpignan to Aix-en-Provence,325.0 km,Road stage",
"9,15 July,Aix-en-Provence to Nice,356.0 km,Road stage",
"10,17 July,Nice to Grenoble,333.0 km,Road stage",
"11,19 July,Grenoble to Geneva (Switzerland),325.0 km,Road stage",
"12,21 July,Geneva (Switzerland) to Belfort,335.0 km,Road stage",
"13,23 July,Belfort to Longwy,325.0 km,Road stage",
"14,25 July,Longwy to Dunkerque,393.0 km,Road stage",
"15,27 July,Dunkerque to Paris,340.0 km,Road stage"
];
let edition = tour_de_france_1913();
assert_eq!(edition.route(), route);
assert_eq!(edition.stage_summary(), "15 stages");
}
#[test]
fn test_tour_de_france_1914() {
let route = [
"1,28 June,Paris to Le Havre,388.0 km,Road stage",
"2,30 June,Le Havre to Cherbourg,364.0 km,Road stage",
"3,2 July,Cherbourg to Brest,405.0 km,Road stage",
"4,4 July,Brest to La Rochelle,470.0 km,Road stage",
"5,6 July,La Rochelle to Bayonne,376.0 km,Road stage",
"6,8 July,Bayonne to Luchon,326.0 km,Road stage",
"7,10 July,Luchon to Perpignan,323.0 km,Road stage",
"8,12 July,Perpignan to Marseille,370.0 km,Road stage",
"9,14 July,Marseille to Nice,338.0 km,Road stage",
"10,16 July,Nice to Grenoble,323.0 km,Road stage",
"11,18 July,Grenoble to Geneva (Switzerland),325.0 km,Road stage",
"12,20 July,Geneva (Switzerland) to Belfort,325.0 km,Road stage",
"13,22 July,Belfort to Longwy,325.0 km,Road stage",
"14,24 July,Longwy to Dunkerque,390.0 km,Road stage",
"15,26 July,Dunkerque to Paris,340.0 km,Road stage"
];
let edition = tour_de_france_1914();
assert_eq!(edition.route(), route);
assert_eq!(edition.stage_summary(), "15 stages");
}
#[test]
fn test_tour_de_france_1919() {
let route = [
"1,29 June,Paris to Le Havre,388.0 km,Road stage",
"2,1 July,Le Havre to Cherbourg,364.0 km,Road stage",
"3,3 July,Cherbourg to Brest,405.0 km,Road stage",
"4,5 July,Brest to Les Sables-d'Olonne,412.0 km,Road stage",
"5,7 July,Les Sables-d'Olonne to Bayonne,482.0 km,Road stage",
"6,9 July,Bayonne to Luchon,326.0 km,Road stage",
"7,11 July,Luchon to Perpignan,323.0 km,Road stage",
"8,13 July,Perpignan to Marseille,370.0 km,Road stage",
"9,15 July,Marseille to Nice,338.0 km,Road stage",
"10,17 July,Nice to Grenoble,333.0 km,Road stage",
"11,19 July,Grenoble to Geneva (Switzerland),325.0 km,Road stage",
"12,21 July,Geneva (Switzerland) to Strasbourg,371.0 km,Road stage",
"13,23 July,Strasbourg to Metz,315.0 km,Road stage",
"14,25 July,Metz to Dunkerque,468.0 km,Road stage",
"15,27 July,Dunkerque to Paris,340.0 km,Road stage"
];
let edition = tour_de_france_1919();
assert_eq!(edition.route(), route);
assert_eq!(edition.stage_summary(), "15 stages");
}
#[test]
fn test_tour_de_france_1920() {
let route = [
"1,27 June,Paris to Le Havre,388.0 km,Road stage",
"2,29 June,Le Havre to Cherbourg,364.0 km,Road stage",
"3,1 July,Cherbourg to Brest,405.0 km,Road stage",
"4,3 July,Brest to Les Sables-d'Olonne,412.0 km,Road stage",
"5,5 July,Les Sables-d'Olonne to Bayonne,482.0 km,Road stage",
"6,7 July,Bayonne to Luchon,326.0 km,Road stage",
"7,9 July,Luchon to Perpignan,323.0 km,Road stage",
"8,11 July,Perpignan to Aix-en-Provence,325.0 km,Road stage",
"9,14 July,Aix-en-Provence to Nice,356.0 km,Road stage",
"10,16 July,Nice to Grenoble,333.0 km,Road stage",
"11,18 July,Grenoble to Gex,362.0 km,Road stage",
"12,20 July,Gex to Strasbourg,354.0 km,Road stage",
"13,22 July,Strasbourg to Metz,300.0 km,Road stage",
"14,24 July,Metz to Dunkerque,433.0 km,Road stage",
"15,27 July,Dunkerque to Paris,340.0 km,Road stage"
];
let edition = tour_de_france_1920();
assert_eq!(edition.route(), route);
assert_eq!(edition.stage_summary(), "15 stages");
}
#[test]
fn test_tour_de_france_1921() {
let route = [
"1,26 June,Paris to Le Havre,388.0 km,Road stage",
"2,28 June,Le Havre to Cherbourg,364.0 km,Road stage",
"3,30 June,Cherbourg to Brest,405.0 km,Road stage",
"4,2 July,Brest to Les Sables-d'Olonne,412.0 km,Road stage",
"5,4 July,Les Sables-d'Olonne to Bayonne,482.0 km,Road stage",
"6,6 July,Bayonne to Luchon,326.0 km,Road stage",
"7,8 July,Luchon to Perpignan,323.0 km,Road stage",
"8,10 July,Perpignan to Toulon,411.0 km,Road stage",
"9,12 July,Toulon to Nice,272.0 km,Road stage",
"10,14 July,Nice to Grenoble,333.0 km,Road stage",
"11,16 July,Grenoble to Geneva (Switzerland),325.0 km,Road stage",
"12,18 July,Geneva (Switzerland) to Strasbourg,371.0 km,Road stage",
"13,20 July,Strasbourg to Metz,300.0 km,Road stage",
"14,22 July,Metz to Dunkerque,433.0 km,Road stage",
"15,24 July,Dunkerque to Paris,340.0 km,Road stage",
];
let edition = tour_de_france_1921();
assert_eq!(edition.route(), route);
assert_eq!(edition.stage_summary(), "15 stages");
}
#[test]
fn test_tour_de_france_1922() {
let route = [
"1,25 June,Paris to Le Havre,388.0 km,Road stage",
"2,27 June,Le Havre to Cherbourg,364.0 km,Road stage",
"3,29 June,Cherbourg to Brest,405.0 km,Road stage",
"4,1 July,Brest to Les Sables-d'Olonne,412.0 km,Road stage",
"5,3 July,Les Sables-d'Olonne to Bayonne,482.0 km,Road stage",
"6,5 July,Bayonne to Luchon,326.0 km,Road stage",
"7,7 July,Luchon to Perpignan,323.0 km,Road stage",
"8,9 July,Perpignan to Toulon,411.0 km,Road stage",
"9,11 July,Toulon to Nice,284.0 km,Road stage",
"10,13 July,Nice to Briançon,274.0 km,Road stage",
"11,15 July,Briançon to Geneva (Switzerland),260.0 km,Road stage",
"12,17 July,Geneva (Switzerland) to Strasbourg,371.0 km,Road stage",
"13,19 July,Strasbourg to Metz,300.0 km,Road stage",
"14,21 July,Metz to Dunkerque,433.0 km,Road stage",
"15,23 July,Dunkerque to Paris,340.0 km,Road stage"
];
let edition = tour_de_france_1922();
assert_eq!(edition.route(), route);
assert_eq!(edition.stage_summary(), "15 stages");
}
#[test]
fn test_tour_de_france_1923() {
let route = [
"1,24 June,Paris to Le Havre,381.0 km,Road stage",
"2,26 June,Le Havre to Cherbourg,371.0 km,Road stage",
"3,28 June,Cherbourg to Brest,405.0 km,Road stage",
"4,30 June,Brest to Les Sables-d'Olonne,412.0 km,Road stage",
"5,2 July,Les Sables-d'Olonne to Bayonne,482.0 km,Road stage",
"6,4 July,Bayonne to Luchon,326.0 km,Road stage",
"7,6 July,Luchon to Perpignan,323.0 km,Road stage",
"8,8 July,Perpignan to Toulon,427.0 km,Road stage",
"9,10 July,Toulon to Nice,281.0 km,Road stage",
"10,12 July,Nice to Briançon,275.0 km,Road stage",
"11,14 July,Briançon to Geneva (Switzerland),260.0 km,Road stage",
"12,16 July,Geneva (Switzerland) to Strasbourg,377.0 km,Road stage",
"13,18 July,Strasbourg to Metz,300.0 km,Road stage",
"14,20 July,Metz to Dunkerque,433.0 km,Road stage",
"15,22 July,Dunkerque to Paris,343.0 km,Road stage"
];
let edition = tour_de_france_1923();
assert_eq!(edition.route(), route);
assert_eq!(edition.stage_summary(), "15 stages");
}
#[test]
fn test_tour_de_france_1924() {
let route = [
"1,22 June,Paris to Le Havre,381.0 km,Road stage",
"2,24 June,Le Havre to Cherbourg,371.0 km,Road stage",
"3,26 June,Cherbourg to Brest,405.0 km,Road stage",
"4,28 June,Brest to Les Sables-d'Olonne,412.0 km,Road stage",
"5,30 June,Les Sables-d'Olonne to Bayonne,482.0 km,Road stage",
"6,2 July,Bayonne to Luchon,326.0 km,Road stage",
"7,4 July,Luchon to Perpignan,323.0 km,Road stage",
"8,6 July,Perpignan to Toulon,427.0 km,Road stage",
"9,8 July,Toulon to Nice,280.0 km,Road stage",
"10,10 July,Nice to Briançon,275.0 km,Road stage",
"11,12 July,Briançon to Gex,307.0 km,Road stage",
"12,14 July,Gex to Strasbourg,360.0 km,Road stage",
"13,16 July,Strasbourg to Metz,300.0 km,Road stage",
"14,18 July,Metz to Dunkerque,433.0 km,Road stage",
"15,20 July,Dunkerque to Paris,343.0 km,Road stage"
];
let edition = tour_de_france_1924();
assert_eq!(edition.route(), route);
assert_eq!(edition.stage_summary(), "15 stages");
}
#[test]
fn test_tour_de_france_1925() {
let route = [
"1,21 June,Paris to Le Havre,340.0 km,Road stage",
"2,23 June,Le Havre to Cherbourg,371.0 km,Road stage",
"3,25 June,Cherbourg to Brest,405.0 km,Road stage",
"4,26 June,Brest to Vannes,208.0 km,Road stage",
"5,27 June,Vannes to Les Sables-d'Olonne,204.0 km,Road stage",
"6,28 June,Les Sables-d'Olonne to Bordeaux,293.0 km,Road stage",
"7,29 June,Bordeaux to Bayonne,189.0 km,Road stage",
"8,1 July,Bayonne to Luchon,326.0 km,Road stage",
"9,3 July,Luchon to Perpignan,323.0 km,Road stage",
"10,4 July,Perpignan to Nîmes,215.0 km,Road stage",
"11,5 July,Nîmes to Toulon,215.0 km,Road stage",
"12,7 July,Toulon to Nice,280.0 km,Road stage",
"13,9 July,Nice to Briançon,275.0 km,Road stage",
"14,11 July,Briançon to Evian,303.0 km,Road stage",
"15,13 July,Evian to Mulhouse,373.0 km,Road stage",
"16,15 July,Mulhouse to Metz,334.0 km,Road stage",
"17,17 July,Metz to Dunkerque,433.0 km,Road stage",
"18,19 July,Dunkerque to Paris,343.0 km,Road stage"
];
let edition = tour_de_france_1925();
assert_eq!(edition.route(), route);
assert_eq!(edition.stage_summary(), "18 stages");
}
#[test]
fn test_tour_de_france_1926() {
let route = [
"1,20 June,Evian to Mulhouse,373.0 km,Road stage",
"2,22 June,Mulhouse to Metz,334.0 km,Road stage",
"3,24 June,Metz to Dunkerque,433.0 km,Road stage",
"4,26 June,Dunkerque to Le Havre,361.0 km,Road stage",
"5,28 June,Le Havre to Cherbourg,357.0 km,Road stage",
"6,30 June,Cherbourg to Brest,405.0 km,Road stage",
"7,2 July,Brest to Les Sables-d'Olonne,412.0 km,Road stage",
"8,3 July,Les Sables-d'Olonne to Bordeaux,285.0 km,Road stage",
"9,4 July,Bordeaux to Bayonne,189.0 km,Road stage",
"10,6 July,Bayonne to Luchon,326.0 km,Road stage",
"11,8 July,Luchon to Perpignan,323.0 km,Road stage",
"12,10 July,Perpignan to Toulon,427.0 km,Road stage",
"13,12 July,Toulon to Nice,280.0 km,Road stage",
"14,14 July,Nice to Briançon,275.0 km,Road stage",
"15,16 July,Briançon to Evian,303.0 km,Road stage",
"16,17 July,Evian to Dijon,321.0 km,Road stage",
"17,18 July,Dijon to Paris,341.0 km,Road stage"
];
let edition = tour_de_france_1926();
assert_eq!(edition.route(), route);
assert_eq!(edition.stage_summary(), "17 stages");
}
#[test]
fn test_tour_de_france_1927() {
let route = [
"1,19 June,Paris to Dieppe,180.0 km,Team time trial",
"2,20 June,Dieppe to Le Havre,103.0 km,Team time trial",
"3,21 June,Le Havre to Caen,225.0 km,Team time trial",
"4,22 June,Caen to Cherbourg,140.0 km,Team time trial",
"5,23 June,Cherbourg to Dinan,199.0 km,Team time trial",
"6,24 June,Dinan to Brest,206.0 km,Team time trial",
"7,25 June,Brest to Vannes,207.0 km,Team time trial",
"8,26 June,Vannes to Les Sables-d'Olonne,204.0 km,Team time trial",
"9,27 June,Les Sables-d'Olonne to Bordeaux,285.0 km,Team time trial",
"10,28 June,Bordeaux to Bayonne,189.0 km,Road stage",
"11,30 June,Bayonne to Luchon,326.0 km,Road stage",
"12,2 July,Luchon to Perpignan,323.0 km,Road stage",
"13,4 July,Perpignan to Marseille,360.0 km,Road stage",
"14,5 July,Marseille to Toulon,120.0 km,Team time trial",
"15,6 July,Toulon to Nice,220.0 km,Road stage",
"16,8 July,Nice to Briançon,275.0 km,Road stage",
"17,9 July,Briançon to Evian,283.0 km,Road stage",
"18,11 July,Evian to Pontarlier,213.0 km,Team time trial",
"19,12 July,Pontarlier to Belfort,119.0 km,Team time trial",
"20,13 July,Belfort to Strasbourg,145.0 km,Team time trial",
"21,14 July,Strasbourg to Metz,165.0 km,Team time trial",
"22,15 July,Metz to Charleville,159.0 km,Team time trial",
"23,16 July,Charleville to Dunkerque,270.0 km,Team time trial",
"24,17 July,Dunkerque to Paris,344.0 km,Road stage"
];
let edition = tour_de_france_1927();
assert_eq!(edition.route(), route);
assert_eq!(edition.stage_summary(), "24 stages");
}
#[test]
fn test_tour_de_france_1928() {
let route = [
"1,17 June,Paris to Caen,207.0 km,Team time trial",
"2,18 June,Caen to Cherbourg,140.0 km,Team time trial",
"3,19 June,Cherbourg to Dinan,199.0 km,Team time trial",
"4,20 June,Dinan to Brest,206.0 km,Team time trial",
"5,21 June,Brest to Vannes,208.0 km,Team time trial",
"6,22 June,Vannes to Les Sables-d'Olonne,204.0 km,Team time trial",
"7,23 June,Les Sables-d'Olonne to Bordeaux,285.0 km,Team time trial",
"8,24 June,Bordeaux to Hendaye,225.0 km,Team time trial",
"9,26 June,Hendaye to Luchon,387.0 km,Road stage",
"10,28 June,Luchon to Perpignan,323.0 km,Road stage",
"11,30 June,Perpignan to Marseille,363.0 km,Road stage",
"12,2 July,Marseille to Nice,330.0 km,Road stage",
"13,4 July,Nice to Grenoble,333.0 km,Road stage",
"14,6 July,Grenoble to Evian,329.0 km,Road stage",
"15,8 July,Evian to Pontarlier,213.0 km,Team time trial",
"16,9 July,Pontarlier to Belfort,119.0 km,Team time trial",
"17,10 July,Belfort to Strasbourg,145.0 km,Team time trial",
"18,11 July,Strasbourg to Metz,165.0 km,Team time trial",
"19,12 July,Metz to Charleville,159.0 km,Team time trial",
"20,13 July,Charleville to Malo-les-Bains,271.0 km,Team time trial",
"21,14 July,Malo-les-Bains to Dunkerque,234.0 km,Team time trial",
"22,15 July,Dieppe to Paris,331.0 km,Road stage"
];
let edition = tour_de_france_1928();
assert_eq!(edition.route(), route);
assert_eq!(edition.stage_summary(), "22 stages");
}
#[test]
fn test_tour_de_france_1929() {
let route = [
"1,30 June,Paris to Caen,206.0 km,Road stage",
"2,1 July,Caen to Cherbourg,140.0 km,Road stage",
"3,2 July,Cherbourg to Dinan,199.0 km,Road stage",
"4,3 July,Dinan to Brest,206.0 km,Road stage",
"5,4 July,Brest to Vannes,208.0 km,Road stage",
"6,5 July,Vannes to Les Sables-d'Olonne,206.0 km,Road stage",
"7,6 July,Les Sables-d'Olonne to Bordeaux,285.0 km,Road stage",
"8,7 July,Bordeaux to Bayonne,182.0 km,Road stage",
"9,9 July,Bayonne to Luchon,363.0 km,Road stage",
"10,11 July,Luchon to Perpignan,323.0 km,Road stage",
"11,13 July,Perpignan to Marseille,366.0 km,Road stage",
"12,15 July,Marseille to Cannes,191.0 km,Team time trial",
"13,16 July,Cannes to Nice,133.0 km,Road stage",
"14,18 July,Nice to Grenoble,333.0 km,Road stage",
"15,20 July,Grenoble to Evian,329.0 km,Road stage",
"16,22 July,Evian to Belfort,283.0 km,Road stage",
"17,23 July,Belfort to Strasbourg,145.0 km,Road stage",
"18,24 July,Strasbourg to Metz,165.0 km,Road stage",
"19,25 July,Metz to Charleville,159.0 km,Team time trial",
"20,26 July,Charleville to Malo-les-Bains,270.0 km,Team time trial",
"21,27 July,Malo-les-Bains to Dunkerque,234.0 km,Road stage",
"22,28 July,Dieppe to Paris,332.0 km,Road stage"
];
let edition = tour_de_france_1929();
assert_eq!(edition.route(), route);
assert_eq!(edition.stage_summary(), "22 stages");
}
#[test]
fn test_tour_de_france_1930() {
let route = [
"1,2 July,Paris to Caen,206.0 km,Road stage",
"2,3 July,Caen to Dinan,203.0 km,Road stage",
"3,4 July,Dinan to Brest,206.0 km,Road stage",
"4,5 July,Brest to Vannes,210.0 km,Road stage",
"5,6 July,Vannes to Les Sables-d'Olonne,202.0 km,Road stage",
"6,7 July,Les Sables-d'Olonne to Bordeaux,285.0 km,Road stage",
"7,8 July,Bordeaux to Hendaye,222.0 km,Road stage",
"8,9 July,Hendaye to Pau,146.0 km,Road stage",
"9,10 July,Pau to Luchon,231.0 km,Road stage",
"10,12 July,Luchon to Perpignan,322.0 km,Road stage",
"11,14 July,Perpignan to Montpellier,164.0 km,Road stage",
"12,15 July,Montpellier to Marseille,209.0 km,Road stage",
"13,16 July,Marseille to Cannes,181.0 km,Road stage",
"14,17 July,Cannes to Nice,132.0 km,Road stage",
"15,19 July,Nice to Grenoble,333.0 km,Road stage",
"16,21 July,Grenoble to Evian,331.0 km,Road stage",
"17,23 July,Evian to Belfort,282.0 km,Road stage",
"18,24 July,Belfort to Metz,223.0 km,Road stage",
"19,25 July,Metz to Charleville,159.0 km,Road stage",
"20,26 July,Charleville to Malo-les-Bains,271.0 km,Road stage",
"21,28 July,Malo-les-Bains to Paris,300.0 km,Road stage"
];
let edition = tour_de_france_1930();
assert_eq!(edition.route(), route);
assert_eq!(edition.stage_summary(), "21 stages");
}
#[test]
fn test_tour_de_france_1931() {
let route = [
"1,30 June,Paris to Caen,208.0 km,Road stage",
"2,1 July,Caen to Dinan,212.0 km,Road stage",
"3,2 July,Dinan to Brest,206.0 km,Road stage",
"4,3 July,Brest to Vannes,211.0 km,Road stage",
"5,4 July,Vannes to Les Sables-d'Olonne,202.0 km,Road stage",
"6,5 July,Les Sables-d'Olonne to Bordeaux,338.0 km,Road stage",
"7,6 July,Bordeaux to Bayonne,180.0 km,Road stage",
"8,7 July,Bayonne to Pau,106.0 km,Road stage",
"9,8 July,Pau to Luchon,231.0 km,Road stage",
"10,10 July,Luchon to Perpignan,322.0 km,Road stage",
"11,12 July,Perpignan to Montpellier,164.0 km,Road stage",
"12,13 July,Montpellier to Marseille,207.0 km,Road stage",
"13,14 July,Marseille to Cannes,181.0 km,Road stage",
"14,15 July,Cannes to Nice,132.0 km,Road stage",
"15,17 July,Nice to Gap,233.0 km,Road stage",
"16,18 July,Gap to Grenoble,102.0 km,Road stage",
"17,19 July,Grenoble to Aix-les-Bains,230.0 km,Road stage",
"18,20 July,Aix-les-Bains to Evian,204.0 km,Road stage",
"19,21 July,Evian to Belfort,282.0 km,Road stage",
"20,22 July,Belfort to Colmar,209.0 km,Road stage",
"21,23 July,Colmar to Metz,192.0 km,Road stage",
"22,24 July,Metz to Charleville,159.0 km,Road stage",
"23,26 July,Charleville to Malo-les-Bains,271.0 km,Road stage",
"24,28 July,Malo-les-Bains to Paris,313.0 km,Road stage"
];
let edition = tour_de_france_1931();
assert_eq!(edition.route(), route);
assert_eq!(edition.stage_summary(), "24 stages");
}
#[test]
fn test_tour_de_france_1932() {
let route = [
"1,6 July,Paris to Caen,208.0 km,Road stage",
"2,7 July,Caen to Nantes,300.0 km,Road stage",
"3,9 July,Nantes to Bordeaux,387.0 km,Road stage",
"4,11 July,Bordeaux to Pau,206.0 km,Road stage",
"5,12 July,Pau to Luchon,229.0 km,Road stage",
"6,14 July,Luchon to Perpignan,322.0 km,Road stage",
"7,16 July,Perpignan to Montpellier,168.0 km,Road stage",
"8,17 July,Montpellier to Marseille,206.0 km,Road stage",
"9,18 July,Marseille to Cannes,191.0 km,Road stage",
"10,19 July,Cannes to Nice,132.0 km,Road stage",
"11,21 July,Nice to Gap,233.0 km,Road stage",
"12,22 July,Gap to Grenoble,102.0 km,Road stage",
"13,23 July,Grenoble to Aix-les-Bains,230.0 km,Road stage",
"14,24 July,Aix-les-Bains to Evian,204.0 km,Road stage",
"15,25 July,Evian to Belfort,291.0 km,Road stage",
"16,26 July,Belfort to Strasbourg,145.0 km,Road stage",
"17,27 July,Strasbourg to Metz,165.0 km,Road stage",
"18,28 July,Metz to Charleville,159.0 km,Road stage",
"19,29 July,Charleville to Malo-les-Bains,271.0 km,Road stage",
"20,30 July,Malo-les-Bains to Amiens,212.0 km,Road stage",
"21,31 July,Amiens to Paris,159.0 km,Road stage"
];
let edition = tour_de_france_1932();
assert_eq!(edition.route(), route);
assert_eq!(edition.stage_summary(), "21 stages");
}
#[test]
fn test_tour_de_france_1933() {
let route = [
"1,27 June,Paris to Lille,262.0 km,Road stage",
"2,28 June,Lille to Charleville,192.0 km,Road stage",
"3,29 June,Charleville to Metz,166.0 km,Road stage",
"4,30 June,Metz to Belfort,220.0 km,Road stage",
"5,1 July,Belfort to Evian,293.0 km,Road stage",
"6,3 July,Evian to Aix-les-Bains,207.0 km,Road stage",
"7,4 July,Aix-les-Bains to Grenoble,229.0 km,Road stage",
"8,5 July,Grenoble to Gap,102.0 km,Road stage",
"9,6 July,Gap to Digne,227.0 km,Road stage",
"10,7 July,Digne to Nice,156.0 km,Road stage",
"11,9 July,Nice to Cannes,128.0 km,Road stage",
"12,10 July,Cannes to Marseille,208.0 km,Road stage",
"13,11 July,Marseille to Montpellier,168.0 km,Road stage",
"14,12 July,Montpellier to Perpignan,166.0 km,Road stage",
"15,14 July,Perpignan to Ax-les-Thermes,158.0 km,Road stage",
"16,15 July,Ax-les-Thermes to Luchon,165.0 km,Road stage",
"17,16 July,Luchon to Tarbes,91.0 km,Road stage",
"18,17 July,Tarbes to Pau,185.0 km,Road stage",
"19,19 July,Pau to Bordeaux,233.0 km,Road stage",
"20,20 July,Bordeaux to La Rochelle,183.0 km,Road stage",
"21,21 July,La Rochelle to Rennes,266.0 km,Road stage",
"22,22 July,Rennes to Caen,169.0 km,Road stage",
"23,23 July,Caen to Paris,222.0 km,Road stage"
];
let edition = tour_de_france_1933();
assert_eq!(edition.route(), route);
assert_eq!(edition.stage_summary(), "23 stages");
}
#[test]
fn test_tour_de_france_1934() {
let route = [
"1,3 July,Paris to Lille,262.0 km,Road stage",
"2,4 July,Lille to Charleville,192.0 km,Road stage",
"3,5 July,Charleville to Metz,161.0 km,Road stage",
"4,6 July,Metz to Belfort,220.0 km,Road stage",
"5,7 July,Belfort to Evian,293.0 km,Road stage",
",8 July,Rest day,Evian",
"6,9 July,Evian to Aix-les-Bains,207.0 km,Road stage",
"7,10 July,Aix-les-Bains to Grenoble,229.0 km,Road stage",
"8,11 July,Grenoble to Gap,102.0 km,Road stage",
"9,12 July,Gap to Digne,227.0 km,Road stage",
"10,13 July,Digne to Nice,156.0 km,Road stage",
",14 July,Rest day,Nice",
"11,15 July,Nice to Cannes,126.0 km,Road stage",
"12,16 July,Cannes to Marseille,195.0 km,Road stage",
"13,17 July,Marseille to Montpellier,172.0 km,Road stage",
"14,18 July,Montpellier to Perpignan,177.0 km,Road stage",
",19 July,Rest day,Perpignan",
"15,20 July,Perpignan to Ax-les-Thermes,158.0 km,Road stage",
"16,21 July,Ax-les-Thermes to Luchon,165.0 km,Road stage",
"17,22 July,Luchon to Tarbes,91.0 km,Road stage",
"18,23 July,Tarbes to Pau,172.0 km,Road stage",
",24 July,Rest day,Pau",
"19,25 July,Pau to Bordeaux,215.0 km,Road stage",
"20,26 July,Bordeaux to La Rochelle,183.0 km,Road stage",
"21a,27 July,La Rochelle to La Roche-sur-Yon,81.0 km,Road stage",
"21b,27 July,La Roche-sur-Yon to Nantes,90.0 km,Individual time trial",
"22,28 July,Nantes to Caen,275.0 km,Road stage",
"23,29 July,Caen to Paris,221.0 km,Road stage"
];
let edition = tour_de_france_1934();
assert_eq!(edition.route(), route);
assert_eq!(edition.stage_summary(), "23 stages including 1 split stage");
}
#[test]
fn test_tour_de_france_1935() {
let route = [
"1,4 July,Paris to Lille,262.0 km,Road stage",
"2,5 July,Lille to Charleville,192.0 km,Road stage",
"3,6 July,Charleville to Metz,161.0 km,Road stage",
"4,7 July,Metz to Belfort,220.0 km,Road stage",
"5a,8 July,Belfort to Geneva (Switzerland),262.0 km,Road stage",
"5b,8 July,Geneva (Switzerland) to Evian,58.0 km,Individual time trial",
",9 July,Rest day,Evian",
"6,10 July,Evian to Aix-les-Bains,207.0 km,Road stage",
"7,11 July,Aix-les-Bains to Grenoble,229.0 km,Road stage",
"8,12 July,Grenoble to Gap,102.0 km,Road stage",
"9,13 July,Gap to Digne,227.0 km,Road stage",
"10,14 July,Digne to Nice,156.0 km,Road stage",
",15 July,Rest day,Nice",
"11,16 July,Nice to Cannes,126.0 km,Road stage",
"12,17 July,Cannes to Marseille,195.0 km,Road stage",
"13a,18 July,Marseille to Nîmes,112.0 km,Road stage",
"13b,18 July,Nîmes to Montpellier,56.0 km,Individual time trial",
"14a,19 July,Montpellier to Narbonne,103.0 km,Road stage",
"14b,19 July,Narbonne to Perpignan,63.0 km,Individual time trial",
"15,20 July,Perpignan to Luchon,325.0 km,Road stage",
",21 July,Rest day,Luchon",
"16,22 July,Luchon to Pau,194.0 km,Road stage",
",23 July,Rest day,Pau",
"17,24 July,Pau to Bordeaux,224.0 km,Road stage",
"18a,25 July,Bordeaux to Rochefort,103.0 km,Road stage",
"18b,25 July,Rochefort to La Rochelle,33.0 km,Individual time trial",
"19a,26 July,La Rochelle to La Roche-sur-Yon,81.0 km,Road stage",
"19b,26 July,La Roche-sur-Yon to Nantes,90.0 km,Individual time trial",
"20a,27 July,Nantes to Vire,220.0 km,Road stage",
"20b,27 July,Vire to Caen,55.0 km,Individual time trial",
"21,28 July,Caen to Paris,221.0 km,Road stage",
];
let edition = tour_de_france_1935();
assert_eq!(edition.route(), route);
assert_eq!(edition.stage_summary(), "21 stages including 6 split stages");
}
#[test]
fn test_tour_de_france_1936() {
let mut route: Vec<String> = Vec::new();
route.push("1,7 July,Paris to Lille,258.0 km,Road stage".to_string());
route.push("2,8 July,Lille to Charleville,192.0 km,Road stage".to_string());
route.push("3,9 July,Charleville to Metz,161.0 km,Road stage".to_string());
route.push("4,10 July,Metz to Belfort,220.0 km,Road stage".to_string());
route.push("5,11 July,Belfort to Evian-les-Bains,298.0 km,Road stage".to_string());
route.push(",12 July,Rest day,Evian-les-Bains".to_string());
route.push("6,13 July,Evian-les-Bains to Aix-les-Bains,212.0 km,Road stage".to_string());
route.push("7,14 July,Aix-les-Bains to Grenoble,230.0 km,Road stage".to_string());
route.push("8,15 July,Grenoble to Briançon,194.0 km,Road stage".to_string());
route.push("9,16 July,Briançon to Digne,220.0 km,Road stage".to_string());
route.push(",17 July,Rest day,Digne".to_string());
route.push("10,18 July,Digne to Nice,156.0 km,Road stage".to_string());
route.push("11,19 July,Nice to Cannes,126.0 km,Road stage".to_string());
route.push(",20 July,Rest day,Cannes".to_string());
route.push("12,21 July,Cannes to Marseille,195.0 km,Road stage".to_string());
route.push("13a,22 July,Marseille to Nîmes,112.0 km,Road stage".to_string());
route.push("13b,22 July,Nîmes to Montpellier,52.0 km,Individual time trial".to_string());
route.push("14a,23 July,Montpellier to Narbonne,103.0 km,Road stage".to_string());
route.push("14b,23 July,Narbonne to Perpignan,63.0 km,Individual time trial".to_string());
route.push(",24 July,Rest day,Perpignan".to_string());
route.push("15,25 July,Perpignan to Luchon,325.0 km,Road stage".to_string());
route.push(",26 July,Rest day,Luchon".to_string());
route.push("16,27 July,Luchon to Pau,194.0 km,Road stage".to_string());
route.push(",28 July,Rest day,Pau".to_string());
route.push("17,29 July,Pau to Bordeaux,229.0 km,Road stage".to_string());
route.push("18a,30 July,Bordeaux to Saintes,117.0 km,Road stage".to_string());
route.push("18b,30 July,Saintes to La Rochelle,75.0 km,Individual time trial".to_string());
route.push("19a,31 July,La Rochelle to La Roche-sur-Yon,81.0 km,Road stage".to_string());
route.push("19b,31 July,La Roche-sur-Yon to Cholet,65.0 km,Individual time trial".to_string());
route.push("19c,31 July,Cholet to Angers,67.0 km,Road stage".to_string());
route.push("20a,1 August,Angers to Vire,204.0 km,Road stage".to_string());
route.push("20b,1 August,Vire to Caen,55.0 km,Individual time trial".to_string());
route.push("21,2 August,Caen to Paris,234.0 km,Road stage".to_string());
let edition = tour_de_france_1936();
assert_eq!(edition.route(), route);
assert_eq!(edition.stage_summary(), "21 stages including 5 split stages");
}
#[test]
fn test_tour_de_france_1937() {
let mut route: Vec<String> = Vec::new();
route.push("1,30 June,Paris to Lille,263.0 km,Road stage".to_string());
route.push("2,1 July,Lille to Charleville,192.0 km,Road stage".to_string());
route.push("3,2 July,Charleville to Metz,161.0 km,Road stage".to_string());
route.push("4,3 July,Metz to Belfort,220.0 km,Road stage".to_string());
route.push("5a,4 July,Belfort to Lons-le-Saunier,175.0 km,Road stage".to_string());
route.push("5b,4 July,Lons-le-Saunier to Champagnole,34.0 km,Team time trial".to_string());
route.push("5c,4 July,Champagnole to Geneva (Switzerland),93.0 km,Road stage".to_string());
route.push(",5 July,Rest day,Geneva (Switzerland)".to_string());
route.push("6,6 July,Geneva (Switzerland) to Aix-les-Bains,180.0 km,Road stage".to_string());
route.push("7,7 July,Aix-les-Bains to Grenoble,228.0 km,Road stage".to_string());
route.push("8,8 July,Grenoble to Briançon,194.0 km,Road stage".to_string());
route.push("9,9 July,Briançon to Digne,220.0 km,Road stage".to_string());
route.push(",10 July,Rest day,Digne".to_string());
route.push("10,11 July,Digne to Nice,251.0 km,Road stage".to_string());
route.push(",12 July,Rest day,Nice".to_string());
route.push("11a,13 July,Nice to Toulon,169.0 km,Road stage".to_string());
route.push("11b,13 July,Toulon to Marseille,65.0 km,Team time trial".to_string());
route.push("12a,14 July,Marseille to Nîmes,112.0 km,Road stage".to_string());
route.push("12b,14 July,Nîmes to Montpellier,51.0 km,Road stage".to_string());
route.push("13a,15 July,Montpellier to Narbonne,51.0 km,Road stage".to_string());
route.push("13b,15 July,Narbonne to Perpignan,63.0 km,Road stage".to_string());
route.push(",16 July,Rest day,Perpignan".to_string());
route.push("14a,17 July,Perpignan to Bourg-Madame,99.0 km,Road stage".to_string());
route.push("14b,17 July,Bourg-Madame to Ax-les-Thermes,59.0 km,Road stage".to_string());
route.push("14c,17 July,Ax-les-Thermes to Luchon,167.0 km,Road stage".to_string());
route.push(",18 July,Rest day,Luchon".to_string());
route.push("15,19 July,Luchon to Pau,194.0 km,Road stage".to_string());
route.push(",20 July,Rest day,Pau".to_string());
route.push("16,21 July,Pau to Bordeaux,235.0 km,Road stage".to_string());
route.push("17a,22 July,Bordeaux to Royan,123.0 km,Road stage".to_string());
route.push("17b,22 July,Royan to Saintes,37.0 km,Road stage".to_string());
route.push("17c,22 July,Saintes to La Rochelle,37.0 km,Road stage".to_string());
route.push("18a,23 July,La Rochelle to La Roche-sur-Yon,82.0 km,Team time trial".to_string());
route.push("18b,23 July,La Roche-sur-Yon to Rennes,172.0 km,Road stage".to_string());
route.push("19a,24 July,Rennes to Vire,114.0 km,Road stage".to_string());
route.push("19b,24 July,Vire to Caen,59.0 km,Individual time trial".to_string());
route.push("20,25 July,Caen to Paris,234.0 km,Road stage".to_string());
let edition = tour_de_france_1937();
assert_eq!(edition.route(), route);
assert_eq!(edition.stage_summary(), "20 stages including 8 split stages");
}
#[test]
fn test_tour_de_france_1938() {
let mut route: Vec<String> = Vec::new();
route.push("1,5 July,Paris to Caen,215.0 km,Road stage".to_string());
route.push("2,6 July,Caen to Saint-Brieuc,237.0 km,Road stage".to_string());
route.push("3,7 July,Saint-Brieuc to Nantes,238.0 km,Road stage".to_string());
route.push("4a,8 July,Nantes to La Roche-sur-Yon,62.0 km,Road stage".to_string());
route.push("4b,8 July,La Roche-sur-Yon to La Rochelle,83.0 km,Road stage".to_string());
route.push("4c,8 July,La Rochelle to Royan,83.0 km,Road stage".to_string());
route.push(",9 July,Rest day,Royan".to_string());
route.push("5,10 July,Royan to Bordeaux,198.0 km,Road stage".to_string());
route.push("6a,11 July,Bordeaux to Arcachon,53.0 km,Road stage".to_string());
route.push("6b,11 July,Arcachon to Bayonne,171.0 km,Road stage".to_string());
route.push("7,12 July,Bayonne to Pau,115.0 km,Road stage".to_string());
route.push(",13 July,Rest day,Pau".to_string());
route.push("8,14 July,Pau to Luchon,193.0 km,Road stage".to_string());
route.push(",15 July,Rest day,Luchon".to_string());
route.push("9,16 July,Luchon to Perpignan,260.0 km,Road stage".to_string());
route.push("10a,17 July,Perpignan to Narbonne,63.0 km,Road stage".to_string());
route.push("10b,17 July,Narbonne to Beziers,27.0 km,Individual time trial".to_string());
route.push("10c,17 July,Beziers to Montpellier,73.0 km,Road stage".to_string());
route.push("11,18 July,Montpellier to Marseille,223.0 km,Road stage".to_string());
route.push("12,19 July,Marseille to Cannes,199.0 km,Road stage".to_string());
route.push(",20 July,Rest day,Cannes".to_string());
route.push("13,21 July,Cannes to Digne,284.0 km,Road stage".to_string());
route.push("14,22 July,Digne to Briançon,219.0 km,Road stage".to_string());
route.push("15,23 July,Briançon to Aix-les-Bains,311.0 km,Road stage".to_string());
route.push(",24 July,Rest day,Aix-les-Bains".to_string());
route.push("16,25 July,Aix-les-Bains to Besançon,284.0 km,Road stage".to_string());
route.push("17a,26 July,Besançon to Belfort,89.0 km,Road stage".to_string());
route.push("17b,26 July,Belfort to Strasbourg,143.0 km,Road stage".to_string());
route.push("18,27 July,Strasbourg to Metz,186.0 km,Road stage".to_string());
route.push("19,28 July,Metz to Reims,196.0 km,Road stage".to_string());
route.push(",29 July,Rest day,Reims".to_string());
route.push("20a,30 July,Reims to Laon,48.0 km,Road stage".to_string());
route.push("20b,30 July,Laon to Saint-Quentin,42.0 km,Individual time trial".to_string());
route.push("20c,30 July,Saint-Quentin to Lille,107.0 km,Road stage".to_string());
route.push("21,31 July,Lille to Paris,279.0 km,Road stage".to_string());
let edition = tour_de_france_1938();
assert_eq!(edition.route(), route);
assert_eq!(edition.stage_summary(), "21 stages including 5 split stages");
}
#[test]
fn test_tour_de_france_1939() {
let route = [
"1,10 July,Paris to Caen,215.0 km,Road stage",
"2a,11 July,Caen to Vire,64.0 km,Individual time trial",
"2b,11 July,Vire to Rennes,119.0 km,Road stage",
"3,12 July,Rennes to Brest,244.0 km,Road stage",
"4,13 July,Brest to Lorient,174.0 km,Road stage",
"5,14 July,Lorient to Nantes,207.0 km,Road stage",
"6a,15 July,Nantes to La Rochelle,144.0 km,Road stage",
"6b,15 July,La Rochelle to Royan,107.0 km,Road stage",
",16 July,Rest day,Royan",
"7,17 July,Royan to Bordeaux,198.0 km,Road stage",
"8a,18 July,Bordeaux to Salies-de-Bearn,210.0 km,Road stage",
"8b,18 July,Salies-de-Bearn to Pau,69.0 km,Individual time trial",
"9,19 July,Pau to Toulouse,311.0 km,Road stage",
",20 July,Rest day,Toulouse",
"10a,21 July,Toulouse to Narbonne,149.0 km,Road stage",
"10b,21 July,Narbonne to Beziers,27.0 km,Individual time trial",
"10c,21 July,Beziers to Montpellier,70.0 km,Road stage",
"11,22 July,Montpellier to Marseille,212.0 km,Road stage",
"12a,23 July,Marseille to Saint-Raphael,157.0 km,Road stage",
"12b,23 July,Saint-Raphael to Monaco (Monaco),122.0 km,Road stage",
"13,24 July,Monaco (Monaco),101.0 km,Road stage",
"14,25 July,Monaco (Monaco) to Digne,175.0 km,Road stage",
"15,26 July,Digne to Briançon,219.0 km,Road stage",
"16a,27 July,Briançon,126.0 km,Road stage",
"16b,27 July,Bonneval to Bourg-Saint-Maurice,64.0 km,Individual time trial",
"16c,27 July,Bourg-Saint-Maurice to Annecy,104.0 km,Road stage",
",28 July,Rest day,Annecy",
"17a,29 July,Annecy to Dole,226.0 km,Road stage",
"17b,29 July,Dole to Dijon,59.0 km,Individual time trial",
"18a,30 July,Dijon to Troyes,151.0 km,Road stage",
"18b,30 July,Troyes to Paris,201.0 km,Road stage",
];
let edition = tour_de_france_1939();
assert_eq!(edition.route(), route);
assert_eq!(edition.stage_summary(), "18 stages including 8 split stages");
}
#[test]
fn test_tour_de_france_1947() {
let route = [
"1,25 June,Paris to Lille,236.0 km,Road stage",
"2,26 June,Lille to Brussels (Belgium),182.0 km,Road stage",
"3,27 June,Brussels (Belgium) to Luxembourg City (Luxembourg),314.0 km,Road stage",
"4,28 June,Luxembourg City (Luxembourg) to Strasbourg,223.0 km,Road stage",
"5,29 June,Strasbourg to Besançon,248.0 km,Road stage",
",30 June,Rest day,Besançon",
"6,1 July,Besançon to Lyon,249.0 km,Road stage",
"7,2 July,Lyon to Grenoble,172.0 km,Road stage",
"8,3 July,Grenoble to Briançon,185.0 km,Road stage",
",4 July,Rest day,Briançon",
"9,5 July,Briançon to Digne,217.0 km,Road stage",
"10,6 July,Digne to Nice,255.0 km,Road stage",
",7 July,Rest day,Nice",
"11,8 July,Nice to Marseille,230.0 km,Road stage",
"12,9 July,Marseille to Montpellier,165.0 km,Road stage",
"13,10 July,Montpellier to Carcassonne,172.0 km,Road stage",
"14,11 July,Carcassonne to Luchon,253.0 km,Road stage",
",12 July,Rest day,Luchon",
"15,13 July,Luchon to Pau,195.0 km,Road stage",
"16,14 July,Pau to Bordeaux,195.0 km,Road stage",
"17,15 July,Bordeaux to Les Sables-d'Olonne,272.0 km,Road stage",
"18,16 July,Les Sables-d'Olonne to Vannes,236.0 km,Road stage",
",17 July,Rest day,Vannes",
"19,18 July,Vannes to Saint-Brieuc,139.0 km,Individual time trial",
"20,19 July,Saint-Brieuc to Caen,235.0 km,Road stage",
"21,20 July,Caen to Paris,257.0 km,Road stage",
];
let edition = tour_de_france_1947();
assert_eq!(edition.route(), route);
assert_eq!(edition.stage_summary(), "21 stages");
}
#[test]
fn test_tour_de_france_1948() {
let route = [
"1,30 June,Paris to Trouville,237.0 km,Road stage",
"2,1 July,Trouville to Dinard,259.0 km,Road stage",
"3,2 July,Dinard to Nantes,251.0 km,Road stage",
"4,3 July,Nantes to La Rochelle,166.0 km,Road stage",
"5,4 July,La Rochelle to Bordeaux,262.0 km,Road stage",
"6,5 July,Bordeaux to Biarritz,244.0 km,Road stage",
",6 July,Rest day,Biarritz",
"7,7 July,Biarritz to Lourdes,219.0 km,Road stage",
"8,8 July,Lourdes to Toulouse,261.0 km,Road stage",
",9 July,Rest day,Toulouse",
"9,10 July,Toulouse to Montpellier,246.0 km,Road stage",
"10,11 July,Montpellier to Marseille,248.0 km,Road stage",
"11,12 July,Marseille to San Remo (Italy),245.0 km,Road stage",
"12,13 July,San Remo (Italy) to Cannes,170.0 km,Road stage",
",14 July,Rest day,Cannes",
"13,15 July,Cannes to Briançon,274.0 km,Road stage",
"14,16 July,Briançon to Aix-les-Bains,263.0 km,Road stage",
",17 July,Rest day,Aix-les-Bains",
"15,18 July,Aix-les-Bains to Lausanne (Switzerland),256.0 km,Road stage",
"16,19 July,Lausanne (Switzerland) to Mulhouse,243.0 km,Road stage",
",20 July,Rest day,Mulhouse",
"17,21 July,Mulhouse to Strasbourg,120.0 km,Individual time trial",
"18,22 July,Strasbourg to Metz,195.0 km,Road stage",
"19,23 July,Metz to Liège (Belgium),249.0 km,Road stage",
"20,24 July,Liège (Belgium) to Roubaix,228.0 km,Road stage",
"21,25 July,Roubaix to Paris,286.0 km,Road stage",
];
let edition = tour_de_france_1948();
assert_eq!(edition.route(), route);
assert_eq!(edition.stage_summary(), "21 stages");
}
#[test]
fn test_tour_de_france_1949() {
let route = [
"1,30 June,Paris to Reims,182.0 km,Road stage",
"2,1 July,Reims to Brussels (Belgium),273.0 km,Road stage",
"3,2 July,Brussels (Belgium) to Boulogne-sur-Mer,211.0 km,Road stage",
"4,3 July,Boulogne-sur-Mer to Rouen,185.0 km,Road stage",
"5,4 July,Rouen to Saint-Malo,293.0 km,Road stage",
"6,5 July,Saint-Malo to Les Sables-d'Olonne,305.0 km,Road stage",
",6 July,Rest day,Les Sables-d'Olonne",
"7,7 July,Les Sables-d'Olonne to La Rochelle,92.0 km,Individual time trial",
"8,8 July,La Rochelle to Bordeaux,262.0 km,Road stage",
"9,9 July,Bordeaux to San Sebastián (Spain),228.0 km,Road stage",
"10,10 July,San Sebastián (Spain) to Pau,192.0 km,Road stage",
",11 July,Rest day,Pau",
"11,12 July,Pau to Luchon,193.0 km,Road stage",
"12,13 July,Luchon to Toulouse,134.0 km,Road stage",
"13,14 July,Toulouse to Nîmes,289.0 km,Road stage",
"14,15 July,Nîmes to Marseille,199.0 km,Road stage",
"15,16 July,Marseille to Cannes,215.0 km,Road stage",
",17 July,Rest day,Cannes",
"16,18 July,Cannes to Briançon,275.0 km,Road stage",
"17,19 July,Briançon to Aosta (Italy),257.0 km,Road stage",
",20 July,Rest day,Aosta (Italy)",
"18,21 July,Aosta (Italy) to Lausanne (Switzerland),265.0 km,Road stage",
"19,22 July,Lausanne (Switzerland) to Colmar,283.0 km,Road stage",
"20,23 July,Colmar to Nancy,137.0 km,Individual time trial",
"21,24 July,Nancy to Paris,340.0 km,Road stage",
];
let edition = tour_de_france_1949();
assert_eq!(edition.route(), route);
assert_eq!(edition.stage_summary(), "21 stages");
}
#[test]
fn test_tour_de_france_1950() {
let route = [
"1,13 July,Paris to Metz,307.0 km,Road stage",
"2,14 July,Metz to Liège (Belgium),241.0 km,Road stage",
"3,15 July,Liège (Belgium) to Lille,232.5 km,Road stage",
"4,16 July,Lille to Rouen,231.0 km,Road stage",
"5,17 July,Rouen to Dinard,316.0 km,Road stage",
",18 July,Rest day,Dinard",
"6,19 July,Dinard to Saint-Brieuc,78.0 km,Individual time trial",
"7,20 July,Saint-Brieuc to Angers,248.0 km,Road stage",
"8,21 July,Angers to Niort,181.0 km,Road stage",
"9,22 July,Niort to Bordeaux,206.0 km,Road stage",
"10,23 July,Bordeaux to Pau,202.0 km,Road stage",
",24 July,Rest day,Pau",
"11,25 July,Pau to Saint-Gaudens,230.0 km,Road stage",
"12,26 July,Saint-Gaudens to Perpignan,233.0 km,Road stage",
"13,27 July,Perpignan to Nîmes,215.0 km,Road stage",
"14,28 July,Nîmes to Toulon,222.0 km,Road stage",
"15,29 July,Toulon to Menton,205.5 km,Road stage",
"16,30 July,Menton to Nice,96.0 km,Road stage",
",31 July,Rest day,Nice",
"17,1 August,Nice to Gap,229.0 km,Road stage",
"18,2 August,Gap to Briançon,165.0 km,Road stage",
"19,3 August,Briançon to Saint-Étienne,291.0 km,Road stage",
",4 August,Rest day,Saint-Étienne",
"20,5 August,Saint-Étienne to Lyon,98.0 km,Individual time trial",
"21,6 August,Lyon to Dijon,233.0 km,Road stage",
"22,7 August,Dijon to Paris,314.0 km,Road stage",
];
let edition = tour_de_france_1950();
assert_eq!(edition.route(), route);
assert_eq!(edition.stage_summary(), "22 stages");
}
#[test]
fn test_tour_de_france_1951() {
let route = [
"1,4 July,Metz to Reims,185.0 km,Road stage",
"2,5 July,Reims to Ghent (Belgium),228.0 km,Road stage",
"3,6 July,Ghent (Belgium) to Le Treport,219.0 km,Road stage",
"4,7 July,Le Treport to Paris,188.0 km,Road stage",
"5,8 July,Paris to Caen,215.0 km,Road stage",
"6,9 July,Caen to Rennes,182.0 km,Road stage",
"7,10 July,La Guerche-de-Bretagne to Angers,85.0 km,Individual time trial",
"8,11 July,Angers to Limoges,241.0 km,Road stage",
",12 July,Rest day,Limoges",
"9,13 July,Limoges to Clermont-Ferrand,236.0 km,Road stage",
"10,14 July,Clermont-Ferrand to Brive,216.0 km,Road stage",
"11,15 July,Brive to Agen,177.0 km,Road stage",
"12,16 July,Agen to Dax,185.0 km,Road stage",
"13,17 July,Dax to Tarbes,201.0 km,Road stage",
"14,18 July,Tarbes to Luchon,142.0 km,Road stage",
"15,19 July,Luchon to Carcassonne,213.0 km,Road stage",
"16,20 July,Carcassonne to Montpellier,192.0 km,Road stage",
",21 July,Rest day,Montpellier",
"17,22 July,Montpellier to Avignon,224.0 km,Road stage",
"18,23 July,Avignon to Marseille,173.0 km,Road stage",
"19,24 July,Marseille to Gap,208.0 km,Road stage",
"20,25 July,Gap to Briançon,165.0 km,Road stage",
"21,26 July,Briançon to Aix-les-Bains,201.0 km,Road stage",
"22,27 July,Aix-les-Bains to Geneva (Switzerland),97.0 km,Individual time trial",
"23,28 July,Geneva (Switzerland) to Dijon,197.0 km,Road stage",
"24,29 July,Dijon to Paris,322.0 km,Road stage",
];
let edition = tour_de_france_1951();
assert_eq!(edition.route(), route);
assert_eq!(edition.stage_summary(), "24 stages");
}
#[test]
fn test_tour_de_france_1952() {
let route = [
"1,25 June,Brest to Rennes,246.0 km,Road stage",
"2,26 June,Rennes to Le Mans,181.0 km,Road stage",
"3,27 June,Le Mans to Rouen,189.0 km,Road stage",
"4,28 June,Rouen to Roubaix,232.0 km,Road stage",
"5,29 June,Roubaix to Namur (Belgium),197.0 km,Road stage",
"6,30 June,Namur (Belgium) to Metz,228.0 km,Road stage",
"7,1 July,Metz to Nancy,60.0 km,Individual time trial",
"8,2 July,Nancy to Mulhouse,252.0 km,Road stage",
"9,3 July,Mulhouse to Lausanne (Switzerland),238.0 km,Road stage",
"10,4 July,Lausanne (Switzerland) to Alpe d'Huez,266.0 km,Road stage",
",5 July,Rest day,Alpe d'Huez",
"11,6 July,Le Bourg-d'Oisans to Sestrière (Italy),182.0 km,Road stage",
"12,7 July,Sestrière (Italy) to Monaco (Monaco),251.0 km,Road stage",
"13,8 July,Monaco (Monaco) to Aix-en-Provence,214.0 km,Road stage",
"14,9 July,Aix-en-Provence to Avignon,178.0 km,Road stage",
"15,10 July,Avignon to Perpignan,275.0 km,Road stage",
"16,11 July,Perpignan to Toulouse,200.0 km,Road stage",
",12 July,Rest day,Toulouse",
"17,13 July,Toulouse to Bagnères-de-Bigorre,204.0 km,Road stage",
"18,14 July,Bagnères-de-Bigorre to Pau,149.0 km,Road stage",
"19,15 July,Pau to Bordeaux,195.0 km,Road stage",
"20,16 July,Bordeaux to Limoges,228.0 km,Road stage",
"21,17 July,Limoges to Puy de Dôme,245.0 km,Road stage",
"22,18 July,Clermont-Ferrand to Vichy,63.0 km,Individual time trial",
"23,19 July,Vichy to Paris,354.0 km,Road stage",
];
let edition = tour_de_france_1952();
assert_eq!(edition.route(), route);
assert_eq!(edition.stage_summary(), "23 stages");
assert_eq!(edition.summit_finishes(), 3);
}
#[test]
fn test_tour_de_france_1953() {
let route = [
"1,3 July,Strasbourg to Metz,195.0 km,Road stage",
"2,4 July,Metz to Liège (Belgium),227.0 km,Road stage",
"3,5 July,Liège (Belgium) to Lille,221.0 km,Road stage",
"4,6 July,Lille to Dieppe,188.0 km,Road stage",
"5,7 July,Dieppe to Caen,200.0 km,Road stage",
"6,8 July,Caen to Le Mans,206.0 km,Road stage",
"7,9 July,Le Mans to Nantes,181.0 km,Road stage",
"8,10 July,Nantes to Bordeaux,345.0 km,Road stage",
",11 July,Rest day,Bordeaux",
"9,12 July,Bordeaux to Pau,197.0 km,Road stage",
"10,13 July,Pau to Cauterets,103.0 km,Road stage",
"11,14 July,Cauterets to Luchon,115.0 km,Road stage",
"12,15 July,Luchon to Albi,228.0 km,Road stage",
"13,16 July,Albi to Beziers,189.0 km,Road stage",
"14,17 July,Beziers to Nîmes,214.0 km,Road stage",
"15,18 July,Nîmes to Marseille,173.0 km,Road stage",
"16,19 July,Marseille to Monaco (Monaco),236.0 km,Road stage",
",20 July,Rest day,Monaco (Monaco)",
"17,21 July,Monaco (Monaco) to Gap,261.0 km,Road stage",
"18,22 July,Gap to Briançon,165.0 km,Road stage",
"19,23 July,Briançon to Lyon,227.0 km,Road stage",
"20,24 July,Lyon to Saint-Étienne,70.0 km,Individual time trial",
"21,25 July,Saint-Étienne to Montlucon,210.0 km,Road stage",
"22,26 July,Montlucon to Paris,328.0 km,Road stage",
];
let edition = tour_de_france_1953();
assert_eq!(edition.route(), route);
assert_eq!(edition.stage_summary(), "22 stages");
assert_eq!(edition.summit_finishes(), 1);
}
#[test]
fn test_tour_de_france_1954() {
let route = [
"1,8 July,Amsterdam (Netherlands) to Brasschaat (Belgium),216.0 km,Road stage",
"2,9 July,Beveren (Belgium) to Lille,255.0 km,Road stage",
"3,10 July,Lille to Rouen,219.0 km,Road stage",
"4a,11 July,Rouen to Circuit des Essarts,10.4 km,Team time trial",
"4b,11 July,Rouen to Caen,131.0 km,Road stage",
"5,12 July,Caen to Saint-Brieuc,224.0 km,Road stage",
"6,13 July,Saint-Brieuc to Brest,179.0 km,Road stage",
"7,14 July,Brest to Vannes,211.0 km,Road stage",
"8,15 July,Vannes to Angers,190.0 km,Road stage",
"9,16 July,Angers to Bordeaux,343.0 km,Road stage",
",17 July,Rest day,Bordeaux",
"10,18 July,Bordeaux to Bayonne,202.0 km,Road stage",
"11,19 July,Bayonne to Pau,241.0 km,Road stage",
"12,20 July,Pau to Luchon,161.0 km,Road stage",
"13,21 July,Luchon to Mulhouse,203.0 km,Road stage",
"14,22 July,Mulhouse to Millau,225.0 km,Road stage",
"15,23 July,Millau to Le Puy-en-Velay,197.0 km,Road stage",
"16,24 July,Le Puy-en-Velay to Lyon,194.0 km,Road stage",
",25 July,Rest day,Lyon",
"17,26 July,Lyon to Grenoble,182.0 km,Road stage",
"18,27 July,Grenoble to Briançon,216.0 km,Road stage",
"19,28 July,Briançon to Aix-les-Bains,221.0 km,Road stage",
"20,29 July,Aix-les-Bains to Besançon,243.0 km,Road stage",
"21a,30 July,Besançon to Epinal,134.0 km,Road stage",
"21b,30 July,Epinal to Nancy,72.0 km,Individual time trial",
"22,31 July,Nancy to Troyes,216.0 km,Road stage",
"23,1 August,Troyes to Paris,180.0 km,Road stage",
];
let edition = tour_de_france_1954();
assert_eq!(edition.route(), route);
assert_eq!(edition.stage_summary(), "23 stages including 2 split stages");
}
#[test]
fn test_tour_de_france_1955() {
let route = [
"1a,7 July,Le Havre to Dieppe,102.0 km,Road stage",
"1b,7 July,Dieppe,12.5 km,Team time trial",
"2,8 July,Dieppe to Roubaix,204.0 km,Road stage",
"3,9 July,Roubaix to Namur (Belgium),210.0 km,Road stage",
"4,10 July,Namur (Belgium) to Metz,225.0 km,Road stage",
"5,11 July,Metz to Colmar,229.0 km,Road stage",
"6,12 July,Colmar to Zurich (Switzerland),195.0 km,Road stage",
"7,13 July,Zurich (Switzerland) to Thonon-les-Bains,267.0 km,Road stage",
"8,14 July,Thonon-les-Bains to Briançon,253.0 km,Road stage",
"9,15 July,Briançon to Monaco (Monaco),275.0 km,Road stage",
",16 July,Rest day,Monaco (Monaco)",
"10,17 July,Monaco (Monaco) to Marseille,240.0 km,Road stage",
"11,18 July,Marseille to Avignon,198.0 km,Road stage",
"12,19 July,Avignon to Millau,240.0 km,Road stage",
"13,20 July,Millau to Albi,205.0 km,Road stage",
"14,21 July,Albi to Narbonne,156.0 km,Road stage",
"15,22 July,Narbonne to Ax-les-Thermes,151.0 km,Road stage",
",23 July,Rest day,Ax-les-Thermes",
"16,24 July,Ax-les-Thermes to Toulouse,123.0 km,Road stage",
"17,25 July,Toulouse to Saint-Gaudens,250.0 km,Road stage",
"18,26 July,Saint-Gaudens to Pau,205.0 km,Road stage",
"19,27 July,Pau to Bordeaux,195.0 km,Road stage",
"20,28 July,Bordeaux to Poitiers,243.0 km,Road stage",
"21,29 July,Chatellerault to Tours,68.6 km,Individual time trial",
"22,30 July,Tours to Paris,229.0 km,Road stage",
];
let edition = tour_de_france_1955();
assert_eq!(edition.route(), route);
assert_eq!(edition.stage_summary(), "22 stages including 1 split stage");
}
#[test]
fn test_tour_de_france_1956() {
let route = [
"1,5 July,Reims to Liège (Belgium),223.0 km,Road stage",
"2,6 July,Liège (Belgium) to Lille,217.0 km,Road stage",
"3,7 July,Lille to Rouen,225.0 km,Road stage",
"4a,8 July,Circuit de Rouen-Les-Essarts,15.1 km,Individual time trial",
"4b,8 July,Rouen to Caen,125.0 km,Road stage",
"5,9 July,Caen to Saint-Malo,189.0 km,Road stage",
"6,10 July,Saint-Malo to Lorient,192.0 km,Road stage",
"7,11 July,Lorient to Angers,244.0 km,Road stage",
"8,12 July,Angers to La Rochelle,180.0 km,Road stage",
"9,13 July,La Rochelle to Bordeaux,219.0 km,Road stage",
",14 July,Rest day,Bordeaux",
"10,15 July,Bordeaux to Bayonne,201.0 km,Road stage",
"11,16 July,Bayonne to Pau,255.0 km,Road stage",
"12,17 July,Pau to Luchon,130.0 km,Road stage",
"13,18 July,Luchon to Toulouse,176.0 km,Road stage",
"14,19 July,Toulouse to Montpellier,231.0 km,Road stage",
"15,20 July,Montpellier to Aix-en-Provence,204.0 km,Road stage",
",21 July,Rest day,Aix-en-Provence",
"16,22 July,Aix-en-Provence to Gap,203.0 km,Road stage",
"17,23 July,Gap to Turin (Italy),234.0 km,Road stage",
"18,24 July,Turin (Italy) to Grenoble,250.0 km,Road stage",
"19,25 July,Grenoble to Saint-Étienne,173.0 km,Road stage",
"20,26 July,Saint-Étienne to Lyon,73.0 km,Individual time trial",
"21,27 July,Lyon to Montlucon,237.0 km,Road stage",
"22,28 July,Montlucon to Paris,331.0 km,Road stage",
];
let edition = tour_de_france_1956();
assert_eq!(edition.route(), route);
assert_eq!(edition.stage_summary(), "22 stages including 1 split stage");
}
#[test]
fn test_tour_de_france_1957() {
let route = [
"1,27 June,Nantes to Granville,204.0 km,Road stage",
"2,28 June,Granville to Caen,226.0 km,Road stage",
"3a,29 June,Circuit de la Prairie,15.0 km,Team time trial",
"3b,29 June,Caen to Rouen,134.0 km,Road stage",
"4,30 June,Rouen to Roubaix,232.0 km,Road stage",
"5,1 July,Roubaix to Charleroi (Belgium),170.0 km,Road stage",
"6,2 July,Charleroi (Belgium) to Metz,248.0 km,Road stage",
"7,3 July,Metz to Colmar,223.0 km,Road stage",
"8,4 July,Colmar to Besançon,192.0 km,Road stage",
"9,5 July,Besançon to Thonon-les-Bains,188.0 km,Road stage",
",6 July,Rest day,Thonon-les-Bains",
"10,7 July,Thonon-les-Bains to Briançon,247.0 km,Road stage",
"11,8 July,Briançon to Cannes,286.0 km,Road stage",
"12,9 July,Cannes to Marseille,239.0 km,Road stage",
"13,10 July,Marseille to Ales,160.0 km,Road stage",
"14,11 July,Ales to Perpignan,246.0 km,Road stage",
"15a,12 July,Perpignan to Barcelona (Spain),197.0 km,Road stage",
"15b,12 July,Montjuic circuit (Spain),9.8 km,Individual time trial",
",13 July,Rest day,Barcelona (Spain)",
"16,14 July,Barcelona (Spain) to Ax-les-Thermes,220.0 km,Road stage",
"17,15 July,Ax-les-Thermes to Saint-Gaudens,236.0 km,Road stage",
"18,16 July,Saint-Gaudens to Pau,207.0 km,Road stage",
"19,17 July,Pau to Bordeaux,194.0 km,Road stage",
"20,18 July,Bordeaux to Libourne,66.0 km,Individual time trial",
"21,19 July,Libourne to Tours,317.0 km,Road stage",
"22,20 July,Tours to Paris,227.0 km,Road stage",
];
let edition = tour_de_france_1957();
assert_eq!(edition.route(), route);
assert_eq!(edition.stage_summary(), "22 stages including 2 split stages");
}
#[test]
fn test_tour_de_france_1958() {
let route = [
"1,26 June,Brussels (Belgium) to Ghent (Belgium),184.0 km,Road stage",
"2,27 June,Ghent (Belgium) to Dunkerque,198.0 km,Road stage",
"3,28 June,Dunkerque to Mers-les-Bains,177.0 km,Road stage",
"4,29 June,Le Treport to Versailles,205.0 km,Road stage",
"5,30 June,Versailles to Caen,232.0 km,Road stage",
"6,1 July,Caen to Saint-Brieuc,223.0 km,Road stage",
"7,2 July,Saint-Brieuc to Brest,170.0 km,Road stage",
"8,3 July,Châteaulin,46.0 km,Individual time trial",
"9,4 July,Quimper to Saint-Nazaire,206.0 km,Road stage",
"10,5 July,Saint-Nazaire to Royan,255.0 km,Road stage",
"11,6 July,Royan to Bordeaux,137.0 km,Road stage",
"12,7 July,Bordeaux to Dax,161.0 km,Road stage",
"13,8 July,Dax to Pau,230.0 km,Road stage",
"14,9 July,Pau to Luchon,129.0 km,Road stage",
"15,10 July,Luchon to Toulouse,176.0 km,Road stage",
"16,11 July,Toulouse to Beziers,187.0 km,Road stage",
"17,12 July,Beziers to Nîmes,189.0 km,Road stage",
"18,13 July,Bedoin to Mont Ventoux,21.0 km,Individual time trial",
"19,14 July,Carpentras to Gap,178.0 km,Road stage",
"20,15 July,Gap to Briançon,165.0 km,Road stage",
"21,16 July,Briançon to Aix-les-Bains,219.0 km,Road stage",
"22,17 July,Aix-les-Bains to Besançon,237.0 km,Road stage",
"23,18 July,Besançon to Dijon,74.0 km,Individual time trial",
"24,19 July,Dijon to Paris,320.0 km,Road stage",
];
let edition = tour_de_france_1958();
assert_eq!(edition.route(), route);
assert_eq!(edition.stage_summary(), "24 stages");
assert_eq!(edition.summit_finishes(), 1);
}
#[test]
fn test_tour_de_france_1959() {
let route = [
"1,25 June,Mulhouse to Metz,238.0 km,Road stage",
"2,26 June,Metz to Namur (Belgium),234.0 km,Road stage",
"3,27 June,Namur (Belgium) to Roubaix,217.0 km,Road stage",
"4,28 June,Roubaix to Rouen,230.0 km,Road stage",
"5,29 June,Rouen to Rennes,286.0 km,Road stage",
"6,30 June,Blain to Nantes,45.0 km,Individual time trial",
"7,1 July,Nantes to La Rochelle,190.0 km,Road stage",
"8,2 July,La Rochelle to Bordeaux,201.0 km,Road stage",
"9,3 July,Bordeaux to Bayonne,207.0 km,Road stage",
",4 July,Rest day,Bayonne",
"10,5 July,Bayonne to Bagnères-de-Bigorre,235.0 km,Road stage",
"11,6 July,Bagnères-de-Bigorre to Saint-Gaudens,119.0 km,Road stage",
"12,7 July,Saint-Gaudens to Albi,184.0 km,Road stage",
"13,8 July,Albi to Aurillac,219.0 km,Road stage",
"14,9 July,Aurillac to Clermont-Ferrand,231.0 km,Road stage",
"15,10 July,Puy de Dôme,12.0 km,Individual time trial",
"16,11 July,Clermont-Ferrand to Saint-Étienne,210.0 km,Road stage",
",12 July,Rest day,Saint-Étienne",
"17,13 July,Saint-Étienne to Grenoble,197.0 km,Road stage",
"18,14 July,Grenoble to Saint-Vincent (Italy),243.0 km,Road stage",
"19,15 July,Saint-Vincent (Italy) to Annecy,251.0 km,Road stage",
"20,16 July,Annecy to Chalon-sur-Saône,202.0 km,Road stage",
"21,17 July,Seurre to Dijon,69.0 km,Individual time trial",
"22,18 July,Dijon to Paris,331.0 km,Road stage",
];
let edition = tour_de_france_1959();
assert_eq!(edition.route(), route);
assert_eq!(edition.stage_summary(), "22 stages");
assert_eq!(edition.summit_finishes(), 1);
}
#[test]
fn test_tour_de_france_1960() {
let route = [
"1a,26 June,Lille to Brussels (Belgium),108.0 km,Road stage",
"1b,26 June,Brussels (Belgium),27.8 km,Individual time trial",
"2,27 June,Brussels (Belgium) to Dunkerque,206.0 km,Road stage",
"3,28 June,Dunkerque to Dieppe,209.0 km,Road stage",
"4,29 June,Dieppe to Caen,211.0 km,Road stage",
"5,30 June,Caen to Saint-Malo,189.0 km,Road stage",
"6,1 July,Saint-Malo to Lorient,191.0 km,Road stage",
"7,2 July,Lorient to Angers,244.0 km,Road stage",
"8,3 July,Angers to Limoges,240.0 km,Road stage",
"9,4 July,Limoges to Bordeaux,225.0 km,Road stage",
"10,5 July,Mont-de-Marsan to Pau,228.0 km,Road stage",
"11,6 July,Pau to Luchon,161.0 km,Road stage",
"12,7 July,Luchon to Toulouse,176.0 km,Road stage",
"13,8 July,Toulouse to Millau,224.0 km,Road stage",
",9 July,Rest day,Millau",
"14,10 July,Millau to Avignon,217.0 km,Road stage",
"15,11 July,Avignon to Gap,187.0 km,Road stage",
"16,12 July,Gap to Briançon,172.0 km,Road stage",
"17,13 July,Briançon to Aix-les-Bains,229.0 km,Road stage",
"18,14 July,Aix-les-Bains to Thonon-les-Bains,215.0 km,Road stage",
"19,15 July,Pontarlier to Besançon,83.0 km,Individual time trial",
"20,16 July,Besançon to Troyes,229.0 km,Road stage",
"21,17 July,Troyes to Paris,200.0 km,Road stage",
];
let edition = tour_de_france_1960();
assert_eq!(edition.route(), route);
assert_eq!(edition.stage_summary(), "21 stages including 1 split stage");
}
#[test]
fn test_tour_de_france_1961() {
let route = [
"1a,25 June,Rouen to Versailles,136.5 km,Road stage",
"1b,25 June,Versailles,28.5 km,Individual time trial",
"2,26 June,Pontoise to Roubaix,230.5 km,Road stage",
"3,27 June,Roubaix to Charleroi (Belgium),197.5 km,Road stage",
"4,28 June,Charleroi (Belgium) to Metz,237.5 km,Road stage",
"5,29 June,Metz to Strasbourg,221.0 km,Road stage",
"6,30 June,Strasbourg to Belfort,180.5 km,Road stage",
"7,1 July,Belfort to Chalon-sur-Saône,214.5 km,Road stage",
"8,2 July,Chalon-sur-Saône to Saint-Étienne,240.5 km,Road stage",
"9,3 July,Saint-Étienne to Grenoble,230.0 km,Road stage",
"10,4 July,Grenoble to Turin (Italy),250.5 km,Road stage",
"11,5 July,Turin (Italy) to Antibes,225.0 km,Road stage",
"12,6 July,Antibes to Aix-en-Provence,199.0 km,Road stage",
"13,7 July,Aix-en-Provence to Montpellier,177.5 km,Road stage",
",8 July,Rest day,Montpellier",
"14,9 July,Montpellier to Perpignan,174.0 km,Road stage",
"15,10 July,Perpignan to Toulouse,206.0 km,Road stage",
"16,11 July,Toulouse to Superbagnères,208.0 km,Road stage",
"17,12 July,Luchon to Pau,197.0 km,Road stage",
"18,13 July,Pau to Bordeaux,207.0 km,Road stage",
"19,14 July,Bergerac to Périgueux,74.5 km,Individual time trial",
"20,15 July,Périgueux to Tours,309.5 km,Road stage",
"21,16 July,Tours to Paris,252.5 km,Road stage",
];
let edition = tour_de_france_1961();
assert_eq!(edition.route(), route);
assert_eq!(edition.stage_summary(), "21 stages including 1 split stage");
assert_eq!(edition.summit_finishes(), 1);
}
#[test]
fn test_tour_de_france_1962() {
let route = [
"1,24 June,Nancy to Spa (Belgium),253.0 km,Road stage",
"2a,25 June,Spa (Belgium) to Herentals (Belgium),147.0 km,Road stage",
"2b,25 June,Herentals (Belgium),23.0 km,Team time trial",
"3,26 June,Brussels (Belgium) to Amiens,210.0 km,Road stage",
"4,27 June,Amiens to Le Havre,196.5 km,Road stage",
"5,28 June,Pont l'Eveque to Saint-Malo,215.0 km,Road stage",
"6,29 June,Dinard to Brest,235.5 km,Road stage",
"7,30 June,Quimper to Saint-Nazaire,201.0 km,Road stage",
"8a,1 July,Saint-Nazaire to Lucon,155.0 km,Road stage",
"8b,1 July,Lucon to La Rochelle,43.0 km,Individual time trial",
"9,2 July,La Rochelle to Bordeaux,214.0 km,Road stage",
"10,3 July,Bordeaux to Bayonne,184.5 km,Road stage",
"11,4 July,Bayonne to Pau,155.5 km,Road stage",
"12,5 July,Pau to Saint-Gaudens,207.5 km,Road stage",
"13,6 July,Luchon to Superbagnères,18.5 km,Individual time trial",
"14,7 July,Luchon to Carcassonne,215.0 km,Road stage",
"15,8 July,Carcassonne to Montpellier,196.5 km,Road stage",
"16,9 July,Montpellier to Aix-en-Provence,185.0 km,Road stage",
"17,10 July,Aix-en-Provence to Antibes,201.0 km,Road stage",
"18,11 July,Antibes to Briançon,241.5 km,Road stage",
"19,12 July,Briançon to Aix-les-Bains,204.5 km,Road stage",
"20,13 July,Bourgoin to Lyon,68.0 km,Individual time trial",
"21,14 July,Lyon to Nevers,232.0 km,Road stage",
"22,15 July,Nevers to Paris,271.0 km,Road stage",
];
let edition = tour_de_france_1962();
assert_eq!(edition.route(), route);
assert_eq!(edition.stage_summary(), "22 stages including 2 split stages");
assert_eq!(edition.summit_finishes(), 1);
}
#[test]
fn test_tour_de_france_1963() {
let route = [
"1,23 June,Paris to Epernay,152.0 km,Road stage",
"2a,24 June,Reims to Jambes (Belgium),186.0 km,Road stage",
"2b,24 June,Jambes (Belgium),22.0 km,Team time trial",
"3,25 June,Jambes (Belgium) to Roubaix,223.0 km,Road stage",
"4,26 June,Roubaix to Rouen,236.0 km,Road stage",
"5,27 June,Rouen to Rennes,285.0 km,Road stage",
"6a,28 June,Rennes to Angers,118.0 km,Road stage",
"6b,28 June,Angers,25.0 km,Individual time trial",
"7,29 June,Angers to Limoges,236.0 km,Road stage",
"8,30 June,Limoges to Bordeaux,232.0 km,Road stage",
"9,1 July,Bordeaux to Pau,202.0 km,Road stage",
"10,2 July,Pau to Bagnères-de-Bigorre,148.0 km,Road stage",
"11,3 July,Bagnères-de-Bigorre to Luchon,131.0 km,Road stage",
"12,4 July,Luchon to Toulouse,173.0 km,Road stage",
"13,5 July,Toulouse to Aurillac,234.0 km,Road stage",
",6 July,Rest day,Aurillac",
"14,7 July,Aurillac to Saint-Étienne,237.0 km,Road stage",
"15,8 July,Saint-Étienne to Grenoble,174.0 km,Road stage",
"16,9 July,Grenoble to Val d'Isère,202.0 km,Road stage",
"17,10 July,Val d'Isère to Chamonix,228.0 km,Road stage",
"18,11 July,Chamonix to Lons-le-Saunier,225.0 km,Road stage",
"19,12 July,Arbois to Besançon,54.0 km,Individual time trial",
"20,13 July,Besançon to Troyes,234.0 km,Road stage",
"21,14 July,Troyes to Paris,185.0 km,Road stage",
];
let edition = tour_de_france_1963();
assert_eq!(edition.route(), route);
assert_eq!(edition.stage_summary(), "21 stages including 2 split stages");
assert_eq!(edition.summit_finishes(), 1);
}
#[test]
fn test_tour_de_france_1964() {
let route = [
"1,22 June,Rennes to Lisieux,215.0 km,Road stage",
"2,23 June,Lisieux to Amiens,208.0 km,Road stage",
"3a,24 June,Amiens to Forest (Belgium),197.0 km,Road stage",
"3b,24 June,Forest (Belgium),21.0 km,Team time trial",
"4,25 June,Forest (Belgium) to Metz,292.0 km,Road stage",
"5,26 June,Luneville to Freiburg (West Germany),161.0 km,Road stage",
"6,27 June,Freiburg (West Germany) to Besançon,200.0 km,Road stage",
"7,28 June,Besançon to Thonon-les-Bains,195.0 km,Road stage",
"8,29 June,Thonon-les-Bains to Briançon,249.0 km,Road stage",
"9,30 June,Briançon to Monaco (Monaco),239.0 km,Road stage",
"10a,1 July,Monaco (Monaco) to Hyeres,187.0 km,Road stage",
"10b,1 July,Hyeres to Toulon,21.0 km,Individual time trial",
"11,2 July,Toulon to Montpellier,250.0 km,Road stage",
"12,3 July,Montpellier to Perpignan,174.0 km,Road stage",
"13,4 July,Perpignan to Andorra la Vella (Andorra),170.0 km,Road stage",
",5 July,Rest day,Andorra la Vella (Andorra)",
"14,6 July,Andorra la Vella (Andorra) to Toulouse,186.0 km,Road stage",
"15,7 July,Toulouse to Luchon,203.0 km,Road stage",
"16,8 July,Luchon to Pau,197.0 km,Road stage",
"17,9 July,Peyrehorade to Bayonne,43.0 km,Individual time trial",
"18,10 July,Bayonne to Bordeaux,187.0 km,Road stage",
"19,11 July,Bordeaux to Brive,215.0 km,Road stage",
"20,12 July,Brive to Puy de Dôme,217.0 km,Road stage",
"21,13 July,Clermont-Ferrand to Orléans,311.0 km,Road stage",
"22a,14 July,Orléans to Versailles,119.0 km,Road stage",
"22b,14 July,Versailles to Paris,27.0 km,Individual time trial",
];
let edition = tour_de_france_1964();
assert_eq!(edition.route(), route);
assert_eq!(edition.stage_summary(), "22 stages including 3 split stages");
}
#[test]
fn test_tour_de_france_1965() {
let route = [
"1a,22 June,Cologne (West Germany) to Liège (Belgium),149.0 km,Road stage",
"1b,22 June,Liège (Belgium),22.5 km,Team time trial",
"2,23 June,Liège (Belgium) to Roubaix,200.5 km,Road stage",
"3,24 June,Roubaix to Rouen,240.0 km,Road stage",
"4,25 June,Caen to Saint-Brieuc,227.0 km,Road stage",
"5a,26 June,Saint-Brieuc to Châteaulin,147.0 km,Road stage",
"5b,26 June,Châteaulin,26.7 km,Individual time trial",
"6,27 June,Quimper to La Baule,210.5 km,Road stage",
"7,28 June,La Baule to La Rochelle,219.0 km,Road stage",
"8,29 June,La Rochelle to Bordeaux,197.5 km,Road stage",
"9,30 June,Dax to Bagnères-de-Bigorre,226.5 km,Road stage",
"10,1 July,Bagnères-de-Bigorre to Ax-les-Thermes,222.5 km,Road stage",
"11,2 July,Ax-les-Thermes to Barcelona (Spain),240.5 km,Road stage",
",3 July,Rest day,Barcelona (Spain)",
"12,4 July,Barcelona (Spain) to Perpignan,219.0 km,Road stage",
"13,5 July,Perpignan to Montpellier,164.0 km,Road stage",
"14,6 July,Montpellier to Mont Ventoux,173.0 km,Road stage",
"15,7 July,Carpentras to Gap,167.5 km,Road stage",
"16,8 July,Gap to Briançon,177.0 km,Road stage",
"17,9 July,Briançon to Aix-les-Bains,193.5 km,Road stage",
"18,10 July,Aix-les-Bains to Le Revard,26.9 km,Individual time trial",
"19,11 July,Aix-les-Bains to Lyon,165.0 km,Road stage",
"20,12 July,Lyon to Auxerre,198.5 km,Road stage",
"21,13 July,Auxerre to Versailles,225.5 km,Road stage",
"22,14 July,Versailles to Paris,37.8 km,Individual time trial",
];
let edition = tour_de_france_1965();
assert_eq!(edition.route(), route);
assert_eq!(edition.stage_summary(), "22 stages including 2 split stages");
}
#[test]
fn test_tour_de_france_1966() {
let route = [
"1,21 June,Nancy to Charleville,209.0 km,Road stage",
"2,22 June,Charleville to Tournai (Belgium),198.0 km,Road stage",
"3a,23 June,Tournai (Belgium),21.0 km,Team time trial",
"3b,23 June,Tournai (Belgium) to Dunkerque,131.0 km,Road stage",
"4,24 June,Dunkerque to Dieppe,205.0 km,Road stage",
"5,25 June,Dieppe to Caen,178.0 km,Road stage",
"6,26 June,Caen to Angers,217.0 km,Road stage",
"7,27 June,Angers to Royan,252.0 km,Road stage",
"8,28 June,Royan to Bordeaux,138.0 km,Road stage",
"9,29 June,Bordeaux to Bayonne,201.0 km,Road stage",
"10,30 June,Bayonne to Pau,234.0 km,Road stage",
"11,1 July,Pau to Luchon,188.0 km,Road stage",
",2 July,Rest day,Luchon",
"12,3 July,Luchon to Revel,219.0 km,Road stage",
"13,4 July,Revel to Sete,191.0 km,Road stage",
"14a,5 July,Montpellier to Vals-les-Bains,144.0 km,Road stage",
"14b,5 July,Vals-les-Bains,20.0 km,Individual time trial",
"15,6 July,Privas to Le Bourg-d'Oisans,203.0 km,Road stage",
"16,7 July,Le Bourg-d'Oisans to Briançon,148.0 km,Road stage",
"17,8 July,Briançon to Turin (Italy),160.0 km,Road stage",
",9 July,Rest day,Turin (Italy)",
"18,10 July,Ivrea (Italy) to Chamonix,188.0 km,Road stage",
"19,11 July,Chamonix to Saint-Étienne,265.0 km,Road stage",
"20,12 July,Saint-Étienne to Montlucon,223.0 km,Road stage",
"21,13 July,Montlucon to Orléans,232.0 km,Road stage",
"22a,14 July,Orléans to Rambouillet,111.0 km,Road stage",
"22b,14 July,Rambouillet to Paris,51.0 km,Individual time trial",
];
let edition = tour_de_france_1966();
assert_eq!(edition.route(), route);
assert_eq!(edition.stage_summary(), "22 stages including 3 split stages");
}
#[test]
fn test_tour_de_france_1967() {
let route = [
"P,29 June,Angers,5.8 km,Individual time trial",
"1,30 June,Angers to Saint-Malo,185.5 km,Road stage",
"2,1 July,Saint-Malo to Caen,180.0 km,Road stage",
"3,2 July,Caen to Amiens,248.0 km,Road stage",
"4,3 July,Amiens to Roubaix,191.0 km,Road stage",
"5a,4 July,Roubaix to Jambes (Belgium),172.0 km,Road stage",
"5b,4 July,Jambes (Belgium),17.0 km,Team time trial",
"6,5 July,Jambes (Belgium) to Metz,238.0 km,Road stage",
"7,6 July,Metz to Strasbourg,205.5 km,Road stage",
"8,7 July,Metz to Belfort,215.0 km,Road stage",
",8 July,Rest day,Belfort",
"9,9 July,Belfort to Divonne-les-Bains,238.5 km,Road stage",
"10,10 July,Divonne-les-Bains to Briançon,243.0 km,Road stage",
"11,11 July,Briançon to Digne,197.0 km,Road stage",
"12,12 July,Digne to Marseille,207.5 km,Road stage",
"13,13 July,Marseille to Carpentras,211.5 km,Road stage",
"14,14 July,Carpentras to Sete,201.5 km,Road stage",
",15 July,Rest day,Sete",
"15,16 July,Sete to Toulouse,230.5 km,Road stage",
"16,17 July,Toulouse to Luchon,188.0 km,Road stage",
"17,18 July,Luchon to Pau,250.0 km,Road stage",
"18,19 July,Pau to Bordeaux,206.5 km,Road stage",
"19,20 July,Bordeaux to Limoges,217.0 km,Road stage",
"20,21 July,Limoges to Puy de Dôme,222.0 km,Road stage",
"21,22 July,Clermont-Ferrand to Fontainebleau,359.0 km,Road stage",
"22a,23 July,Fontainebleau to Versailles,104.0 km,Road stage",
"22b,23 July,Versailles to Paris,46.6 km,Individual time trial",
];
let edition = tour_de_france_1967();
assert_eq!(edition.route(), route);
assert_eq!(edition.stage_summary(), "22 stages + Prologue including 2 split stages");
}
#[test]
fn test_tour_de_france_1968() {
let route = [
"P,27 June,Vittel,6.1 km,Individual time trial",
"1,28 June,Vittel to Esch-sur-Alzette (Luxembourg),189.0 km,Road stage",
"2,29 June,Arlon (Belgium) to Forest (Belgium),210.5 km,Road stage",
"3a,30 June,Forest (Belgium),22.0 km,Team time trial",
"3b,30 June,Forest (Belgium) to Roubaix,112.0 km,Road stage",
"4,1 July,Roubaix to Rouen,238.0 km,Road stage",
"5a,2 July,Rouen to Bagnoles-de-l'Orne,165.0 km,Road stage",
"5b,2 July,Bagnoles-de-l'Orne to Dinard,154.5 km,Road stage",
"6,3 July,Dinard to Lorient,188.0 km,Road stage",
"7,4 July,Lorient to Nantes,190.0 km,Road stage",
"8,5 July,Nantes to Royan,233.0 km,Road stage",
",6 July,Rest day,Royan",
"9,7 July,Royan to Bordeaux,137.5 km,Road stage",
"10,8 July,Bordeaux to Bayonne,202.5 km,Road stage",
"11,9 July,Bayonne to Pau,183.5 km,Road stage",
"12,10 July,Pau to Saint-Gaudens,226.5 km,Road stage",
"13,11 July,Saint-Gaudens to La Seu d'Urgell (Spain),208.5 km,Road stage",
"14,12 July,La Seu d'Urgell (Spain) to Perpignan,231.5 km,Road stage",
",13 July,Rest day,Font-Romeu-Odeillo-Via",
"15,14 July,Font-Romeu-Odeillo-Via to Albi,250.5 km,Road stage",
"16,15 July,Albi to Aurillac,199.0 km,Road stage",
"17,16 July,Aurillac to Saint-Étienne,236.5 km,Road stage",
"18,17 July,Saint-Étienne to Grenoble,235.0 km,Road stage",
"19,18 July,Grenoble to Sallanches,200.0 km,Road stage",
"20,19 July,Sallanches to Besançon,242.5 km,Road stage",
"21,20 July,Besançon to Auxerre,242.0 km,Road stage",
"22a,21 July,Auxerre to Melun,136.0 km,Road stage",
"22b,21 July,Melun to Paris,55.2 km,Individual time trial",
];
let edition = tour_de_france_1968();
assert_eq!(edition.route(), route);
assert_eq!(edition.stage_summary(), "22 stages + Prologue including 3 split stages");
}
#[test]
fn test_tour_de_france_1969() {
let route = [
"P,28 June,Roubaix,10.0 km,Individual time trial",
"1a,29 June,Roubaix to Sint-Pieters-Woluwe (Belgium),147.0 km,Road stage",
"1b,29 June,Sint-Pieters-Woluwe (Belgium),16.0 km,Team time trial",
"2,30 June,Sint-Pieters-Woluwe (Belgium) to Maastricht (Netherlands),182.0 km,Road stage",
"3,1 July,Maastricht (Netherlands) to Charleville-Mezieres,213.0 km,Road stage",
"4,2 July,Charleville-Mezieres to Nancy,214.0 km,Road stage",
"5,3 July,Nancy to Mulhouse,194.0 km,Road stage",
"6,4 July,Mulhouse to Ballon d'Alsace,133.0 km,Road stage",
"7,5 July,Belfort to Divonne-les-Bains,241.0 km,Road stage",
"8a,6 July,Divonne-les-Bains,9.0 km,Individual time trial",
"8b,6 July,Divonne-les-Bains to Thonon-les-Bains,137.0 km,Road stage",
"9,7 July,Thonon-les-Bains to Chamonix,111.0 km,Road stage",
"10,8 July,Chamonix to Briançon,221.0 km,Road stage",
"11,9 July,Briançon to Digne,198.0 km,Road stage",
"12,10 July,Digne to Aubagne,161.0 km,Road stage",
"13,11 July,Aubagne to La Grande-Motte,196.0 km,Road stage",
"14,12 July,La Grande-Motte to Revel,234.0 km,Road stage",
",13 July,Rest day,Revel",
"15,14 July,Castelnaudary to Luchon,199.0 km,Road stage",
"16,15 July,Luchon to Mourenx,214.0 km,Road stage",
"17,16 July,Mourenx to Bordeaux,201.0 km,Road stage",
"18,17 July,Bordeaux to Brive,193.0 km,Road stage",
"19,18 July,Brive to Puy de Dôme,198.0 km,Road stage",
"20,19 July,Clermont-Ferrand to Montargis,329.0 km,Road stage",
"21a,20 July,Montargis to Creteil,111.0 km,Road stage",
"21b,20 July,Creteil to Paris,37.0 km,Individual time trial",
];
let edition = tour_de_france_1969();
assert_eq!(edition.route(), route);
assert_eq!(edition.stage_summary(), "21 stages + Prologue including 3 split stages");
}
#[test]
fn test_tour_de_france_1970() {
let route = [
"P,26 June,Limoges,7.4 km,Individual time trial",
"1,27 June,Limoges to La Rochelle,224.0 km,Road stage",
"2,28 June,La Rochelle to Angers,200.0 km,Road stage",
"3a,29 June,Angers,10.7 km,Team time trial",
"3b,29 June,Angers to Rennes,140.0 km,Road stage",
"4,30 June,Rennes to Lisieux,229.0 km,Road stage",
"5a,1 July,Lisieux to Rouen,94.5 km,Road stage",
"5b,1 July,Rouen to Amiens,223.0 km,Road stage",
"6,2 July,Amiens to Valenciennes,135.5 km,Road stage",
"7a,3 July,Valenciennes to Forest (Belgium),120.0 km,Road stage",
"7b,3 July,Forest (Belgium),7.2 km,Individual time trial",
"8,4 July,Ciney to Felsberg (West Germany),232.5 km,Road stage",
"9,5 July,Saarlouis (West Germany) to Mulhouse,269.5 km,Road stage",
"10,6 July,Belfort to Divonne-les-Bains,241.0 km,Road stage",
"11a,7 July,Divonne-les-Bains,8.8 km,Individual time trial",
"11b,7 July,Divonne-les-Bains to Thonon-les-Bains,139.5 km,Road stage",
"12,8 July,Divonne-les-Bains to Grenoble,194.0 km,Road stage",
"13,9 July,Grenoble to Gap,194.5 km,Road stage",
"14,10 July,Gap to Mont Ventoux,170.0 km,Road stage",
"15,11 July,Carpentras to Montpellier,140.5 km,Road stage",
"16,12 July,Montpellier to Toulouse,160.0 km,Road stage",
"17,13 July,Toulouse to Saint-Gaudens,190.0 km,Road stage",
"18,14 July,Saint-Gaudens to La Mongie,135.5 km,Road stage",
"19,15 July,Bagnères-de-Bigorre to Mourenx,185.5 km,Road stage",
"20a,16 July,Mourenx to Bordeaux,223.5 km,Road stage",
"20b,16 July,Bordeaux,8.2 km,Individual time trial",
"21,17 July,Ruffex to Tours,191.5 km,Road stage",
"22,18 July,Tours to Versailles,238.5 km,Road stage",
"23,19 July,Versailles to Paris,54.0 km,Individual time trial",
];
let edition = tour_de_france_1970();
assert_eq!(edition.route(), route);
assert_eq!(edition.stage_summary(), "23 stages + Prologue including 5 split stages");
}
#[test]
fn test_tour_de_france_1971() {
let route = [
"P,26 June,Mulhouse,11.0 km,Individual time trial",
"1a,27 June,Mulhouse to Basel (Switzerland),59.5 km,Road stage",
"1b,27 June,Basel (Switzerland) to Freiburg (West Germany),90.0 km,Road stage",
"1c,27 June,Freiburg (West Germany) to Mulhouse,74.5 km,Road stage",
"2,28 June,Mulhouse to Strasbourg,144.0 km,Road stage",
"3,29 June,Strasbourg to Nancy,165.6 km,Road stage",
"4,30 June,Nancy to Marche-en-Famenne (Belgium),242.0 km,Road stage",
"5,1 July,Dinant (Belgium) to Roubaix,208.5 km,Road stage",
"6a,2 July,Roubaix to Amiens,127.5 km,Road stage",
"6b,2 July,Amiens to Le Touquet,133.5 km,Road stage",
",3 July,Rest day,Le Touquet",
"7,4 July,Rungis to Nevers,257.5 km,Road stage",
"8,5 July,Nevers to Puy de Dôme,221.0 km,Road stage",
"9,6 July,Clermont-Ferrand to Saint-Étienne,153.0 km,Road stage",
"10,7 July,Saint-Étienne to Grenoble,188.5 km,Road stage",
"11,8 July,Grenoble to Orcières-Merlette,134.0 km,Road stage",
",9 July,Rest day,Orcières-Merlette",
"12,10 July,Orcières-Merlette to Marseille,251.0 km,Road stage",
"13,11 July,Albi,16.3 km,Road stage",
"14,12 July,Revel to Luchon,214.5 km,Road stage",
"15,13 July,Luchon to Superbagnères,19.6 km,Road stage",
"16a,14 July,Luchon to Gourette,145.0 km,Road stage",
"16b,14 July,Gourette to Pau,57.5 km,Road stage",
"17,15 July,Mont-de-Marsan to Bordeaux,188.0 km,Road stage",
"18,16 July,Bordeaux to Poitiers,244.0 km,Road stage",
"19,17 July,Blois to Versailles,244.0 km,Road stage",
"20,18 July,Versailles to Paris,53.8 km,Individual time trial",
];
let edition = tour_de_france_1971();
assert_eq!(edition.route(), route);
assert_eq!(edition.stage_summary(), "20 stages + Prologue including 3 split stages");
}
#[test]
fn test_tour_de_france_1972() {
let route = [
"P,1 July,Angers,7.2 km,Individual time trial",
"1,2 July,Angers to Saint-Brieuc,235.5 km,Road stage",
"2,3 July,Saint-Brieuc to La Baule,206.5 km,Road stage",
"3a,4 July,Pornichet to Saint-Jean-de-Monts,161.0 km,Road stage",
"3b,4 July,Merlin-Plage,16.2 km,Individual time trial",
"4,5 July,Merlin-Plage to Royan,236.0 km,Road stage",
"5a,6 July,Royan to Bordeaux,133.5 km,Road stage",
"5b,6 July,Bordeaux,12.7 km,Individual time trial",
"6,7 July,Bordeaux to Bayonne,205.0 km,Road stage",
",8 July,Rest day,Bayonne",
"7,9 July,Bayonne to Pau,220.5 km,Road stage",
"8,10 July,Pau to Luchon,163.5 km,Road stage",
"9,11 July,Luchon to Colomiers,179.0 km,Road stage",
"10,12 July,Castres to La Grande-Motte,210.0 km,Road stage",
"11,13 July,Carnon-Plage to Mont Ventoux,207.0 km,Road stage",
"12,14 July,Carpentras to Orcières-Merlette,192.0 km,Road stage",
",15 July,Rest day,Orcières-Merlette",
"13,16 July,Orcières-Merlette to Briançon,201.0 km,Road stage",
"14a,17 July,Briançon to Valloire,51.0 km,Road stage",
"14b,17 July,Valloire to Aix-les-Bains,151.0 km,Road stage",
"15,18 July,Aix-les-Bains to Le Revard,28.0 km,Road stage",
"16,19 July,Aix-les-Bains to Pontarlier,198.5 km,Road stage",
"17,20 July,Pontarlier to Ballon d'Alsace,213.0 km,Road stage",
"18,21 July,Vesoul to Auxerre,257.5 km,Road stage",
"19,22 July,Auxerre to Versailles,230.0 km,Road stage",
"20a,23 July,Versailles,42.0 km,Individual time trial",
"20b,23 July,Versailles to Paris,89.0 km,Road stage",
];
let edition = tour_de_france_1972();
assert_eq!(edition.route(), route);
assert_eq!(edition.stage_summary(), "20 stages + Prologue including 4 split stages");
}
#[test]
fn test_tour_de_france_1973() {
let route = [
"P,30 June,Scheveningen (Netherlands),7.1 km,Individual time trial",
"1a,1 July,Scheveningen (Netherlands) to Rotterdam (Netherlands),84.0 km,Road stage",
"1b,1 July,Rotterdam (Netherlands) to Sint-Niklaas (Belgium),137.5 km,Road stage",
"2a,2 July,Sint-Niklaas (Belgium),12.4 km,Team time trial",
"2b,2 July,Sint-Niklaas (Belgium) to Roubaix,138.0 km,Road stage",
"3,3 July,Roubaix to Reims,226.0 km,Road stage",
"4,4 July,Reims to Nancy,214.0 km,Road stage",
"5,5 July,Nancy to Mulhouse,188.0 km,Road stage",
"6,6 July,Mulhouse to Divonne-les-Bains,244.5 km,Road stage",
",7 July,Rest day,Divonne-les-Bains",
"7a,8 July,Divonne-les-Bains to Gaillard,86.5 km,Road stage",
"7b,8 July,Gaillard to Méribel-les-Allues,150.5 km,Road stage",
"8,9 July,Moûtiers to Les Orres,237.5 km,Road stage",
"9,10 July,Embrun to Nice,234.5 km,Road stage",
"10,11 July,Nice to Aubagne,222.5 km,Road stage",
"11,12 July,Montpellier to Argelès-sur-Mer,238.0 km,Road stage",
"12a,13 July,Perpignan to Thuir,28.3 km,Individual time trial",
"12b,13 July,Thuir to Pyrénées 2000,76.0 km,Road stage",
",14 July,Rest day,Pyrénées 2000",
"13,15 July,Bourg-Madame to Luchon,235.0 km,Road stage",
"14,16 July,Luchon to Pau,227.5 km,Road stage",
"15,17 July,Pau to Fleurance,137.0 km,Road stage",
"16a,18 July,Fleurance to Bordeaux,210.0 km,Road stage",
"16b,18 July,Bordeaux,12.4 km,Individual time trial",
"17,19 July,Sainte-Foy-la-Grande to Brive-la-Gaillarde,248.0 km,Road stage",
"18,20 July,Brive-la-Gaillarde to Puy de Dôme,216.5 km,Road stage",
"19,21 July,Bourges to Versailles,233.5 km,Road stage",
"20a,22 July,Versailles,16.0 km,Individual time trial",
"20b,22 July,Versailles to Paris,89.0 km,Road stage",
];
let edition = tour_de_france_1973();
assert_eq!(edition.route(), route);
assert_eq!(edition.stage_summary(), "20 stages + Prologue including 6 split stages");
}
#[test]
fn test_tour_de_france_1974() {
let route = [
"P,27 June,Brest,7.0 km,Individual time trial",
"1,28 June,Brest to Saint-Pol-de-Léon,144.0 km,Road stage",
"2,29 June,Plymouth (United Kingdom),164.0 km,Road stage",
"3,30 June,Morlaix to Saint-Malo,190.0 km,Road stage",
"4,1 July,Saint-Malo to Caen,184.0 km,Road stage",
"5,2 July,Caen to Dieppe,165.0 km,Road stage",
"6a,3 July,Dieppe to Harelbeke (Belgium),239.0 km,Road stage",
"6b,3 July,Harelbeke (Belgium),9.0 km,Team time trial",
"7,4 July,Mons (Belgium) to Châlons-sur-Marne,221.0 km,Road stage",
"8a,5 July,Châlons-sur-Marne to Chaumont,136.0 km,Road stage",
"8b,5 July,Chaumont to Besançon,152.0 km,Road stage",
"9,6 July,Besançon to Gaillard,241.0 km,Road stage",
"10,7 July,Gaillard to Aix-les-Bains,131.0 km,Road stage",
"11,8 July,Aix-les-Bains to Serre Chevalier,199.0 km,Road stage",
",9 July,Rest day,Aix-les-Bains",
"12,10 July,Savines-le-Lac to Orange,231.0 km,Road stage",
"13,11 July,Avignon to Montpellier,126.0 km,Road stage",
"14,12 July,Lodève to Colomiers,249.0 km,Road stage",
",13 July,Rest day,Colomiers",
"15,14 July,Colomiers to La Seu d'Urgell (Spain),225.0 km,Road stage",
"16,15 July,La Seu d'Urgell (Spain) to Saint-Lary-Soulan Pla d'Adet,209.0 km,Road stage",
"17,16 July,Saint-Lary-Soulan to La Mongie,119.0 km,Road stage",
"18,17 July,Bagnères-de-Bigorre to Pau,141.0 km,Road stage",
"19a,18 July,Pau to Bordeaux,196.0 km,Road stage",
"19b,18 July,Bordeaux,12.0 km,Individual time trial",
"20,19 July,Saint-Gilles-Croix-de-Vie to Nantes,120.0 km,Road stage",
"21a,20 July,Vouvray to Orléans,113.0 km,Road stage",
"21b,20 July,Orléans,37.0 km,Individual time trial",
"22,21 July,Orléans to Paris,146.0 km,Road stage",
];
let edition = tour_de_france_1974();
assert_eq!(edition.route(), route);
assert_eq!(edition.stage_summary(), "22 stages + Prologue including 4 split stages");
}
#[test]
fn test_tour_de_france_1975() {
let route = [
"P,26 June,Charleroi (Belgium),6.0 km,Individual time trial",
"1a,27 June,Charleroi (Belgium) to Molenbeek (Belgium),94.0 km,Road stage",
"1b,27 June,Molenbeek (Belgium) to Roubaix,109.0 km,Road stage",
"2,28 June,Roubaix to Amiens,121.0 km,Road stage",
"3,29 June,Amiens to Versailles,170.0 km,Road stage",
"4,30 June,Versailles to Le Mans,223.0 km,Road stage",
"5,1 July,Sablé-sur-Sarthe to Merlin-Plage,222.0 km,Road stage",
"6,2 July,Merlin-Plage,16.0 km,Individual time trial",
"7,3 July,Saint-Gilles-Croix-de-Vie to Angoulême,236.0 km,Road stage",
"8,4 July,Angoulême to Bordeaux,134.0 km,Road stage",
"9a,5 July,Langon to Fleurance,131.0 km,Road stage",
"9b,5 July,Fleurance to Auch,37.0 km,Individual time trial",
",6 July,Rest day,Auch",
"10,7 July,Auch to Pau,206.0 km,Road stage",
"11,8 July,Pau to Saint-Lary-Soulan Pla d'Adet,160.0 km,Road stage",
"12,9 July,Tarbes to Albi,242.0 km,Road stage",
"13,10 July,Albi to Le Lioran,260.0 km,Road stage",
"14,11 July,Aurillac to Puy de Dôme,174.0 km,Road stage",
",12 July,Rest day,Nice",
"15,13 July,Nice to Pra-Loup,217.0 km,Road stage",
"16,14 July,Barcelonnette to Serre Chevalier,107.0 km,Road stage",
"17,15 July,Valloire to Morzine-Avoriaz,225.0 km,Road stage",
"18,16 July,Morzine to Châtel,40.0 km,Individual time trial",
"19,17 July,Thonon-les-Bains to Chalon-sur-Saône,229.0 km,Road stage",
"20,18 July,Pouilly-en-Auxois to Melun,256.0 km,Road stage",
"21,19 July,Melun to Senlis,220.0 km,Road stage",
"22,20 July,Paris,164.0 km,Road stage",
];
let edition = tour_de_france_1975();
assert_eq!(edition.route(), route);
assert_eq!(edition.stage_summary(), "22 stages + Prologue including 2 split stages");
}
#[test]
fn test_tour_de_france_1976() {
let route = [
"P,24 June,Saint-Jean-de-Monts,8.0 km,Individual time trial",
"1,25 June,Saint-Jean-de-Monts to Angers,173.0 km,Road stage",
"2,26 June,Angers to Caen,237.0 km,Road stage",
"3,27 June,Le Touquet-Paris-Plage,37.0 km,Individual time trial",
"4,28 June,Le Touquet-Paris-Plage to Bornem (Belgium),258.0 km,Road stage",
"5a,29 June,Leuven (Belgium),4.0 km,Team time trial",
"5b,29 June,Leuven (Belgium) to Verviers (Belgium),144.0 km,Road stage",
"6,30 June,Bastogne (Belgium) to Nancy,209.0 km,Road stage",
"7,1 July,Nancy to Mulhouse,206.0 km,Road stage",
"8,2 July,Valentigney to Divonne-les-Bains,220.0 km,Road stage",
",3 July,Rest day,Divonne-les-Bains",
"9,4 July,Divonne-les-Bains to Alpe d'Huez,258.0 km,Road stage",
"10,5 July,Le Bourg-d'Oisans to Montgenèvre,166.0 km,Road stage",
"11,6 July,Montgenèvre to Manosque,224.0 km,Road stage",
",7 July,Rest day,Le Barcarès",
"12,8 July,Le Barcarès to Pyrénées 2000,205.0 km,Road stage",
"13,9 July,Pyrénées 2000 to Saint-Gaudens,188.0 km,Road stage",
"14,10 July,Saint-Gaudens to Saint-Lary-Soulan,139.0 km,Road stage",
"15,11 July,Saint-Lary-Soulan to Pau,195.0 km,Road stage",
"16,12 July,Pau to Fleurance,152.0 km,Road stage",
"17,13 July,Fleurance to Auch,39.0 km,Individual time trial",
"18a,14 July,Auch to Langon,86.0 km,Road stage",
"18b,14 July,Langon to Lacanau,123.0 km,Road stage",
"18c,14 July,Lacanau to Bordeaux,70.0 km,Road stage",
"19,15 July,Sainte-Foy-la-Grande to Tulle,220.0 km,Road stage",
"20,16 July,Tulle to Puy de Dôme,220.0 km,Road stage",
"21,17 July,Montargis to Versailles,145.0 km,Road stage",
"22a,18 July,Paris,6.0 km,Individual time trial",
"22b,18 July,Paris,91.0 km,Road stage",
];
let edition = tour_de_france_1976();
assert_eq!(edition.route(), route);
assert_eq!(edition.stage_summary(), "22 stages + Prologue including 3 split stages");
}
#[test]
fn test_tour_de_france_1977() {
let route = [
"P,30 June,Fleurance,5.0 km,Individual time trial",
"1,1 July,Fleurance to Auch,237.0 km,Road stage",
"2,2 July,Auch to Pau,253.0 km,Road stage",
"3,3 July,Oloron-Sainte-Marie to Vitoria-Gasteiz (Spain),248.0 km,Road stage",
"4,4 July,Vitoria-Gasteiz (Spain) to Seignosse le Penon,256.0 km,Road stage",
"5a,5 July,Morcenx to Bordeaux,139.0 km,Road stage",
"5b,5 July,Bordeaux,30.0 km,Individual time trial",
",6 July,Rest day,Bordeaux",
"6,7 July,Bordeaux to Limoges,225.0 km,Road stage",
"7a,8 July,Jaunay-Clan to Angers,140.0 km,Road stage",
"7b,8 July,Angers,4.0 km,Team time trial",
"8,9 July,Angers to Lorient,247.0 km,Road stage",
"9,10 July,Lorient to Rennes,187.0 km,Road stage",
"10,11 July,Bagnoles-de-l'Orne to Rouen,174.0 km,Road stage",
"11,12 July,Rouen to Roubaix,242.0 km,Road stage",
"12,13 July,Roubaix to Charleroi (Belgium),193.0 km,Road stage",
"13a,14 July,Freiburg (West Germany),46.0 km,Road stage",
"13b,14 July,Altkirch to Besançon,160.0 km,Road stage",
",15 July,Rest day,Freiburg (West Germany)",
"14,16 July,Besançon to Thonon-les-Bains,230.0 km,Road stage",
"15a,17 July,Thonon-les-Bains to Morzine,105.0 km,Road stage",
"15b,17 July,Morzine to Avoriaz,14.0 km,Individual time trial",
"16,18 July,Morzine to Chamonix,121.0 km,Road stage",
"17,19 July,Chamonix to Alpe d'Huez,185.0 km,Road stage",
"18,20 July,Rossignol Voiron to Saint-Étienne,199.0 km,Road stage",
"19,21 July,Saint-Trivier-sur-Moignans to Dijon,172.0 km,Road stage",
"20,22 July,Dijon,50.0 km,Individual time trial",
"21,23 July,Montereau-Fault-Yonne to Versailles,142.0 km,Road stage",
"22a,24 July,Paris,6.0 km,Individual time trial",
"22b,24 July,Paris,91.0 km,Road stage",
];
let edition = tour_de_france_1977();
assert_eq!(edition.route(), route);
assert_eq!(edition.stage_summary(), "22 stages + Prologue including 5 split stages");
}
#[test]
fn test_tour_de_france_1978() {
let route = [
"P,29 June,Leiden (Netherlands),5.0 km,Individual time trial",
"1a,30 June,Leiden (Netherlands) to Sint Willebrord (Netherlands),135.0 km,Road stage",
"1b,30 June,Sint Willebrord (Netherlands) to Brussels (Belgium),100.0 km,Road stage",
"2,1 July,Brussels (Belgium) to Saint-Amand-les-Eaux,199.0 km,Road stage",
"3,2 July,Saint-Amand-les-Eaux to Saint-Germain-en-Laye,244.0 km,Road stage",
"4,3 July,Evreux to Caen,153.0 km,Team time trial",
"5,4 July,Caen to Maze-Montgeoffroy,244.0 km,Road stage",
"6,5 July,Maze-Montgeoffroy to Poitiers,162.0 km,Road stage",
"7,6 July,Poitiers to Bordeaux,242.0 km,Road stage",
"8,7 July,Saint-Emilion to Sainte-Foy-la-Grande,59.0 km,Individual time trial",
"9,8 July,Bordeaux to Biarritz,233.0 km,Road stage",
",9 July,Rest day,Biarritz",
"10,10 July,Biarritz to Pau,192.0 km,Road stage",
"11,11 July,Pau to Saint-Lary-Soulan Pla d'Adet,161.0 km,Road stage",
"12a,12 July,Tarbes to Valence d'Agen,158.0 km,Road stage",
"12b,12 July,Valence d'Agen to Toulouse,96.0 km,Road stage",
"13,13 July,Figeac to Super Besse,221.0 km,Road stage",
"14,14 July,Besse-en-Chandesse to Puy de Dôme,52.0 km,Individual time trial",
"15,15 July,Saint-Dier-d'Auvergne to Saint-Étienne,196.0 km,Road stage",
"16,16 July,Saint-Étienne to Alpe d'Huez,241.0 km,Road stage",
",17 July,Rest day,Alpe d'Huez",
"17,18 July,Grenoble to Morzine,225.0 km,Road stage",
"18,19 July,Morzine to Lausanne (Switzerland),137.0 km,Road stage",
"19,20 July,Lausanne (Switzerland) to Belfort,182.0 km,Road stage",
"20,21 July,Metz to Nancy,72.0 km,Individual time trial",
"21,22 July,Epernay to Senlis,207.0 km,Road stage",
"22,23 July,Saint-Germain-en-Laye to Paris,162.0 km,Road stage",
];
let edition = tour_de_france_1978();
assert_eq!(edition.route(), route);
assert_eq!(edition.stage_summary(), "22 stages + Prologue including 2 split stages");
}
#[test]
fn test_tour_de_france_1979() {
let route = [
"P,27 June,Fleurance,5.0 km,Individual time trial",
"1,28 June,Fleurance to Luchon,225.0 km,Road stage",
"2,29 June,Luchon to Superbagnères,24.0 km,Individual time trial",
"3,30 June,Luchon to Pau,180.0 km,Road stage",
"4,1 July,Captieux to Bordeaux,87.0 km,Team time trial",
"5,2 July,Neuville-de-Poitou to Angers,145.0 km,Road stage",
"6,3 July,Angers to Saint-Brieuc,239.0 km,Road stage",
"7,4 July,Saint-Hilaire-du-Harcouët to Deauville,158.0 km,Road stage",
"8,5 July,Deauville to Le Havre,90.0 km,Team time trial",
"9,6 July,Amiens to Roubaix,201.0 km,Road stage",
"10,7 July,Roubaix to Brussels (Belgium),124.0 km,Road stage",
"11,8 July,Brussels (Belgium),33.0 km,Individual time trial",
"12,9 July,Rochefort (Belgium) to Metz,193.0 km,Road stage",
"13,10 July,Metz to Ballon d'Alsace,202.0 km,Road stage",
"14,11 July,Belfort to Evian-les-Bains,248.0 km,Road stage",
"15,12 July,Evian-les-Bains to Morzine-Avoriaz,54.0 km,Individual time trial",
"16,13 July,Morzine-Avoriaz to Les Menuires,201.0 km,Road stage",
",14 July,Rest day,Les Menuires",
"17,15 July,Les Menuires to Alpe d'Huez,167.0 km,Road stage",
"18,16 July,Alpe d'Huez,119.0 km,Road stage",
"19,17 July,Alpe d'Huez to Saint-Priest,162.0 km,Road stage",
"20,18 July,Saint-Priest to Dijon,240.0 km,Road stage",
"21,19 July,Dijon,49.0 km,Individual time trial",
"22,20 July,Dijon to Auxerre,189.0 km,Road stage",
"23,21 July,Auxerre to Nogent-sur-Marne,205.0 km,Road stage",
"24,22 July,Le Perreux-sur-Marne to Paris,180.0 km,Road stage",
];
let edition = tour_de_france_1979();
assert_eq!(edition.route(), route);
assert_eq!(edition.summit_finishes(), 4);
assert_eq!(edition.stage_summary(), "24 stages + Prologue");
}
#[test]
fn test_tour_de_france_1980() {
let route = [
"P,26 June,Frankfurt (West Germany),8.0 km,Individual time trial",
"1a,27 June,Frankfurt (West Germany) to Wiesbaden (West Germany),133.0 km,Road stage",
"1b,27 June,Wiesbaden (West Germany) to Frankfurt (West Germany),46.0 km,Team time trial",
"2,28 June,Frankfurt (West Germany) to Metz,276.0 km,Road stage",
"3,29 June,Metz to Liège (Belgium),282.0 km,Road stage",
"4,30 June,Spa (Belgium),35.0 km,Individual time trial",
"5,1 July,Liège (Belgium) to Lille,249.0 km,Road stage",
"6,2 July,Lille to Compiegne,216.0 km,Road stage",
"7a,3 July,Compiegne to Beauvais,65.0 km,Team time trial",
"7b,3 July,Beauvais to Rouen,92.0 km,Road stage",
"8,4 July,Flers to Saint-Malo,164.0 km,Road stage",
",5 July,Rest day,Saint-Malo",
"9,6 July,Saint-Malo to Nantes,205.0 km,Road stage",
"10,7 July,Rochefort to Bordeaux,163.0 km,Road stage",
"11,8 July,Damazan to Laplume,52.0 km,Individual time trial",
"12,9 July,Agen to Pau,194.0 km,Road stage",
"13,10 July,Pau to Bagnères-de-Luchon,200.0 km,Road stage",
"14,11 July,Lezignan-Corbieres to Montpellier,189.0 km,Road stage",
"15,12 July,Montpellier to Martigues,160.0 km,Road stage",
"16,13 July,Trets to Pra-Loup,209.0 km,Road stage",
"17,14 July,Serre Chevalier to Morzine,242.0 km,Road stage",
",15 July,Rest day,Morzine",
"18,16 July,Morzine to Prapoutel,199.0 km,Road stage",
"19,17 July,Voreppe to Saint-Étienne,140.0 km,Road stage",
"20,18 July,Saint-Étienne,34.0 km,Individual time trial",
"21,19 July,Auxerre to Fontenay-sous-Bois,208.0 km,Road stage",
"22,20 July,Fontenay-sous-Bois to Paris,186.0 km,Road stage",
];
let edition = tour_de_france_1980();
assert_eq!(edition.route(), route);
assert_eq!(edition.stage_summary(), "22 stages + Prologue including 2 split stages");
}
#[test]
fn test_tour_de_france_1981() {
let route = [
"P,25 June,Nice,6.0 km,Individual time trial",
"1a,26 June,Nice,97.0 km,Road stage",
"1b,26 June,Nice,40.0 km,Team time trial",
"2,27 June,Nice to Martigues,254.0 km,Road stage",
"3,28 June,Martigues to Narbonne,232.0 km,Road stage",
"4,29 June,Narbonne to Carcassonne,77.0 km,Team time trial",
"5,30 June,Saint-Gaudens to Pla d'Adet,117.0 km,Road stage",
"6,1 July,Nay to Pau,27.0 km,Individual time trial",
"7,2 July,Pau to Bordeaux,227.0 km,Road stage",
"8,3 July,Rochefort to Nantes,182.0 km,Road stage",
",4 July,Rest day,Nantes",
"9,5 July,Nantes to Le Mans,197.0 km,Road stage",
"10,6 July,Le Mans to Aulnay-sous-Bois,264.0 km,Road stage",
"11,7 July,Compiegne to Roubaix,246.0 km,Road stage",
"12a,8 July,Roubaix to Brussels (Belgium),107.0 km,Road stage",
"12b,8 July,Brussels (Belgium) to Circuit Zolder (Belgium),138.0 km,Road stage",
"13,9 July,Beringen (Belgium) to Hasselt (Belgium),157.0 km,Road stage",
"14,10 July,Mulhouse,38.0 km,Individual time trial",
"15,11 July,Besançon to Thonon-les-Bains,231.0 km,Road stage",
"16,12 July,Thonon-les-Bains to Morzine,200.0 km,Road stage",
",13 July,Rest day,Morzine",
"17,14 July,Morzine to Alpe d'Huez,230.0 km,Road stage",
"18,15 July,Le Bourg-d'Oisans to Le Pleynet,134.0 km,Road stage",
"19,16 July,Veurey to Saint-Priest,118.0 km,Road stage",
"20,17 July,Saint-Priest,46.0 km,Individual time trial",
"21,18 July,Auxerre to Fontenay-sous-Bois,207.0 km,Road stage",
"22,19 July,Fontenay-sous-Bois to Paris,187.0 km,Road stage",
];
let edition = tour_de_france_1981();
assert_eq!(edition.route(), route);
assert_eq!(edition.stage_summary(), "22 stages + Prologue including 2 split stages");
}
#[test]
fn test_tour_de_france_1982() {
let route = [
"P,2 July,Basel (Switzerland),7.0 km,Individual time trial",
"1,3 July,Basel (Switzerland) to Mohin (Switzerland),207.0 km,Road stage",
"2,4 July,Basel (Switzerland) to Nancy,250.0 km,Road stage",
"3,5 July,Nancy to Longwy,134.0 km,Road stage",
"4,6 July,Beauraing (Belgium) to Mouscron (Belgium),219.0 km,Road stage",
"5,7 July,Orchies to Fontaine-au-Pire,73.0 km,Team time trial",
"6,8 July,Lille,233.0 km,Road stage",
",9 July,Rest day,Lille",
"7,10 July,Cancale to Concarneau,235.0 km,Road stage",
"8,11 July,Concarneau to Châteaulin,201.0 km,Road stage",
"9a,12 July,Lorient to Plumelec,69.0 km,Team time trial",
"9b,12 July,Plumelec to Nantes,138.0 km,Road stage",
"10,13 July,Saintes to Bordeaux,147.0 km,Road stage",
"11,14 July,Valence d'Agen,57.0 km,Individual time trial",
"12,15 July,Fleurance to Pau,249.0 km,Road stage",
"13,16 July,Pau to Saint-Lary-Soulan Pla d'Adet,122.0 km,Road stage",
",17 July,Rest day,Martigues",
"14,18 July,Martigues,33.0 km,Individual time trial",
"15,19 July,Manosque to Orcières-Merlette,208.0 km,Road stage",
"16,20 July,Orcières-Merlette to Alpe d'Huez,123.0 km,Road stage",
"17,21 July,Le Bourg-d'Oisans to Morzine,251.0 km,Road stage",
"18,22 July,Morzine to Saint-Priest,233.0 km,Road stage",
"19,23 July,Saint-Priest,48.0 km,Individual time trial",
"20,24 July,Sens to Aulnay-sous-Bois,161.0 km,Road stage",
"21,25 July,Fontenay-sous-Bois to Paris,187.0 km,Road stage",
];
let edition = tour_de_france_1982();
assert_eq!(edition.route(), route);
assert_eq!(edition.stage_summary(), "21 stages + Prologue including 1 split stage");
}
#[test]
fn test_tour_de_france_1983() {
let route = [
"P,1 July,Fontenay-sous-Bois,6.0 km,Individual time trial",
"1,2 July,Nogent-sur-Marne to Creteil,163.0 km,Road stage",
"2,3 July,Soissons to Fontaine-au-Pire,100.0 km,Road stage",
"3,4 July,Valenciennes to Roubaix,152.0 km,Road stage",
"4,5 July,Roubaix to Le Havre,300.0 km,Road stage",
"5,6 July,Le Havre to Le Mans,257.0 km,Road stage",
"6,7 July,Chateaubriant to Nantes,58.0 km,Individual time trial",
"7,8 July,Nantes to Ile d'Oleron,216.0 km,Road stage",
"8,9 July,La Rochelle to Bordeaux,222.0 km,Road stage",
"9,10 July,Bordeaux to Pau,207.0 km,Road stage",
"10,11 July,Pau to Bagnères-de-Luchon,201.0 km,Road stage",
"11,12 July,Bagnères-de-Luchon to Fleurance,177.0 km,Road stage",
"12,13 July,Fleurance to Roquefort-sur-Soulzon,261.0 km,Road stage",
"13,14 July,Roquefort-sur-Soulzon to Aurillac,210.0 km,Road stage",
"14,15 July,Aurillac to Issoire,149.0 km,Road stage",
"15,16 July,Clermont-Ferrand to Puy de Dôme,16.0 km,Individual time trial",
"16,17 July,Issoire to Saint-Étienne,144.0 km,Road stage",
"17,18 July,La Tour-du-Pin to Alpe d'Huez,233.0 km,Road stage",
",19 July,Rest day,Alpe d'Huez",
"18,20 July,Le Bourg-d'Oisans to Morzine,247.0 km,Road stage",
"19,21 July,Morzine to Avoriaz,15.0 km,Individual time trial",
"20,22 July,Morzine to Dijon,291.0 km,Road stage",
"21,23 July,Dijon,50.0 km,Individual time trial",
"22,24 July,Alfortville to Paris,195.0 km,Road stage",
];
let edition = tour_de_france_1983();
assert_eq!(edition.route(), route);
assert_eq!(edition.stage_summary(), "22 stages + Prologue");
}
#[test]
fn test_tour_de_france_1984() {
let route = [
"P,29 June,Montreuil to Noisy-le-Sec,5.0 km,Individual time trial",
"1,30 June,Bondy to Saint-Denis,149.0 km,Road stage",
"2,1 July,Bobigny to Louvroil,249.0 km,Road stage",
"3a,2 July,Louvroil to Valenciennes,51.0 km,Team time trial",
"3b,2 July,Valenciennes to Bethune,83.0 km,Road stage",
"4,3 July,Bethune to Cergy-Pontoise,207.0 km,Road stage",
"5,4 July,Cergy-Pontoise to Alencon,202.0 km,Road stage",
"6,5 July,Alencon to Le Mans,67.0 km,Individual time trial",
"7,6 July,Le Mans to Nantes,192.0 km,Road stage",
"8,7 July,Nantes to Bordeaux,338.0 km,Road stage",
"9,8 July,Langon to Pau,198.0 km,Road stage",
"10,9 July,Pau to Guzet-Neige,227.0 km,Road stage",
"11,10 July,Saint-Girons to Blagnac,111.0 km,Road stage",
"12,11 July,Blagnac to Rodez,220.0 km,Road stage",
"13,12 July,Rodez to Domaine du Rouret,228.0 km,Road stage",
"14,13 July,Domaine du Rouret to Grenoble,241.0 km,Road stage",
",14 July,Rest day,Grenoble",
"15,15 July,Les Echelles to La Ruchère,22.0 km,Individual time trial",
"16,16 July,Grenoble to Alpe d'Huez,151.0 km,Road stage",
"17,17 July,Le Bourg-d'Oisans to La Plagne,185.0 km,Road stage",
"18,18 July,La Plagne to Morzine,186.0 km,Road stage",
"19,19 July,Morzine to Crans-Montana (Switzerland),141.0 km,Road stage",
"20,20 July,Crans-Montana (Switzerland) to Villefranche-sur-Saone,320.0 km,Road stage",
"21,21 July,Villié-Morgon to Villefranche-sur-Saone,51.0 km,Individual time trial",
"22,22 July,Pantin to Paris,197.0 km,Road stage",
];
let edition = tour_de_france_1984();
assert_eq!(edition.route(), route);
assert_eq!(edition.stage_summary(), "22 stages + Prologue including 1 split stage");
}
#[test]
fn test_tour_de_france_1985() {
let route = [
"P,28 June,Plumelec,6.0 km,Individual time trial",
"1,29 June,Vannes to Lanester,256.0 km,Road stage",
"2,30 June,Lorient to Vitre,242.0 km,Road stage",
"3,1 July,Vitre to Fougeres,242.0 km,Road stage",
"4,2 July,Fougeres to Pont-Audemer,239.0 km,Road stage",
"5,3 July,Neufchatel-en-Bray to Roubaix,224.0 km,Road stage",
"6,4 July,Roubaix to Reims,222.0 km,Road stage",
"7,5 July,Reims to Nancy,217.0 km,Road stage",
"8,6 July,Sarrebourg to Strasbourg,75.0 km,Individual time trial",
"9,7 July,Strasbourg to Epinal,174.0 km,Road stage",
"10,8 July,Epinal to Pontarlier,204.0 km,Road stage",
"11,9 July,Pontarlier to Morzine-Avoriaz,195.0 km,Road stage",
"12,10 July,Morzine-Avoriaz to Lans-en-Vercors,269.0 km,Road stage",
"13,11 July,Villard-de-Lans,32.0 km,Individual time trial",
",12 July,Rest day,Villard-de-Lans",
"14,13 July,Autrans to Saint-Étienne,179.0 km,Road stage",
"15,14 July,Saint-Étienne to Aurillac,238.0 km,Road stage",
"16,15 July,Aurillac to Toulouse,247.0 km,Road stage",
"17,16 July,Toulouse to Luz Ardiden,209.0 km,Road stage",
"18a,17 July,Luz-Saint-Sauveur to Aubisque,53.0 km,Road stage",
"18b,17 July,Laruns to Pau,83.0 km,Road stage",
"19,18 July,Pau to Bordeaux,203.0 km,Road stage",
"20,19 July,Montpon-Menesterol to Limoges,225.0 km,Road stage",
"21,20 July,Lac de Vassiviere,46.0 km,Individual time trial",
"22,21 July,Orléans to Paris,196.0 km,Road stage",
];
let edition = tour_de_france_1985();
assert_eq!(edition.route(), route);
assert_eq!(edition.stage_summary(), "22 stages + Prologue including 1 split stage");
}
#[test]
fn test_tour_de_france_1986() {
let route = [
"P,4 July,Boulogne-Billancourt,4.6 km,Individual time trial",
"1,5 July,Nanterre to Sceaux,85.0 km,Road stage",
"2,5 July,Meudon to Saint-Quentin-en-Yvelines,56.0 km,Team time trial",
"3,6 July,Levallois-Perret to Lievin,214.0 km,Road stage",
"4,7 July,Lievin to Evreux,243.0 km,Road stage",
"5,8 July,Evreux to Villers-sur-Mer,124.5 km,Road stage",
"6,9 July,Villers-sur-Mer to Cherbourg,200.0 km,Road stage",
"7,10 July,Cherbourg to Saint-Hilaire-du-Harcouët,201.0 km,Road stage",
"8,11 July,Saint-Hilaire-du-Harcouët to Nantes,204.0 km,Road stage",
"9,12 July,Nantes,61.5 km,Individual time trial",
"10,13 July,Nantes to Futuroscope,183.0 km,Road stage",
"11,14 July,Futuroscope to Bordeaux,258.3 km,Road stage",
"12,15 July,Bayonne to Pau,217.5 km,Road stage",
"13,16 July,Pau to Superbagnères,186.0 km,Road stage",
"14,17 July,Superbagnères to Blagnac,154.0 km,Road stage",
"15,18 July,Carcassonne to Nîmes,225.5 km,Road stage",
"16,19 July,Nîmes to Gap,246.5 km,Road stage",
"17,20 July,Gap to Serre Chevalier,190.0 km,Road stage",
"18,21 July,Briançon to Alpe d'Huez,162.5 km,Road stage",
",22 July,Rest day,Alpe d'Huez",
"19,23 July,Villard-de-Lans to Saint-Étienne,179.5 km,Road stage",
"20,24 July,Saint-Étienne,58.0 km,Individual time trial",
"21,25 July,Saint-Étienne to Puy de Dôme,190.0 km,Road stage",
"22,26 July,Clermont-Ferrand to Nevers,194.0 km,Road stage",
"23,27 July,Cosne-sur-Loire to Paris,255.0 km,Road stage",
];
let edition = tour_de_france_1986();
assert_eq!(edition.route(), route);
assert_eq!(edition.stage_summary(), "23 stages + Prologue");
}
#[test]
fn test_tour_de_france_1987() {
let route = [
"P,1 July,West Berlin (West Germany),6.0 km,Individual time trial",
"1,2 July,West Berlin (West Germany),105.0 km,Road stage",
"2,2 July,West Berlin (West Germany),40.5 km,Team time trial",
",3 July,Rest day",
"3,4 July,Karlsruhe (West Germany) to Stuttgart (West Germany),219.0 km,Road stage",
"4,5 July,Stuttgart (West Germany) to Pforzheim (West Germany),79.0 km,Road stage",
"5,5 July,Pforzheim (West Germany) to Strasbourg,112.5 km,Road stage",
"6,6 July,Strasbourg to Epinal,169.0 km,Road stage",
"7,7 July,Epinal to Troyes,211.0 km,Road stage",
"8,8 July,Troyes to Epnay-sous-Senart,205.5 km,Road stage",
"9,9 July,Orléans to Renaze,260.0 km,Road stage",
"10,10 July,Saumur to Futuroscope,87.5 km,Individual time trial",
"11,11 July,Poitiers to Chaumeil,255.0 km,Road stage",
"12,12 July,Brive to Bordeaux,228.0 km,Road stage",
"13,13 July,Bayonne to Pau,219.0 km,Road stage",
"14,14 July,Pau to Luz Ardiden,166.0 km,Road stage",
"15,15 July,Tarbes to Blagnac,164.0 km,Road stage",
"16,16 July,Blagnac to Millau,216.5 km,Road stage",
"17,17 July,Millau to Avignon,239.0 km,Road stage",
",18 July,Rest day,Avignon",
"18,19 July,Carpentras to Mont Ventoux,36.5 km,Individual time trial",
"19,20 July,Valreas to Villard-de-Lans,185.0 km,Road stage",
"20,21 July,Villard-de-Lans to Alpe d'Huez,201.0 km,Road stage",
"21,22 July,Le Bourg-d'Oisans to La Plagne,185.5 km,Road stage",
"22,23 July,La Plagne to Morzine,186.0 km,Road stage",
"23,24 July,Saint-Julien-en-Genevois to Dijon,224.5 km,Road stage",
"24,25 July,Dijon,38.0 km,Individual time trial",
"25,26 July,Creteil to Paris,192.0 km,Road stage",
];
let edition = tour_de_france_1987();
assert_eq!(edition.route(), route);
assert_eq!(edition.stage_summary(), "25 stages + Prologue");
}
#[test]
fn test_tour_de_france_1988() {
let route = [
"P,3 July,Pornichet to La Baule,1.0 km,Individual time trial",
"1,4 July,Pontchateau to Machecoul,91.5 km,Road stage",
"2,4 July,La Haie-Fouassiere to Ancenis,48.0 km,Team time trial",
"3,5 July,Nantes to Le Mans,213.5 km,Road stage",
"4,6 July,Le Mans to Evreux,158.0 km,Road stage",
"5,7 July,Neufchatel-en-Bray to Lievin,147.5 km,Road stage",
"6,8 July,Lievin to Wasquehal,52.0 km,Individual time trial",
"7,9 July,Wasquehal to Reims,225.5 km,Road stage",
"8,10 July,Reims to Nancy,219.0 km,Road stage",
"9,11 July,Nancy to Strasbourg,160.5 km,Road stage",
"10,12 July,Belfort to Besançon,149.5 km,Road stage",
"11,13 July,Besançon to Morzine,232.0 km,Road stage",
"12,14 July,Morzine to Alpe d'Huez,227.0 km,Road stage",
"13,15 July,Grenoble to Villard-de-Lans,38.0 km,Individual time trial",
",16 July,Rest day,Blagnac",
"14,17 July,Blagnac to Guzet-Neige,163.0 km,Road stage",
"15,18 July,Saint-Girons to Luz Ardiden,187.5 km,Road stage",
"16,19 July,Luz Ardiden to Pau,38.0 km,Road stage",
"17,19 July,Pau to Bordeaux,210.0 km,Road stage",
"18,20 July,Ruelle sur Tourve to Limoges,93.5 km,Road stage",
"19,21 July,Limoges to Puy de Dôme,188.0 km,Road stage",
"20,22 July,Clermont-Ferrand to Chalon-sur-Saône,233.5 km,Road stage",
"21,23 July,Santennay,48.0 km,Individual time trial",
"22,24 July,Nemours to Paris,172.5 km,Road stage",
];
let edition = tour_de_france_1988();
assert_eq!(edition.route(), route);
assert_eq!(edition.stage_summary(), "22 stages + Prologue");
}
#[test]
fn test_tour_de_france_1989() {
let route = [
"P,1 July,Luxembourg City (Luxembourg),7.8 km,Individual time trial",
"1,2 July,Luxembourg City (Luxembourg),135.5 km,Road stage",
"2,2 July,Luxembourg City (Luxembourg),46.0 km,Team time trial",
"3,3 July,Luxembourg City (Luxembourg) to Spa (Belgium),241.0 km,Road stage",
"4,4 July,Liège (Belgium) to Wasquehal,255.0 km,Road stage",
",5 July,Rest day,Dinard",
"5,6 July,Dinard to Rennes,73.0 km,Individual time trial",
"6,7 July,Rennes to Futuroscope,259.0 km,Road stage",
"7,8 July,Poitiers to Bordeaux,258.5 km,Road stage",
"8,9 July,Labastide-d'Armagnac to Pau,157.0 km,Road stage",
"9,10 July,Pau to Cauterets,147.0 km,Road stage",
"10,11 July,Cauterets to Superbagnères,136.0 km,Road stage",
"11,12 July,Luchon to Blagnac,158.5 km,Road stage",
"12,13 July,Toulouse to Montpellier,242.0 km,Road stage",
"13,14 July,Montpellier to Marseille,179.0 km,Road stage",
"14,15 July,Marseille to Gap,240.0 km,Road stage",
"15,16 July,Gap to Orcières-Merlette,39.0 km,Individual time trial",
",17 July,Rest day,Orcières-Merlette",
"16,18 July,Gap to Briançon,175.0 km,Road stage",
"17,19 July,Briançon to Alpe d'Huez,165.0 km,Road stage",
"18,20 July,Le Bourg-d'Oisans to Villard-de-Lans,91.5 km,Road stage",
"19,21 July,Villard-de-Lans to Aix-les-Bains,125.0 km,Road stage",
"20,22 July,Aix-les-Bains to L'Isle-d'Abeau,130.0 km,Road stage",
"21,23 July,Versailles to Paris,24.5 km,Individual time trial",
];
let edition = tour_de_france_1989();
assert_eq!(edition.route(), route);
assert_eq!(edition.stage_summary(), "21 stages + Prologue");
}
#[test]
fn test_tour_de_france_1990() {
let route = [
"P,30 June,Futuroscope,6.3 km,Individual time trial",
"1,1 July,Futuroscope,138.5 km,Road stage",
"2,1 July,Futuroscope,44.5 km,Team time trial",
"3,2 July,Poitiers to Nantes,233.0 km,Road stage",
"4,3 July,Nantes to Mont Saint-Michel,203.0 km,Road stage",
"5,4 July,Avranches to Rouen,301.0 km,Road stage",
",5 July,Rest day,Rouen",
"6,6 July,Sarrebourg to Vittel,202.5 km,Road stage",
"7,7 July,Vittel to Epinal,61.5 km,Individual time trial",
"8,8 July,Epinal to Besançon,181.5 km,Road stage",
"9,9 July,Besançon to Geneva (Switzerland),196.0 km,Road stage",
"10,10 July,Geneva (Switzerland) to Saint-Gervais,118.5 km,Road stage",
"11,11 July,Saint-Gervais to Alpe d'Huez,182.5 km,Road stage",
"12,12 July,Fontaine to Villard-de-Lans,33.5 km,Individual time trial",
",13 July,Rest day,Villard-de-Lans",
"13,14 July,Villard-de-Lans to Saint-Étienne,149.0 km,Road stage",
"14,15 July,Le Puy-en-Velay to Millau,205.0 km,Road stage",
"15,16 July,Millau to Revel,170.0 km,Road stage",
"16,17 July,Blagnac to Luz Ardiden,215.0 km,Road stage",
"17,18 July,Lourdes to Pau,150.0 km,Road stage",
"18,19 July,Pau to Bordeaux,202.0 km,Road stage",
"19,20 July,Castillon-la-Bataille to Limoges,182.5 km,Road stage",
"20,21 July,Lac de Vassiviere,45.5 km,Individual time trial",
"21,22 July,Bretigny-sur-Orge to Paris,182.5 km,Road stage",
];
let edition = tour_de_france_1990();
assert_eq!(edition.route(), route);
assert_eq!(edition.stage_summary(), "21 stages + Prologue");
}
#[test]
fn test_tour_de_france_1991() {
let route = [
"P,6 July,Lyon,5.4 km,Individual time trial",
"1,7 July,Lyon,114.5 km,Road stage",
"2,7 July,Bron to Chassieu,36.5 km,Team time trial",
"3,8 July,Villeurbanne to Dijon,210.5 km,Road stage",
"4,9 July,Dijon to Reims,286.0 km,Road stage",
"5,10 July,Reims to Valenciennes,149.5 km,Road stage",
"6,11 July,Arras to Le Havre,259.0 km,Road stage",
"7,12 July,Le Havre to Argentan,167.0 km,Road stage",
"8,13 July,Argentan to Alencon,73.0 km,Individual time trial",
"9,14 July,Alencon to Rennes,161.0 km,Road stage",
"10,15 July,Rennes to Quimper,207.5 km,Road stage",
"11,16 July,Quimper to Saint-Herblain,246.0 km,Road stage",
",17 July,Rest day,Pau",
"12,18 July,Pau to Jaca (Spain),192.0 km,Road stage",
"13,19 July,Jaca (Spain) to Val Louron,232.0 km,Road stage",
"14,20 July,Saint-Gaudens to Castres,172.5 km,Road stage",
"15,21 July,Albi to Ales,235.0 km,Road stage",
"16,22 July,Ales to Gap,215.0 km,Road stage",
"17,23 July,Gap to Alpe d'Huez,125.0 km,Road stage",
"18,24 July,Le Bourg-d'Oisans to Morzine,255.0 km,Road stage",
"19,25 July,Morzine to Aix-les-Bains,177.0 km,Road stage",
"20,26 July,Aix-les-Bains to Macon,166.0 km,Road stage",
"21,27 July,Lugny to Macon,57.0 km,Individual time trial",
"22,28 July,Melun to Paris,178.0 km,Road stage",
];
let edition = tour_de_france_1991();
assert_eq!(edition.route(), route);
assert_eq!(edition.stage_summary(), "22 stages + Prologue");
}
#[test]
fn test_tour_de_france_1992() {
let route = [
"P,4 July,San Sebastián (Spain),8.0 km,Individual time trial",
"1,5 July,San Sebastián (Spain),194.5 km,Road stage",
"2,6 July,San Sebastián (Spain) to Pau,255.0 km,Road stage",
"3,7 July,Pau to Bordeaux,210.0 km,Road stage",
"4,8 July,Libourne,63.5 km,Team time trial",
"5,9 July,Nogent-sur-Oise to Wasquehal,196.0 km,Road stage",
"6,10 July,Roubaix to Brussels (Belgium),167.0 km,Road stage",
"7,11 July,Brussels (Belgium) to Valkenburg (Netherlands),196.5 km,Road stage",
"8,12 July,Valkenburg (Netherlands) to Koblenz (Germany),206.5 km,Road stage",
"9,13 July,Luxembourg City (Luxembourg),65.0 km,Individual time trial",
"10,14 July,Luxembourg City (Luxembourg) to Strasbourg,217.0 km,Road stage",
"11,15 July,Strasbourg to Mulhouse,249.5 km,Road stage",
"12,16 July,Dole to Saint-Gervais,267.5 km,Road stage",
",17 July,Rest day,Dole",
"13,18 July,Saint-Gervais to Sestrière (Italy),254.5 km,Road stage",
"14,19 July,Sestrière (Italy) to Alpe d'Huez,186.5 km,Road stage",
"15,20 July,Le Bourg-d'Oisans to Saint-Étienne,198.0 km,Road stage",
"16,21 July,Saint-Étienne to La Bourboule,212.0 km,Road stage",
"17,22 July,La Bourboule to Montlucon,189.0 km,Road stage",
"18,23 July,Montlucon to Tours,212.0 km,Road stage",
"19,24 July,Tours to Blois,64.0 km,Individual time trial",
"20,25 July,Blois to Nanterre,222.0 km,Road stage",
"21,26 July,La Defense to Paris,141.0 km,Road stage",
];
let edition = tour_de_france_1992();
assert_eq!(edition.route(), route);
assert_eq!(edition.stage_summary(), "21 stages + Prologue");
}
#[test]
fn test_tour_de_france_1993() {
let route = [
"P,3 July,Le Puy du Fou,6.8 km,Individual time trial",
"1,4 July,Lucon to Les Sables-d'Olonne,215.0 km,Road stage",
"2,5 July,Les Sables-d'Olonne to Vannes,227.5 km,Road stage",
"3,6 July,Vannes to Dinard,189.5 km,Road stage",
"4,7 July,Dinard to Avranches,81.0 km,Team time trial",
"5,8 July,Avranches to Evreux,225.5 km,Road stage",
"6,9 July,Evreux to Amiens,158.0 km,Road stage",
"7,10 July,Peronne to Châlons-sur-Marne,199.0 km,Road stage",
"8,11 July,Châlons-sur-Marne to Verdun,184.5 km,Road stage",
"9,12 July,Lac de Madine,59.0 km,Individual time trial",
",13 July,Rest day,Villard-de-Lans",
"10,14 July,Villard-de-Lans to Serre Chevalier,203.0 km,Road stage",
"11,15 July,Serre Chevalier to Isola 2000,179.0 km,Road stage",
"12,16 July,Isola to Marseille,286.5 km,Road stage",
"13,17 July,Marseille to Montpellier,181.5 km,Road stage",
"14,18 July,Montpellier to Perpignan,223.0 km,Road stage",
"15,19 July,Perpignan to Pal (Andorra),231.5 km,Road stage",
",20 July,Rest day,Pal (Andorra)",
"16,21 July,Pal (Andorra) to Saint-Lary-Soulan Pla d'Adet,230.0 km,Road stage",
"17,22 July,Tarbes to Pau,190.0 km,Road stage",
"18,23 July,Orthez to Bordeaux,195.5 km,Road stage",
"19,24 July,Bretigny-sur-Orge to Montlhery,48.0 km,Individual time trial",
"20,25 July,Viry-Chatillon to Paris,196.5 km,Road stage",
];
let edition = tour_de_france_1993();
assert_eq!(edition.route(), route);
assert_eq!(edition.stage_summary(), "20 stages + Prologue");
}
#[test]
fn test_tour_de_france_1994() {
let route = [
"P,2 July,Lille,7.2 km,Individual time trial",
"1,3 July,Lille to Armentieres,234.0 km,Road stage",
"2,4 July,Roubaix to Boulogne-sur-Mer,203.5 km,Road stage",
"3,5 July,Calais to Eurotunnel,66.5 km,Team time trial",
"4,6 July,Dover (United Kingdom) to Brighton (United Kingdom),204.5 km,Road stage",
"5,7 July,Portsmouth (United Kingdom),187.0 km,Road stage",
"6,8 July,Cherbourg to Rennes,270.5 km,Road stage",
"7,9 July,Rennes to Futuroscope,259.5 km,Road stage",
"8,10 July,Poitiers to Trelissac,218.5 km,Road stage",
"9,11 July,Périgueux to Bergerac,64.0 km,Individual time trial",
"10,12 July,Bergerac to Cahors,160.5 km,Road stage",
"11,13 July,Cahors to Hautacam,263.5 km,Road stage",
",14 July,Rest day,Lourdes",
"12,15 July,Lourdes to Luz Ardiden,204.5 km,Road stage",
"13,16 July,Bagnères-de-Bigorre to Albi,223.0 km,Road stage",
"14,17 July,Castres to Montpellier,202.0 km,Road stage",
"15,18 July,Montpellier to Carpentras,231.0 km,Road stage",
"16,19 July,Valreas to Alpe d'Huez,224.5 km,Road stage",
"17,20 July,Le Bourg-d'Oisans to Val Thorens,149.0 km,Road stage",
"18,21 July,Moûtiers to Cluses,174.5 km,Road stage",
"19,22 July,Cluses to Avoriaz,47.5 km,Individual time trial",
"20,23 July,Morzine to Lac Saint-Point,208.5 km,Road stage",
"21,24 July,Disneyland Paris to Paris,175.0 km,Road stage",
];
let edition = tour_de_france_1994();
assert_eq!(edition.route(), route);
assert_eq!(edition.stage_summary(), "21 stages + Prologue");
}
#[test]
fn test_tour_de_france_1995() {
let route = [
"P,1 July,Saint-Brieuc,7.3 km,Individual time trial",
"1,2 July,Dinan to Lannion,233.5 km,Road stage",
"2,3 July,Perros-Guirec to Vitre,235.5 km,Road stage",
"3,4 July,Mayenne to Alencon,67.0 km,Team time trial",
"4,5 July,Alencon to Le Havre,162.0 km,Road stage",
"5,6 July,Fecamp to Dunkerque,261.0 km,Road stage",
"6,7 July,Dunkerque to Charleroi (Belgium),202.0 km,Road stage",
"7,8 July,Charleroi (Belgium) to Liège (Belgium),203.0 km,Road stage",
"8,9 July,Huy (Belgium) to Seraing (Belgium),54.0 km,Individual time trial",
",10 July,Rest day,Le Grand Bornand",
"9,11 July,Le Grand Bornand to La Plagne,160.0 km,Road stage",
"10,12 July,La Plagne to Alpe d'Huez,162.5 km,Road stage",
"11,13 July,Le Bourg-d'Oisans to Saint-Étienne,199.0 km,Road stage",
"12,14 July,Saint-Étienne to Mende,222.5 km,Road stage",
"13,15 July,Mende to Revel,245.0 km,Road stage",
"14,16 July,Saint-Orens-de-Gameville to Guzet-Neige,164.0 km,Road stage",
",17 July,Rest day,Saint-Girons",
"15,18 July,Saint-Girons to Cauterets,206.0 km,Road stage",
"16,19 July,Tarbes to Pau,149.0 km,Road stage",
"17,20 July,Pau to Bordeaux,246.0 km,Road stage",
"18,21 July,Montpon-Menesterol to Limoges,246.0 km,Road stage",
"19,22 July,Lac de Vassiviere,46.5 km,Individual time trial",
"20,23 July,Sainte-Genevieve-des-Bois to Paris,155.0 km,Road stage",
];
let edition = tour_de_france_1995();
assert_eq!(edition.route(), route);
assert_eq!(edition.stage_summary(), "20 stages + Prologue");
}
#[test]
fn test_tour_de_france_1996() {
let route = [
"P,29 June,'s-Hertogenbosch (Netherlands),9.4 km,Individual time trial",
"1,30 June,'s-Hertogenbosch (Netherlands),209.0 km,Road stage",
"2,1 July,'s-Hertogenbosch (Netherlands) to Wasquehal,247.5 km,Road stage",
"3,2 July,Wasquehal to Nogent-sur-Oise,195.0 km,Road stage",
"4,3 July,Soissons to Lac de Madine,232.0 km,Road stage",
"5,4 July,Lac de Madine to Besançon,242.0 km,Road stage",
"6,5 July,Arc-et-Senans to Aix-les-Bains,207.0 km,Road stage",
"7,6 July,Chambery to Les Arcs,200.0 km,Road stage",
"8,7 July,Bourg-Saint-Maurice to Val d'Isère,30.5 km,Individual time trial",
"9,8 July,Le Monetier-les-Bains to Sestrière (Italy),46.0 km,Road stage",
"10,9 July,Turin (Italy) to Gap,208.5 km,Road stage",
",10 July,Rest day,Gap",
"11,11 July,Gap to Valence,202.0 km,Road stage",
"12,12 July,Valence to Le Puy-en-Velay,143.5 km,Road stage",
"13,13 July,Le Puy-en-Velay to Super Besse,177.0 km,Road stage",
"14,14 July,Besse to Tulle,186.5 km,Road stage",
"15,15 July,Brive-la-Gaillarde to Villeneuve-sur-Lot,176.0 km,Road stage",
"16,16 July,Agen to Hautacam,199.0 km,Road stage",
"17,17 July,Argeles-Gazost to Pamplona (Spain),262.0 km,Road stage",
"18,18 July,Pamplona (Spain) to Hendaye,154.5 km,Road stage",
"19,19 July,Hendaye to Bordeaux,226.5 km,Road stage",
"20,20 July,Bordeaux to Saint-Emilion,63.5 km,Individual time trial",
"21,21 July,Palaiseau to Paris,147.5 km,Road stage",
];
let edition = tour_de_france_1996();
assert_eq!(edition.route(), route);
assert_eq!(edition.stage_summary(), "21 stages + Prologue");
}
#[test]
fn test_tour_de_france_1997() {
let route = [
"P,5 July,Rouen,7.3 km,Individual time trial",
"1,6 July,Rouen to Forges-les-Eaux,192.0 km,Road stage",
"2,7 July,Saint-Valery-en-Caux to Vire,262.0 km,Road stage",
"3,8 July,Vire to Plumelec,224.0 km,Road stage",
"4,9 July,Plumelec to Le Puy du Fou,223.0 km,Road stage",
"5,10 July,Chantonnay to La Chatre,261.5 km,Road stage",
"6,11 July,Le Blanc to Marennes,217.5 km,Road stage",
"7,12 July,Marennes to Bordeaux,194.0 km,Road stage",
"8,13 July,Sauternes to Pau,161.5 km,Road stage",
"9,14 July,Pau to Loudenvielle,182.0 km,Road stage",
"10,15 July,Luchon to Andorra-Arcalis (Andorra),182.0 km,Road stage",
"11,16 July,Andorra-Arcalis (Andorra) to Perpignan,192.0 km,Road stage",
",17 July,Rest day,Saint-Étienne",
"12,18 July,Saint-Étienne,55.0 km,Individual time trial",
"13,19 July,Saint-Étienne to Alpe d'Huez,203.5 km,Road stage",
"14,20 July,Le Bourg-d'Oisans to Courchevel,148.0 km,Road stage",
"15,21 July,Courchevel to Morzine,208.5 km,Road stage",
"16,22 July,Morzine to Fribourg (Switzerland),181.0 km,Road stage",
"17,23 July,Fribourg (Switzerland) to Colmar,218.5 km,Road stage",
"18,24 July,Colmar to Montbeliard,175.5 km,Road stage",
"19,25 July,Montbeliard to Dijon,172.0 km,Road stage",
"20,26 July,Disneyland Paris,63.0 km,Individual time trial",
"21,27 July,Disneyland Paris to Paris,149.5 km,Road stage",
];
let edition = tour_de_france_1997();
assert_eq!(edition.route(), route);
assert_eq!(edition.stage_summary(), "21 stages + Prologue");
}
#[test]
fn test_tour_de_france_1998() {
let route = [
"P,11 July,Dublin (Ireland),5.6 km,Individual time trial",
"1,12 July,Dublin (Ireland),180.5 km,Road stage",
"2,13 July,Enniscorthy (Ireland) to Cork (Ireland),205.5 km,Road stage",
"3,14 July,Roscoff to Lorient,169.0 km,Road stage",
"4,15 July,Plouay to Cholet,252.0 km,Road stage",
"5,16 July,Cholet to Chateauroux,228.5 km,Road stage",
"6,17 July,La Chatre to Brive-la-Gaillarde,204.5 km,Road stage",
"7,18 July,Meyrignac-l'Eglise to Correze,58.0 km,Individual time trial",
"8,19 July,Brive-la-Gaillarde to Montauban,190.5 km,Road stage",
"9,20 July,Montauban to Pau,210.0 km,Road stage",
"10,21 July,Pau to Luchon,196.5 km,Road stage",
"11,22 July,Luchon to Plateau de Beille,170.0 km,Road stage",
",23 July,Rest day,Ariege",
"12,24 July,Tarascon-sur-Ariege to Cap d'Agde,222.0 km,Road stage",
"13,25 July,Frontignan la Peyrade to Carpentras,196.0 km,Road stage",
"14,26 July,Valreas to Grenoble,186.5 km,Road stage",
"15,27 July,Grenoble to Les Deux Alpes,189.0 km,Road stage",
"16,28 July,Vizelle to Albertville,204.0 km,Road stage",
"17,29 July,Albertville to Aix-les-Bains,149.0 km,Road stage",
"18,30 July,Aix-les-Bains to Neuchatel (Switzerland),218.5 km,Road stage",
"19,31 July,La Chaux-de-Fonds (Switzerland) to Autun,242.0 km,Road stage",
"20,1 August,Montceau-les-Mines to Le Creusot,52.0 km,Individual time trial",
"21,2 August,Melun to Paris,147.5 km,Road stage",
];
let edition = tour_de_france_1998();
assert_eq!(edition.route(), route);
assert_eq!(edition.stage_summary(), "21 stages + Prologue");
}
#[test]
fn test_tour_de_france_1999() {
let route = [
"P,3 July,Le Puy du Fou,6.8 km,Individual time trial",
"1,4 July,Montaigu to Challans,208.0 km,Road stage",
"2,5 July,Challans to Saint-Nazaire,176.0 km,Road stage",
"3,6 July,Nantes to Laval,194.5 km,Road stage",
"4,7 July,Laval to Blois,194.5 km,Road stage",
"5,8 July,Bonneval to Amiens,233.5 km,Road stage",
"6,9 July,Amiens to Mauberge,171.5 km,Road stage",
"7,10 July,Avesnes-sur-Helpe to Thionville,227.0 km,Road stage",
"8,11 July,Metz,56.5 km,Individual time trial",
",12 July,Rest day,Le Grand Bornand",
"9,13 July,Le Grand Bornand to Sestrière (Italy),213.5 km,Road stage",
"10,14 July,Sestrière (Italy) to Alpe d'Huez,220.5 km,Road stage",
"11,15 July,Le Bourg-d'Oisans to Saint-Étienne,198.5 km,Road stage",
"12,16 July,Saint Galmier to Saint-Flour,201.5 km,Road stage",
"13,17 July,Saint-Flour to Albi,236.5 km,Road stage",
"14,18 July,Castres to Saint-Gaudens,199.0 km,Road stage",
",19 July,Rest day,Saint-Gaudens",
"15,20 July,Saint-Gaudens to Piau-Engaly,173.0 km,Road stage",
"16,21 July,Lannemezan to Pau,192.0 km,Road stage",
"17,22 July,Mourenx to Bordeaux,200.0 km,Road stage",
"18,23 July,Jonzac to Futuroscope,187.5 km,Road stage",
"19,24 July,Futuroscope,57.0 km,Individual time trial",
"20,25 July,Arpajon to Paris,143.5 km,Road stage",
];
let edition = tour_de_france_1999();
assert_eq!(edition.route(), route);
assert_eq!(edition.stage_summary(), "20 stages + Prologue");
}
#[test]
fn test_tour_de_france_2000() {
let route = [
"1,1 July,Futuroscope,16.5 km,Individual time trial",
"2,2 July,Futuroscope to Loudon,194.0 km,Road stage",
"3,3 July,Loudon to Nantes,161.5 km,Road stage",
"4,4 July,Nantes to Saint-Nazaire,70.0 km,Team time trial",
"5,5 July,Vannes to Vitre,202.0 km,Road stage",
"6,6 July,Vitre to Tours,198.5 km,Road stage",
"7,7 July,Tours to Limoges,205.5 km,Road stage",
"8,8 July,Limoges to Villeneuve-sur-Lot,203.5 km,Road stage",
"9,9 July,Agen to Dax,181.0 km,Road stage",
"10,10 July,Dax to Hautacam,205.0 km,Road stage",
"11,11 July,Bagnères-de-Bigorre to Revel,218.5 km,Road stage",
",12 July,Rest day,Provence",
"12,13 July,Carpentras to Mont Ventoux,149.0 km,Road stage",
"13,14 July,Avignon to Draguignan,185.5 km,Road stage",
"14,15 July,Draguignan to Briançon,249.5 km,Road stage",
"15,16 July,Briançon to Courchevel,173.5 km,Road stage",
",17 July,Rest day,Courchevel",
"16,18 July,Courchevel to Morzine,196.5 km,Road stage",
"17,19 July,Evian-les-Bains to Lausanne (Switzerland),155.0 km,Road stage",
"18,20 July,Lausanne (Switzerland) to Freiburg (Germany),246.5 km,Road stage",
"19,21 July,Freiburg (Germany) to Mulhouse,58.5 km,Individual time trial",
"20,22 July,Belfort to Troyes,254.5 km,Road stage",
"21,23 July,Paris,138.0 km,Road stage",
];
let edition = tour_de_france_2000();
assert_eq!(edition.route(), route);
assert_eq!(edition.stage_summary(), "21 stages");
}
#[test]
fn test_tour_de_france_2001() {
let route = [
"P,7 July,Dunkerque,8.2 km,Individual time trial",
"1,8 July,Saint-Omer to Boulogne-sur-Mer,194.5 km,Road stage",
"2,9 July,Calais to Antwerp (Belgium),220.5 km,Road stage",
"3,10 July,Antwerp (Belgium) to Seraing (Belgium),198.5 km,Road stage",
"4,11 July,Huy (Belgium) to Verdun,215.0 km,Road stage",
"5,12 July,Verdun to Bar-le-Duc,67.0 km,Team time trial",
"6,13 July,Commercy to Strasbourg,211.5 km,Road stage",
"7,14 July,Strasbourg to Colmar,162.5 km,Road stage",
"8,15 July,Colmar to Pontarlier,222.5 km,Road stage",
"9,16 July,Pontarlier to Aix-les-Bains,185.0 km,Road stage",
"10,17 July,Aix-les-Bains to Alpe d'Huez,209.0 km,Road stage",
"11,18 July,Grenoble to Chamrousse,32.0 km,Individual time trial",
",19 July,Rest day,Perpignan",
"12,20 July,Perpignan to Plateau de Bonascre,165.5 km,Road stage",
"13,21 July,Foix to Saint-Lary-Soulan Pla d'Adet,194.0 km,Road stage",
"14,22 July,Tarbes to Luz Ardiden,141.5 km,Road stage",
",23 July,Rest day,Pau",
"15,24 July,Pau to Lavaur,232.5 km,Road stage",
"16,25 July,Castelsarrasin to Sarran,229.5 km,Road stage",
"17,26 July,Brive-la-Gaillarde to Montlucon,194.0 km,Road stage",
"18,27 July,Montlucon to Saint-Amand-Montrond,61.0 km,Individual time trial",
"19,28 July,Orléans to Evry,149.5 km,Road stage",
"20,29 July,Corbeil-Essonnes to Paris,160.5 km,Road stage",
];
let edition = tour_de_france_2001();
assert_eq!(edition.route(), route);
assert_eq!(edition.stage_summary(), "20 stages + Prologue");
}
#[test]
fn test_tour_de_france_2002() {
let route = [
"P,6 July,Luxembourg City (Luxembourg),7.0 km,Individual time trial",
"1,7 July,Luxembourg City (Luxembourg),192.5 km,Road stage",
"2,8 July,Luxembourg City (Luxembourg) to Saarbrücken (Germany),181.0 km,Road stage",
"3,9 July,Metz to Reims,174.5 km,Road stage",
"4,10 July,Epernay to Chateau-Thierry,67.5 km,Team time trial",
"5,11 July,Soissons to Rouen,195.0 km,Road stage",
"6,12 July,Forges-les-Eaux to Alencon,199.5 km,Road stage",
"7,13 July,Bagnoles-de-l'Orne to Avranches,176.0 km,Road stage",
"8,14 July,Saint-Martin-de-Landelles to Plouay,217.5 km,Road stage",
"9,15 July,Lanester to Lorient,52.0 km,Individual time trial",
",16 July,Rest day,Bordeaux",
"10,17 July,Bazas to Pau,147.0 km,Road stage",
"11,18 July,Pau to La Mongie,158.0 km,Road stage",
"12,19 July,Lannemezan to Plateau de Beille,199.5 km,Road stage",
"13,20 July,Lavelanet to Beziers,171.0 km,Road stage",
"14,21 July,Lodève to Mont Ventoux,221.0 km,Road stage",
",22 July,Rest day,Vaucluse",
"15,23 July,Vaison-la-Romaine to Les Deux Alpes,226.5 km,Road stage",
"16,24 July,Les Deux Alpes to La Plagne,179.5 km,Road stage",
"17,25 July,Aime to Cluses,142.0 km,Road stage",
"18,26 July,Cluses to Bourg-en-Bresse,176.5 km,Road stage",
"19,27 July,Regnie-Durette to Macon,50.0 km,Individual time trial",
"20,28 July,Melun to Paris,144.0 km,Road stage",
];
let edition = tour_de_france_2002();
assert_eq!(edition.route(), route);
assert_eq!(edition.stage_summary(), "20 stages + Prologue");
}
#[test]
fn test_tour_de_france_2003() {
let route = [
"P,5 July,Paris,6.5 km,Individual time trial",
"1,6 July,Saint-Denis to Meaux,168.0 km,Road stage",
"2,7 July,La Ferte-sous-Jouarre to Sedan,204.5 km,Road stage",
"3,8 July,Charleville-Mezieres to Saint-Dizier,167.5 km,Road stage",
"4,9 July,Joinville to Saint-Dizier,69.0 km,Team time trial",
"5,10 July,Troyes to Nevers,196.5 km,Road stage",
"6,11 July,Nevers to Lyon,230.0 km,Road stage",
"7,12 July,Lyon to Morzine,230.5 km,Road stage",
"8,13 July,Sallanches to Alpe d'Huez,219.0 km,Road stage",
"9,14 July,Le Bourg-d'Oisans to Gap,184.5 km,Road stage",
"10,15 July,Gap to Marseille,219.5 km,Road stage",
",16 July,Rest day,Narbonne",
"11,17 July,Narbonne to Toulouse,153.5 km,Road stage",
"12,18 July,Gaillac to Cap Decouverte,47.0 km,Individual time trial",
"13,19 July,Toulouse to Ax 3 Domaines,197.5 km,Road stage",
"14,20 July,Saint-Girons to Loudenvielle,191.5 km,Road stage",
"15,21 July,Bagnères-de-Bigorre to Luz Ardiden,159.5 km,Road stage",
",22 July,Rest day,Pau",
"16,23 July,Pau to Bayonne,197.5 km,Road stage",
"17,24 July,Dax to Bordeaux,181.0 km,Road stage",
"18,25 July,Bordeaux to Saint-Maixent-l'Ecole,203.5 km,Road stage",
"19,26 July,Pornic to Nantes,49.0 km,Individual time trial",
"20,27 July,Ville-d'Avray to Paris,152.0 km,Road stage",
];
let edition = tour_de_france_2003();
assert_eq!(edition.route(), route);
assert_eq!(edition.stage_summary(), "20 stages + Prologue");
}
#[test]
fn test_tour_de_france_2004() {
let route = [
"P,3 July,Liège (Belgium),6.1 km,Individual time trial",
"1,4 July,Liège (Belgium) to Charleroi (Belgium),202.5 km,Road stage",
"2,5 July,Charleroi (Belgium) to Namur (Belgium),197.0 km,Road stage",
"3,6 July,Waterloo (Belgium) to Wasquehal,210.0 km,Road stage",
"4,7 July,Cambrai to Arras,64.5 km,Team time trial",
"5,8 July,Amiens to Chartres,200.5 km,Road stage",
"6,9 July,Bonneval to Angers,196.0 km,Road stage",
"7,10 July,Chateaubriant to Saint-Brieuc,204.5 km,Road stage",
"8,11 July,Lamballe to Quimper,168.0 km,Road stage",
",12 July,Rest day,Limoges",
"9,13 July,Saint-Leonard-de-Noblat to Gueret,160.5 km,Road stage",
"10,14 July,Limoges to Saint-Flour,237.0 km,Road stage",
"11,15 July,Saint-Flour to Figeac,164.0 km,Road stage",
"12,16 July,Castelsarrasin to La Mongie,197.5 km,Road stage",
"13,17 July,Lannemezan to Plateau de Beille,205.5 km,Road stage",
"14,18 July,Carcassonne to Nîmes,192.5 km,Road stage",
",19 July,Rest day,Nîmes",
"15,20 July,Valreas to Villard-de-Lans,180.5 km,Road stage",
"16,21 July,Le Bourg-d'Oisans to Alpe d'Huez,15.5 km,Individual time trial",
"17,22 July,Le Bourg-d'Oisans to Le Grand Bornand,204.5 km,Road stage",
"18,23 July,Annemasse to Lons-le-Saunier,166.5 km,Road stage",
"19,24 July,Besançon,55.0 km,Individual time trial",
"20,25 July,Montereau-Fault-Yonne to Paris,163.0 km,Road stage",
];
let edition = tour_de_france_2004();
assert_eq!(edition.route(), route);
assert_eq!(edition.stage_summary(), "20 stages + Prologue");
}
#[test]
fn test_tour_de_france_2005() {
let route = [
"1,2 July,Fromentine to Noirmoutier-en-l'Île,19.0 km,Individual time trial",
"2,3 July,Challans to Les Essarts,181.5 km,Road stage",
"3,4 July,La Chataigneraie to Tours,212.5 km,Road stage",
"4,5 July,Tours to Blois,67.5 km,Team time trial",
"5,6 July,Chambord to Montargis,183.0 km,Road stage",
"6,7 July,Troyes to Nancy,199.0 km,Road stage",
"7,8 July,Luneville to Karlsruhe (Germany),228.5 km,Road stage",
"8,9 July,Pforzheim (Germany) to Gerardmer,231.5 km,Road stage",
"9,10 July,Gerardmer to Mulhouse,171.0 km,Road stage",
"10,11 July,Grenoble to Courchevel,177.0 km,Road stage",
",12 July,Rest day,Grenoble",
"11,13 July,Courchevel to Briançon,173.0 km,Road stage",
"12,14 July,Briançon to Digne-les-Bains,187.0 km,Road stage",
"13,15 July,Miramas to Montpellier,173.5 km,Road stage",
"14,16 July,Agde to Ax 3 Domaines,220.5 km,Road stage",
"15,17 July,Lezat-sur-Leze to Saint-Lary-Soulan Pla d'Adet,205.5 km,Road stage",
"16,18 July,Mourenx to Pau,180.5 km,Road stage",
",19 July,Rest day,Pau",
"17,20 July,Pau to Revel,239.5 km,Road stage",
"18,21 July,Albi to Mende,189.0 km,Road stage",
"19,22 July,Issoire to Le Puy-en-Velay,153.5 km,Road stage",
"20,23 July,Saint-Étienne,55.5 km,Individual time trial",
"21,24 July,Corbeil-Essonnes to Paris,144.5 km,Road stage",
];
let edition = tour_de_france_2005();
assert_eq!(edition.route(), route);
assert_eq!(edition.stage_summary(), "21 stages");
}
#[test]
fn test_tour_de_france_2006() {
let route = [
"P,1 July,Strasbourg,7.1 km,Individual time trial",
"1,2 July,Strasbourg,184.5 km,Road stage",
"2,3 July,Obernai to Esch-sur-Alzette (Luxembourg),228.5 km,Road stage",
"3,4 July,Esch-sur-Alzette (Luxembourg) to Valkenburg (Netherlands),216.5 km,Road stage",
"4,5 July,Huy (Belgium) to Saint-Quentin,207.0 km,Road stage",
"5,6 July,Beauvais to Caen,225.0 km,Road stage",
"6,7 July,Lisieux to Vitre,189.0 km,Road stage",
"7,8 July,Saint Gregoire to Rennes,52.0 km,Individual time trial",
"8,9 July,Saint-Meen-le-Grand to Lorient,181.0 km,Road stage",
",10 July,Rest day,Bordeaux",
"9,11 July,Bordeaux to Dax,169.5 km,Road stage",
"10,12 July,Cambo-les-Bains to Pau,190.5 km,Road stage",
"11,13 July,Tarbes to Val d'Aran/Pla-de-Beret,206.5 km,Road stage",
"12,14 July,Luchon to Carcassonne,211.5 km,Road stage",
"13,15 July,Beziers to Montelimar,230.0 km,Road stage",
"14,16 July,Montelimar to Gap,180.5 km,Road stage",
",17 July,Rest day,Gap",
"15,18 July,Gap to Alpe d'Huez,187.0 km,Road stage",
"16,19 July,Le Bourg-d'Oisans to La Toussuire,182.0 km,Road stage",
"17,20 July,Saint-Jean-de-Maurienne to Morzine,200.5 km,Road stage",
"18,21 July,Morzine to Macon,197.0 km,Road stage",
"19,22 July,Le Creusot to Montceau-les-Mines,57.0 km,Individual time trial",
"20,23 July,Antony/Parc de Sceaux to Paris,154.5 km,Road stage",
];
let edition = tour_de_france_2006();
assert_eq!(edition.route(), route);
assert_eq!(edition.stage_summary(), "20 stages + Prologue");
}
#[test]
fn test_tour_de_france_2007() {
let route = [
"P,7 July,London (United Kingdom),7.9 km,Individual time trial",
"1,8 July,London (United Kingdom) to Canterbury (United Kingdom),203.0 km,Road stage",
"2,9 July,Dunkerque to Ghent (Belgium),168.5 km,Road stage",
"3,10 July,Waregem (Belgium) to Compiegne,236.5 km,Road stage",
"4,11 July,Villers-Cotterets to Joigny,193.0 km,Road stage",
"5,12 July,Chablis to Autun,182.5 km,Road stage",
"6,13 July,Semur-en-Auxois to Bourg-en-Bresse,199.5 km,Road stage",
"7,14 July,Bourg-en-Bresse to Le Grand Bornand,197.5 km,Road stage",
"8,15 July,Le Grand Bornand to Tignes,165.0 km,Road stage",
",16 July,Rest day,Tignes",
"9,17 July,Val d'Isère to Briançon,159.5 km,Road stage",
"10,18 July,Tallard to Marseille,229.5 km,Road stage",
"11,19 July,Marseille to Montpellier,182.5 km,Road stage",
"12,20 July,Montpellier to Castres,178.5 km,Road stage",
"13,21 July,Albi,54.0 km,Individual time trial",
"14,22 July,Mazamet to Plateau de Beille,197.0 km,Road stage",
"15,23 July,Foix to Loudenvielle,196.0 km,Road stage",
",24 July,Rest day,Pau",
"16,25 July,Orthez to Gourette-Col d'Aubisque,218.5 km,Road stage",
"17,26 July,Pau to Castelsarrasin,188.5 km,Road stage",
"18,27 July,Cahors to Angoulême,211.0 km,Road stage",
"19,28 July,Cognac to Angoulême,55.5 km,Individual time trial",
"20,29 July,Marcoussis to Paris,146.0 km,Road stage",
];
let edition = tour_de_france_2007();
assert_eq!(edition.route(), route);
assert_eq!(edition.stage_summary(), "20 stages + Prologue");
}
#[test]
fn test_tour_de_france_2008() {
let route = [
"1,5 July,Brest to Plumelec,197.5 km,Road stage",
"2,6 July,Aulay to Saint-Brieuc,164.5 km,Road stage",
"3,7 July,Saint-Malo to Nantes,208.0 km,Road stage",
"4,8 July,Cholet,29.5 km,Individual time trial",
"5,9 July,Cholet to Chateauroux,232.0 km,Road stage",
"6,10 July,Aigurande to Super Besse,195.0 km,Road stage",
"7,11 July,Brioude to Aurillac,159.0 km,Road stage",
"8,12 July,Figeac to Toulouse,172.5 km,Road stage",
"9,13 July,Toulouse to Bagnères-de-Bigorre,224.0 km,Road stage",
"10,14 July,Pau to Hautacam,156.0 km,Road stage",
",15 July,Rest day,Pau",
"11,16 July,Lannemezan to Foix,167.5 km,Road stage",
"12,17 July,Lavalanet to Narbonne,168.5 km,Road stage",
"13,18 July,Narbonne to Nîmes,182.0 km,Road stage",
"14,19 July,Nîmes to Digne-les-Bains,194.5 km,Road stage",
"15,20 July,Embrun to Prato Nevoso (Italy),183.0 km,Road stage",
",21 July,Rest day,Cuneo (Italy)",
"16,22 July,Cuneo (Italy) to Jausiers,157.0 km,Road stage",
"17,23 July,Embrun to Alpe d'Huez,210.5 km,Road stage",
"18,24 July,Le Bourg-d'Oisans to Saint-Étienne,196.5 km,Road stage",
"19,25 July,Roanne to Montlucon,165.5 km,Road stage",
"20,26 July,Cerilly to Saint-Amand-Montrond,53.0 km,Individual time trial",
"21,27 July,Etampes to Paris,143.0 km,Road stage",
];
let edition = tour_de_france_2008();
assert_eq!(edition.route(), route);
assert_eq!(edition.stage_summary(), "21 stages");
}
#[test]
fn test_tour_de_france_2009() {
let route = [
"1,4 July,Monaco (Monaco),15.5 km,Individual time trial",
"2,5 July,Monaco (Monaco) to Brignoles,187.0 km,Road stage",
"3,6 July,Marseille to La Grande-Motte,196.5 km,Road stage",
"4,7 July,Montpellier,39.0 km,Team time trial",
"5,8 July,Cap d'Agde to Perpignan,196.5 km,Road stage",
"6,9 July,Girona (Spain) to Barcelona (Spain),181.5 km,Road stage",
"7,10 July,Barcelona (Spain) to Andorra-Arcalis (Andorra),224.0 km,Road stage",
"8,11 July,Andorra la Vella (Andorra) to Saint-Girons,176.5 km,Road stage",
"9,12 July,Saint-Girons to Tarbes,160.5 km,Road stage",
",13 July,Rest day,Limoges",
"10,14 July,Limoges to Issoudun,194.5 km,Road stage",
"11,15 July,Vatan to Saint-Fargeau,192.0 km,Road stage",
"12,16 July,Tonnerre to Vittel,211.5 km,Road stage",
"13,17 July,Vittel to Colmar,200.0 km,Road stage",
"14,18 July,Colmar to Besançon,199.0 km,Road stage",
"15,19 July,Pontarlier to Verbier (Switzerland),207.5 km,Road stage",
",20 July,Rest day,Verbier (Switzerland)",
"16,21 July,Martigny (Switzerland) to Bourg-Saint-Maurice,159.0 km,Road stage",
"17,22 July,Bourg-Saint-Maurice to Le Grand Bornand,169.5 km,Road stage",
"18,23 July,Annecy,40.5 km,Individual time trial",
"19,24 July,Bourgoin-Jallieu to Aubenas,178.0 km,Road stage",
"20,25 July,Montelimar to Mont Ventoux,167.0 km,Road stage",
"21,26 July,Montereau-Fault-Yonne to Paris,164.0 km,Road stage",
];
let edition = tour_de_france_2009();
assert_eq!(edition.route(), route);
assert_eq!(edition.stage_summary(), "21 stages");
}
#[test]
fn test_tour_de_france_2010() {
let route = [
"P,3 July,Rotterdam (Netherlands),8.9 km,Individual time trial",
"1,4 July,Rotterdam (Netherlands) to Brussels (Belgium),223.5 km,Road stage",
"2,5 July,Brussels (Belgium) to Spa (Belgium),201.0 km,Road stage",
"3,6 July,Wanze (Belgium) to Arenberg Porte du Hainaut,213.0 km,Road stage",
"4,7 July,Cambrai to Reims,153.5 km,Road stage",
"5,8 July,Epernay to Montargis,187.5 km,Road stage",
"6,9 July,Montargis to Gueugnon,227.5 km,Road stage",
"7,10 July,Tournus to Station des Rousses,165.6 km,Road stage",
"8,11 July,Station des Rousses to Morzine-Avoriaz,189.0 km,Road stage",
",12 July,Rest day,Morzine-Avoriaz",
"9,13 July,Morzine-Avoriaz to Saint-Jean-de-Maurienne,204.5 km,Road stage",
"10,14 July,Chambery to Gap,179.0 km,Road stage",
"11,15 July,Sisteron to Bourg-lès-Valence,184.5 km,Road stage",
"12,16 July,Bourg-de-Peage to Mende,210.5 km,Road stage",
"13,17 July,Rodez to Revel,196.0 km,Road stage",
"14,18 July,Revel to Ax 3 Domaines,184.5 km,Road stage",
"15,19 July,Pamiers to Bagnères-de-Luchon,187.5 km,Road stage",
"16,20 July,Bagnères-de-Luchon to Pau,199.5 km,Road stage",
",21 July,Rest day,Pau",
"17,22 July,Pau to Col du Tourmalet,174.0 km,Road stage",
"18,23 July,Salies-de-Bearn to Bordeaux,198.0 km,Road stage",
"19,24 July,Bordeaux to Pauillac,52.0 km,Individual time trial",
"20,25 July,Longjumeau to Paris,102.5 km,Road stage",
];
let edition = tour_de_france_2010();
assert_eq!(edition.route(), route);
assert_eq!(edition.stage_summary(), "20 stages + Prologue");
}
#[test]
fn test_tour_de_france_2011() {
let route = [
"1,2 July,Passage du Gois to Mont des Alouettes,191.5 km,Road stage",
"2,3 July,Les Essarts,23.0 km,Team time trial",
"3,4 July,Olonne-sur-Mer to Redon,198.0 km,Road stage",
"4,5 July,Lorient to Mûr-de-Bretagne,172.5 km,Road stage",
"5,6 July,Carhaix to Cap Frehel,164.5 km,Road stage",
"6,7 July,Dinan to Lisieux,226.5 km,Road stage",
"7,8 July,Le Mans to Chateauroux,218.0 km,Road stage",
"8,9 July,Aigurande to Super Besse,189.0 km,Road stage",
"9,10 July,Issoire to Saint-Flour,208.0 km,Road stage",
",11 July,Rest day,Le Lioran",
"10,12 July,Aurillac to Carmaux,158.0 km,Road stage",
"11,13 July,Blaye-les-Mines to Lavaur,167.5 km,Road stage",
"12,14 July,Cugnaux to Luz Ardiden,211.0 km,Road stage",
"13,15 July,Pau to Lourdes,152.5 km,Road stage",
"14,16 July,Saint-Gaudens to Plateau de Beille,168.5 km,Road stage",
"15,17 July,Limoux to Montpellier,192.5 km,Road stage",
",18 July,Rest day,Drome",
"16,19 July,Saint-Paul-Trois-Chateaux to Gap,162.5 km,Road stage",
"17,20 July,Gap to Pinerolo (Italy),179.0 km,Road stage",
"18,21 July,Pinerolo (Italy) to Col du Galibier - Serre Chevalier,200.5 km,Road stage",
"19,22 July,Modane to Alpe d'Huez,109.5 km,Road stage",
"20,23 July,Grenoble,42.5 km,Individual time trial",
"21,24 July,Creteil to Paris,95.0 km,Road stage",
];
let edition = tour_de_france_2011();
assert_eq!(edition.route(), route);
assert_eq!(edition.stage_summary(), "21 stages");
}
#[test]
fn test_tour_de_france_2012() {
let route = [
"1,30 June,Liège (Belgium),6.4 km,Road stage",
"2,1 July,Liège (Belgium) to Seraing (Belgium),198.0 km,Road stage",
"3,2 July,Vise (Belgium) to Tournai (Belgium),198.0 km,Road stage",
"4,3 July,Orchies to Boulogne-sur-Mer,197.0 km,Road stage",
"5,4 July,Abbeville to Rouen,214.5 km,Road stage",
"6,5 July,Rouen to Saint-Quentin,196.5 km,Road stage",
"7,6 July,Epernay to Metz,207.5 km,Road stage",
"8,7 July,Tomblaine to La Planche des Belles Filles,199.0 km,Road stage",
"9,8 July,Belfort to Porrentruy,157.5 km,Road stage",
"10,9 July,Arc-et-Senans to Besançon,41.5 km,Individual time trial",
",10 July,Rest day,Macon",
"11,11 July,Macon to Bellegarde-sue-Valserine,194.5 km,Road stage",
"12,12 July,Albertville to La Toussuire - Les Sybelles,148.0 km,Road stage",
"13,13 July,Saint-Jean-de-Maurienne to Annonay-Davezieux,226.0 km,Road stage",
"14,14 July,Saint-Paul-Trois-Chateaux to Cap d'Agde,217.0 km,Road stage",
"15,15 July,Limoux to Foix,191.0 km,Road stage",
"16,16 July,Samatan to Pau,158.5 km,Road stage",
",17 July,Rest day,Pau",
"17,18 July,Pau to Bagnères-de-Luchon,197.0 km,Road stage",
"18,19 July,Bagnères-de-Luchon to Peyragudes,143.5 km,Road stage",
"19,20 July,Blagnac to Brive-la-Gaillarde,222.5 km,Road stage",
"20,21 July,Bonneval to Chartres,53.5 km,Individual time trial",
"21,22 July,Rambouillet to Paris,120.0 km,Road stage",
];
let edition = tour_de_france_2012();
assert_eq!(edition.route(), route);
assert_eq!(edition.stage_summary(), "21 stages");
}
#[test]
fn test_tour_de_france_2013() {
let route = [
"1,29 June,Porto-Vecchio to Bastia,213.0 km,Road stage",
"2,30 June,Bastia to Ajaccio,156.0 km,Road stage",
"3,1 July,Ajaccio to Calvi,145.5 km,Road stage",
"4,2 July,Nice,25.0 km,Team time trial",
"5,3 July,Cagnes-sur-Mer to Marseille,228.5 km,Road stage",
"6,4 July,Aix-en-Provence to Montpellier,176.5 km,Road stage",
"7,5 July,Montpellier to Albi,205.5 km,Road stage",
"8,6 July,Castres to Ax 3 Domaines,195.0 km,Road stage",
"9,7 July,Saint-Girons to Bagnères-de-Bigorre,168.5 km,Road stage",
",8 July,Rest day,Saint-Nazaire",
"10,9 July,Saint-Gildas-des-Bois to Saint-Malo,197.0 km,Road stage",
"11,10 July,Avranches to Mont Saint-Michel,33.0 km,Individual time trial",
"12,11 July,Fougeres to Tours,218.0 km,Road stage",
"13,12 July,Tours to Saint-Amand-Montrond,173.0 km,Road stage",
"14,13 July,Saint-Pourcain-sur-Sioule to Lyon,191.0 km,Road stage",
"15,14 July,Givors to Mont Ventoux,242.5 km,Road stage",
",15 July,Rest day,Vaucluse",
"16,16 July,Vaison-la-Romaine to Gap,168.0 km,Road stage",
"17,17 July,Embrun to Chorges,32.0 km,Individual time trial",
"18,18 July,Gap to Alpe d'Huez,172.5 km,Road stage",
"19,19 July,Le Bourg-d'Oisans to Le Grand Bornand,204.5 km,Road stage",
"20,20 July,Annecy to Semnoz,125.0 km,Road stage",
"21,21 July,Versailles to Paris,133.5 km,Road stage",
];
let edition = tour_de_france_2013();
assert_eq!(edition.route(), route);
assert_eq!(edition.stage_summary(), "21 stages");
}
#[test]
fn test_tour_de_france_2014() {
let route = [
"1,5 July,Leeds (United Kingdom) to Harrogate (United Kingdom),190.5 km,Road stage",
"2,6 July,York (United Kingdom) to Sheffield (United Kingdom),201.0 km,Road stage",
"3,7 July,Cambridge (United Kingdom) to London (United Kingdom),155.0 km,Road stage",
"4,8 July,Le Touquet-Paris-Plage to Lille Metropole,163.5 km,Road stage",
"5,9 July,Ypres (Belgium) to Arenberg Porte du Hainaut,152.5 km,Road stage",
"6,10 July,Arras to Reims,194.0 km,Road stage",
"7,11 July,Epernay to Nancy,234.5 km,Road stage",
"8,12 July,Tomblaine to Gerardmer las Mauselaine,161.0 km,Road stage",
"9,13 July,Gerardmer to Mulhouse,170.0 km,Road stage",
"10,14 July,Mulhouse to La Planche des Belles Filles,161.5 km,Road stage",
",15 July,Rest day,Besançon",
"11,16 July,Besançon to Oyonnax,187.5 km,Road stage",
"12,17 July,Bourg-en-Bresse to Saint-Étienne,185.5 km,Road stage",
"13,18 July,Saint-Étienne to Chamrousse,197.5 km,Road stage",
"14,19 July,Grenoble to Risoul,177.0 km,Road stage",
"15,20 July,Tallard to Nîmes,222.0 km,Road stage",
",21 July,Rest day,Carcassonne",
"16,22 July,Carcassonne to Bagnères-de-Luchon,237.5 km,Road stage",
"17,23 July,Saint-Gaudens to Saint-Lary Pla d'Adet,124.5 km,Road stage",
"18,24 July,Pau to Hautacam,145.5 km,Road stage",
"19,25 July,Maubourguet Pays du Val d'Adour to Bergerac,208.5 km,Road stage",
"20,26 July,Bergerac to Périgueux,54.0 km,Individual time trial",
"21,27 July,Evry to Paris,137.5 km,Road stage",
];
let edition = tour_de_france_2014();
assert_eq!(edition.route(), route);
assert_eq!(edition.stage_summary(), "21 stages");
}
#[test]
fn test_tour_de_france_2015() {
let route = [
"1,4 July,Utrecht (Netherlands),13.8 km,Individual time trial",
"2,5 July,Utrecht (Netherlands) to Zeeland (Netherlands),166.0 km,Road stage",
"3,6 July,Antwerp (Belgium) to Huy (Belgium),159.5 km,Road stage",
"4,7 July,Seraing (Belgium) to Cambrai,223.5 km,Road stage",
"5,8 July,Arras to Amiens,189.5 km,Road stage",
"6,9 July,Abbeville to Le Havre,191.5 km,Road stage",
"7,10 July,Livarot to Fougeres,190.5 km,Road stage",
"8,11 July,Rennes to Mûr-de-Bretagne,181.5 km,Road stage",
"9,12 July,Vannes to Plumelec,28.0 km,Team time trial",
",13 July,Rest day,Pau",
"10,14 July,Tarbes to La Pierre Saint-Martin,167.0 km,Road stage",
"11,15 July,Pau to Cauterets,188.0 km,Road stage",
"12,16 July,Lannemezan to Plateau de Beille,195.0 km,Road stage",
"13,17 July,Muret to Rodez,198.5 km,Road stage",
"14,18 July,Rodez to Mende,178.5 km,Road stage",
"15,19 July,Mende to Valence,183.0 km,Road stage",
"16,20 July,Bourg-de-Peage to Gap,201.0 km,Road stage",
",21 July,Rest day,Gap",
"17,22 July,Digne-les-Bains to Pra-Loup,161.0 km,Road stage",
"18,23 July,Gap to Saint-Jean-de-Maurienne,186.5 km,Road stage",
"19,24 July,Saint-Jean-de-Maurienne to La Toussuire - Les Sybelles,138.0 km,Road stage",
"20,25 July,Modane to Alpe d'Huez,110.5 km,Road stage",
"21,26 July,Sevres to Paris,109.5 km,Road stage",
];
let edition = tour_de_france_2015();
assert_eq!(edition.route(), route);
assert_eq!(edition.stage_summary(), "21 stages");
}
#[test]
fn test_tour_de_france_2016() {
let route = [
"1,2 July,Mont Saint-Michel to Utah Beach (Sainte-Marie-du-Mont),188.0 km,Road stage",
"2,3 July,Saint-Lo to Cherbourg-en-Cotentin,183.0 km,Road stage",
"3,4 July,Granville to Angers,223.5 km,Road stage",
"4,5 July,Saumur to Limoges,237.5 km,Road stage",
"5,6 July,Limoges to Le Lioran,216.0 km,Road stage",
"6,7 July,Arpajon-sur-Cere to Montauban,190.5 km,Road stage",
"7,8 July,L'Isle-Jourdain to Lac de Payolle,162.5 km,Road stage",
"8,9 July,Pau to Bagnères-de-Luchon,184.0 km,Road stage",
"9,10 July,Vielha Val d'Aran (Spain) to Andorra-Arcalis (Andorra),184.5 km,Road stage",
",11 July,Rest day,Andorra-Arcalis (Andorra)",
"10,12 July,Escaldes-Engordany (Andorra) to Revel,197.0 km,Road stage",
"11,13 July,Carcassonne to Montpellier,162.5 km,Road stage",
"12,14 July,Montpellier to Chalet Reynard (Mont Ventoux),178.0 km,Road stage",
"13,15 July,Bourg-Saint-Andeol to La Caverne du Pont-d'Arc,37.5 km,Individual time trial",
"14,16 July,Montelimar to Villar-les-Dombes (Parc des Oiseaux),208.5 km,Road stage",
"15,17 July,Bourg-en-Bresse to Culoz,160.0 km,Road stage",
"16,18 July,Moirans-en-Montagne to Bern (Switzerland),209.0 km,Road stage",
",19 July,Rest day,Bern (Switzerland)",
"17,20 July,Bern (Switzerland) to Finhaut-Emosson (Switzerland),184.5 km,Road stage",
"18,21 July,Sallanches to Megeve,17.0 km,Individual time trial",
"19,22 July,Abbeville to Saint Gervais-les-Bains,146.0 km,Road stage",
"20,23 July,Megeve to Morzine,146.5 km,Road stage",
"21,24 July,Chantilly to Paris,113.0 km,Road stage",
];
let edition = tour_de_france_2016();
assert_eq!(edition.route(), route);
assert_eq!(edition.stage_summary(), "21 stages");
}
#[test]
fn test_tour_de_france_2017() {
let route = [
"1,1 July,Dusseldorf (Germany),14.0 km,Individual time trial",
"2,2 July,Dusseldorf (Germany) to Liège (Belgium),203.5 km,Road stage",
"3,3 July,Verviers (Belgium) to Longwy,212.5 km,Road stage",
"4,4 July,Mondorf-les-Bains (Luxembourg) to Vittel,207.5 km,Road stage",
"5,5 July,Vittel to La Planche des Belles Filles,160.5 km,Road stage",
"6,6 July,Vesoul to Troyes,216.0 km,Road stage",
"7,7 July,Troyes to Nuits-Saint-Georges,213.5 km,Road stage",
"8,8 July,Dole to Station des Rousses,187.5 km,Road stage",
"9,9 July,Nantua to Chambery,181.5 km,Road stage",
",10 July,Rest day,Dordogne",
"10,11 July,Périgueux to Bergerac,178.0 km,Road stage",
"11,12 July,Eymet to Pau,203.5 km,Road stage",
"12,13 July,Pau to Peyragudes,214.5 km,Road stage",
"13,14 July,Saint-Girons to Foix,101.0 km,Road stage",
"14,15 July,Blagnac to Rodez,181.5 km,Road stage",
"15,16 July,Laissac-Severac-l'Eglise to Le Puy-en-Velay,189.5 km,Road stage",
",17 July,Rest day,Le Puy-en-Velay",
"16,18 July,Le Puy-en-Velay to Romans-sur-Isere,165.0 km,Road stage",
"17,19 July,La Mure to Serre Chevalier,183.0 km,Road stage",
"18,20 July,Briançon to Col d'Izoard,179.5 km,Road stage",
"19,21 July,Embrun to Salon-de-Provence,222.5 km,Road stage",
"20,22 July,Marseille,22.5 km,Individual time trial",
"21,23 July,Montgeron to Paris,103.0 km,Road stage",
];
let edition = tour_de_france_2017();
assert_eq!(edition.route(), route);
assert_eq!(edition.stage_summary(), "21 stages");
}
#[test]
fn test_tour_de_france_2018() {
let route = [
"1,7 July,Noirmoutier-en-l'Île to Fontenay-le-Comte,201.0 km,Road stage",
"2,8 July,Mouilleron-Saint-Germain to La Roche-sur-Yon,182.5 km,Road stage",
"3,9 July,Cholet,35.5 km,Team time trial",
"4,10 July,La Baule to Sarzeau,195.0 km,Road stage",
"5,11 July,Lorient to Quimper,204.5 km,Road stage",
"6,12 July,Brest to Mûr-de-Bretagne,181.0 km,Road stage",
"7,13 July,Fougres to Chartres,231.0 km,Road stage",
"8,14 July,Dreux to Amiens,181.0 km,Road stage",
"9,15 July,Arras to Roubaix,156.5 km,Road stage",
",16 July,Rest day,Annecy",
"10,17 July,Annecy to Le Grand Bornand,158.5 km,Road stage",
"11,18 July,Albertville to La Rosiere,108.5 km,Road stage",
"12,19 July,Bourg-Saint-Maurice to Alpe d'Huez,175.5 km,Road stage",
"13,20 July,Le Bourg-d'Oisans to Valence,169.5 km,Road stage",
"14,21 July,Saint-Paul-Trois-Chateaux to Mende,188.0 km,Road stage",
"15,22 July,Millau to Carcassonne,181.5 km,Road stage",
",23 July,Rest day,Lourdes",
"16,24 July,Carcassonne to Bagnères-de-Luchon,218.0 km,Road stage",
"17,25 July,Bagnères-de-Luchon to Saint-Lary-Soulan (Col de Portet),65.0 km,Road stage",
"18,26 July,Trie-sur-Basie to Pau,171.0 km,Road stage",
"19,27 July,Lourdes to Laruns,200.5 km,Road stage",
"20,28 July,Saint-Pée-sur-Nivelle to Espelette,31.0 km,Individual time trial",
"21,29 July,Houilles to Paris,116.0 km,Road stage",
];
let edition = tour_de_france_2018();
assert_eq!(edition.route(), route);
assert_eq!(edition.summit_finishes(), 4);
assert_eq!(edition.stage_summary(), "21 stages");
}
}
| true |
5a07fd45765dd1862cc558746d3a25120a820a2d
|
Rust
|
willdoescode/hera
|
/src/parser/mod.rs
|
UTF-8
| 12,021 | 3.3125 | 3 |
[
"MIT"
] |
permissive
|
#[cfg(test)]
pub mod test;
use crate::{ast::*, lexer::Lexer, token::Token};
pub struct Parser {
pub l: Lexer,
pub current_token: Token,
pub peek_token: Token,
pub errors: Vec<String>,
}
impl Parser {
pub fn new(lexer: Lexer) -> Self {
let mut p: Parser = Parser {
l: lexer,
current_token: Token::Eof,
peek_token: Token::Eof,
errors: vec![],
};
p.next_token();
p.next_token();
p
}
pub fn next_token(&mut self) {
self.current_token = self.peek_token.clone();
self.peek_token = self.l.next_token();
}
fn token_to_precedence(tok: &Token) -> Precedence {
match tok {
Token::Equal | Token::NotEq => Precedence::Equals,
Token::Lt | Token::LtEq => Precedence::LessGreater,
Token::Gt | Token::GtEq => Precedence::LessGreater,
Token::Plus | Token::Minus => Precedence::Sum,
Token::Slash | Token::Asterisk => Precedence::Product,
Token::LBrace => Precedence::Index,
Token::LParen => Precedence::Call,
_ => Precedence::Lowest,
}
}
pub fn parse_program(&mut self) -> Program {
let mut statements: Vec<Statement> = vec![];
while self.current_token != Token::Eof {
let stmt: Option<Statement> = self.parse_statement();
if stmt != None {
statements.push(stmt.unwrap());
};
self.next_token();
}
Program { statements }
}
pub fn parse_statement(&mut self) -> Option<Statement> {
match self.current_token {
Token::Let => self.parse_let_statement(),
Token::Return => self.parse_return_statement(),
// _ => panic!("Illegal token found."),
_ => self.parse_expression_statement(),
}
}
pub fn parse_expression_statement(&mut self) -> Option<Statement> {
match self.parse_expression(Precedence::Lowest) {
Some(expression) => {
if self.peek_token_is(&Token::SemiColon) {
self.next_token();
}
Some(Statement::Expression(expression))
}
None => None,
}
}
pub fn parse_let_statement(&mut self) -> Option<Statement> {
match &self.peek_token {
Token::Ident(_) => self.next_token(),
_ => {
self.peek_error(Token::Ident(String::new()));
return None;
}
}
let name: Ident = match self.parse_ident() {
Some(Expression::Ident(ref mut s)) => s.clone(),
_ => return None,
};
if !self.expect_peek(Token::Assign) {
return None;
}
self.next_token();
let lit: Expression = match self.parse_expression(Precedence::Lowest) {
Some(e) => e,
None => return None,
};
while !self.current_token_is(Token::SemiColon) {
self.next_token();
}
Some(Statement::Let(name, lit))
}
pub fn parse_return_statement(&mut self) -> Option<Statement> {
self.next_token();
let exp = match self.parse_expression(Precedence::Lowest) {
Some(e) => e,
None => return None,
};
while !self.current_token_is(Token::SemiColon) {
self.next_token();
}
Some(Statement::Return(exp))
}
fn parse_block_statement(&mut self) -> BlockStatement {
self.next_token();
let mut statements = vec![];
while !self.current_token_is(Token::RBrace) && !self.current_token_is(Token::Eof) {
if let Some(s) = self.parse_statement() {
statements.push(s);
}
self.next_token();
}
statements
}
fn parse_expression(&mut self, precedence: Precedence) -> Option<Expression> {
// prefix
let mut left: Option<Expression> = match self.current_token {
Token::Ident(_) => self.parse_ident(),
Token::Int(_) => self.parse_int_literal(),
Token::Bool(_) => self.parse_bool_literal(),
Token::Bang | Token::Minus | Token::Plus => self.parse_prefix_expression(),
Token::LParen => self.parse_grouped_expression(),
Token::If => self.parse_if_expression(),
Token::Function => self.parse_fn_expression(),
_ => {
// TODO: add function call here
None
}
};
// infix
while !self.peek_token_is(&Token::SemiColon) && precedence < self.next_token_precedence() {
match self.peek_token {
Token::Plus
| Token::Minus
| Token::Asterisk
| Token::Equal
| Token::Slash
| Token::NotEq
| Token::Lt
| Token::LtEq
| Token::Gt
| Token::GtEq => {
self.next_token();
left = self.parse_infix_expression(left.unwrap());
}
Token::LParen => {
self.next_token();
left = self.parse_call_expression(left.unwrap());
}
_ => return left,
}
}
left
}
fn parse_int_literal(&mut self) -> Option<Expression> {
match self.current_token {
Token::Int(ref mut int) => Some(Expression::Literal(Literal::Int(*int))),
_ => None,
}
}
fn parse_bool_literal(&mut self) -> Option<Expression> {
match self.current_token {
Token::Bool(boolean) => Some(Expression::Literal(Literal::Bool(boolean))),
_ => None,
}
}
fn parse_ident(&mut self) -> Option<Expression> {
match self.current_token {
Token::Ident(ref mut ident) => Some(Expression::Ident(Ident(ident.clone()))),
_ => None,
}
}
fn parse_prefix_expression(&mut self) -> Option<Expression> {
let prefix = match self.current_token {
Token::Bang => Prefix::Not,
Token::Minus => Prefix::Minus,
Token::Plus => Prefix::Plus,
_ => return None,
};
self.next_token();
self.parse_expression(Precedence::Prefix)
.map(|expr| Expression::Prefix(prefix, Box::new(expr)))
}
fn parse_infix_expression(&mut self, left: Expression) -> Option<Expression> {
let infix = match self.current_token {
Token::Plus => Infix::Plus,
Token::Minus => Infix::Minus,
Token::Slash => Infix::Divide,
Token::Asterisk => Infix::Multiply,
Token::Equal => Infix::Equal,
Token::NotEq => Infix::NotEqual,
Token::Lt => Infix::LessThan,
Token::Gt => Infix::GreaterThan,
Token::LtEq => Infix::LessThanEqual,
Token::GtEq => Infix::GreaterThanEqual,
_ => return None,
};
let precedence = self.current_token_precedence();
self.next_token();
self.parse_expression(precedence)
.map(|e| Expression::Infix(infix, Box::new(left), Box::new(e)))
}
fn parse_grouped_expression(&mut self) -> Option<Expression> {
self.next_token();
let exp = self.parse_expression(Precedence::Lowest);
if !self.expect_peek(Token::RParen) {
return None;
}
exp
}
fn parse_if_expression(&mut self) -> Option<Expression> {
if !self.expect_peek(Token::LParen) {
return None;
}
self.next_token();
let expr: Expression = match self.parse_expression(Precedence::Lowest) {
Some(e) => e,
None => return None,
};
if !self.expect_peek(Token::RParen) || !self.expect_peek(Token::LBrace) {
return None;
}
let cons: Vec<Statement> = self.parse_block_statement();
let mut alternative: Option<Vec<Statement>> = None;
if self.peek_token_is(&Token::Else) {
self.next_token();
if self.peek_token_is(&Token::If) {
self.next_token();
let else_if = self.parse_if_expression();
alternative = Some(vec![Statement::Expression(else_if.unwrap())]);
} else if !self.expect_peek(Token::LBrace) {
return None;
} else {
alternative = Some(self.parse_block_statement())
};
}
Some(Expression::If {
condition: Box::new(expr),
consequence: cons,
alternative,
})
}
fn parse_fn_expression(&mut self) -> Option<Expression> {
if !self.expect_peek(Token::LParen) {
return None;
}
let params = match self.parse_fn_params() {
Some(s) => s,
None => return None,
};
let body = self.parse_block_statement();
Some(Expression::Fn { params, body })
}
fn parse_fn_params(&mut self) -> Option<Vec<Ident>> {
let mut idents: Vec<Ident> = vec![];
if self.peek_token_is(&Token::RParen) {
self.next_token();
return Some(idents);
}
self.next_token();
match self.current_token {
Token::Ident(ref mut ident) => idents.push(Ident(ident.clone())),
_ => return None,
};
while self.peek_token_is(&Token::Comma) {
self.next_token();
self.next_token();
match self.current_token {
Token::Ident(ref mut ident) => idents.push(Ident(ident.clone())),
_ => return None,
};
}
Some(idents)
}
fn parse_call_expression(&mut self, left: Expression) -> Option<Expression> {
let args = match self.parse_call_arguments() {
Some(e) => e,
None => return None,
};
Some(Expression::Call {
function: Box::new(left),
args,
})
}
fn parse_call_arguments(&mut self) -> Option<Vec<Expression>> {
let mut args: Vec<Expression> = vec![];
if self.peek_token_is(&Token::RParen) {
self.next_token();
return Some(args);
}
self.next_token();
match self.parse_expression(Precedence::Lowest) {
Some(e) => args.push(e),
None => return None,
};
while self.peek_token_is(&Token::Comma) {
self.next_token();
self.next_token();
match self.parse_expression(Precedence::Lowest) {
Some(e) => args.push(e),
None => return None,
};
}
if !self.expect_peek(Token::RParen) {
return None;
}
Some(args)
}
fn peek_token_is(&self, t: &Token) -> bool {
self.peek_token == *t
}
fn current_token_is(&self, t: Token) -> bool {
self.current_token == t
}
fn expect_peek(&mut self, t: Token) -> bool {
if let Token::Ident(..) = t {
self.next_token();
return true;
}
if self.peek_token_is(&t) {
self.next_token();
true
} else {
self.peek_error(t);
false
}
}
fn peek_error(&mut self, t: Token) {
let msg = format!(
"Expected next token to be {expected}, got {found}",
expected = t,
found = self.peek_token
);
self.errors.push(msg);
}
fn current_token_precedence(&mut self) -> Precedence {
Self::token_to_precedence(&self.current_token)
}
fn next_token_precedence(&mut self) -> Precedence {
Self::token_to_precedence(&self.peek_token)
}
}
| true |
d76754865d7abff5fd3b44b0f7a7d30ff52e6d45
|
Rust
|
zellij-org/zellij
|
/zellij-client/src/old_config_converter/old_config.rs
|
UTF-8
| 42,838 | 2.640625 | 3 |
[
"MIT"
] |
permissive
|
// This is a converter from the old yaml config to the new KDL config.
//
// It is supposed to be mostly self containing - please refrain from adding to it, importing
// from it or changing it
use std::fmt;
use std::path::PathBuf;
use serde::de::{Error, Visitor};
use serde::{Deserialize, Deserializer, Serialize};
use std::collections::{BTreeMap, HashMap};
use url::Url;
const ON_FORCE_CLOSE_DESCRIPTION: &'static str = "
// Choose what to do when zellij receives SIGTERM, SIGINT, SIGQUIT or SIGHUP
// eg. when terminal window with an active zellij session is closed
// Options:
// - detach (Default)
// - quit
//
";
const SIMPLIFIED_UI_DESCRIPTION: &'static str = "
// Send a request for a simplified ui (without arrow fonts) to plugins
// Options:
// - true
// - false (Default)
//
";
const DEFAULT_SHELL_DESCRIPTION: &'static str = "
// Choose the path to the default shell that zellij will use for opening new panes
// Default: $SHELL
//
";
const PANE_FRAMES_DESCRIPTION: &'static str = "
// Toggle between having pane frames around the panes
// Options:
// - true (default)
// - false
//
";
const DEFAULT_THEME_DESCRIPTION: &'static str = "
// Choose the theme that is specified in the themes section.
// Default: default
//
";
const DEFAULT_MODE_DESCRIPTION: &'static str = "
// Choose the mode that zellij uses when starting up.
// Default: normal
//
";
const MOUSE_MODE_DESCRIPTION: &'static str = "
// Toggle enabling the mouse mode.
// On certain configurations, or terminals this could
// potentially interfere with copying text.
// Options:
// - true (default)
// - false
//
";
const SCROLL_BUFFER_SIZE_DESCRIPTION: &'static str = "
// Configure the scroll back buffer size
// This is the number of lines zellij stores for each pane in the scroll back
// buffer. Excess number of lines are discarded in a FIFO fashion.
// Valid values: positive integers
// Default value: 10000
//
";
const COPY_COMMAND_DESCRIPTION: &'static str = "
// Provide a command to execute when copying text. The text will be piped to
// the stdin of the program to perform the copy. This can be used with
// terminal emulators which do not support the OSC 52 ANSI control sequence
// that will be used by default if this option is not set.
// Examples:
//
// copy_command \"xclip -selection clipboard\" // x11
// copy_command \"wl-copy\" // wayland
// copy_command \"pbcopy\" // osx
";
const COPY_CLIPBOARD_DESCRIPTION: &'static str = "
// Choose the destination for copied text
// Allows using the primary selection buffer (on x11/wayland) instead of the system clipboard.
// Does not apply when using copy_command.
// Options:
// - system (default)
// - primary
//
";
const COPY_ON_SELECT_DESCRIPTION: &'static str = "
// Enable or disable automatic copy (and clear) of selection when releasing mouse
// Default: true
//
";
const SCROLLBACK_EDITOR_DESCRIPTION: &'static str = "
// Path to the default editor to use to edit pane scrollbuffer
// Default: $EDITOR or $VISUAL
//
";
const MIRROR_SESSION_DESCRIPTION: &'static str = "
// When attaching to an existing session with other users,
// should the session be mirrored (true)
// or should each user have their own cursor (false)
// Default: false
//
";
const DEFAULT_LAYOUT_DESCRIPTION: &'static str = "
// The name of the default layout to load on startup
// Default: \"default\"
//
";
const LAYOUT_DIR_DESCRIPTION: &'static str = "
// The folder in which Zellij will look for layouts
//
";
const THEME_DIR_DESCRIPTION: &'static str = "
// The folder in which Zellij will look for themes
//
";
fn options_yaml_to_options_kdl(options_yaml: &OldOptions, no_comments: bool) -> String {
let mut options_kdl = String::new();
macro_rules! push_option {
($attribute_name:ident, $description_text:ident, $present_pattern:expr) => {
if !no_comments {
options_kdl.push_str($description_text);
}
if let Some($attribute_name) = &options_yaml.$attribute_name {
options_kdl.push_str(&format!($present_pattern, $attribute_name));
options_kdl.push('\n');
};
};
($attribute_name:ident, $description_text:ident, $present_pattern:expr, $absent_pattern:expr) => {
if !no_comments {
options_kdl.push_str($description_text);
}
match &options_yaml.$attribute_name {
Some($attribute_name) => {
options_kdl.push_str(&format!($present_pattern, $attribute_name));
},
None => {
if !no_comments {
options_kdl.push_str(&format!($absent_pattern));
}
},
};
if !no_comments || options_yaml.$attribute_name.is_some() {
options_kdl.push('\n');
}
};
}
push_option!(
on_force_close,
ON_FORCE_CLOSE_DESCRIPTION,
"on_force_close \"{}\"",
"// on_force_close \"quit\""
);
push_option!(
simplified_ui,
SIMPLIFIED_UI_DESCRIPTION,
"simplified_ui {}",
"// simplified_ui true"
);
push_option!(
default_shell,
DEFAULT_SHELL_DESCRIPTION,
"default_shell {:?}",
"// default_shell \"fish\""
);
push_option!(
pane_frames,
PANE_FRAMES_DESCRIPTION,
"pane_frames {}",
"// pane_frames true"
);
push_option!(
theme,
DEFAULT_THEME_DESCRIPTION,
"theme {:?} ",
"// theme \"default\""
);
push_option!(
default_layout,
DEFAULT_LAYOUT_DESCRIPTION,
"default_layout {:?}",
"// default_layout \"compact\""
);
push_option!(
default_mode,
DEFAULT_MODE_DESCRIPTION,
"default_mode \"{}\"",
"// default_mode \"locked\""
);
push_option!(
mouse_mode,
MOUSE_MODE_DESCRIPTION,
"mouse_mode {}",
"// mouse_mode false"
);
push_option!(
scroll_buffer_size,
SCROLL_BUFFER_SIZE_DESCRIPTION,
"scroll_buffer_size {}",
"// scroll_buffer_size 10000"
);
push_option!(copy_command, COPY_COMMAND_DESCRIPTION, "copy_command {:?}");
push_option!(
copy_clipboard,
COPY_CLIPBOARD_DESCRIPTION,
"copy_clipboard \"{}\"",
"// copy_clipboard \"primary\""
);
push_option!(
copy_on_select,
COPY_ON_SELECT_DESCRIPTION,
"copy_on_select {}",
"// copy_on_select false"
);
push_option!(
scrollback_editor,
SCROLLBACK_EDITOR_DESCRIPTION,
"scrollback_editor {:?}",
"// scrollback_editor \"/usr/bin/vim\""
);
push_option!(
mirror_session,
MIRROR_SESSION_DESCRIPTION,
"mirror_session {}",
"// mirror_session true"
);
push_option!(
layout_dir,
LAYOUT_DIR_DESCRIPTION,
"layout_dir {:?}",
"// layout_dir /path/to/my/layout_dir"
);
push_option!(
theme_dir,
THEME_DIR_DESCRIPTION,
"theme_dir {:?}",
"// theme_dir \"/path/to/my/theme_dir\""
);
options_kdl
}
fn env_yaml_to_env_kdl(env_yaml: &OldEnvironmentVariablesFromYaml) -> String {
let mut env_kdl = String::new();
let mut env_vars: Vec<(String, String)> = env_yaml
.env
.iter()
.map(|(name, val)| (name.clone(), val.clone()))
.collect();
env_vars.sort_unstable();
env_kdl.push_str("env {\n");
for (name, val) in env_vars {
env_kdl.push_str(&format!(" {} \"{}\"\n", name, val));
}
env_kdl.push_str("}\n");
env_kdl
}
fn plugins_yaml_to_plugins_kdl(plugins_yaml_to_plugins_kdl: &OldPluginsConfigFromYaml) -> String {
let mut plugins_kdl = String::new();
if !&plugins_yaml_to_plugins_kdl.0.is_empty() {
plugins_kdl.push_str("\n");
plugins_kdl.push_str("plugins {\n")
}
for plugin_config in &plugins_yaml_to_plugins_kdl.0 {
if plugin_config._allow_exec_host_cmd {
plugins_kdl.push_str(&format!(
" {} {{ path {:?}; _allow_exec_host_cmd true; }}\n",
plugin_config.tag.0, plugin_config.path
));
} else {
plugins_kdl.push_str(&format!(
" {} {{ path {:?}; }}\n",
plugin_config.tag.0, plugin_config.path
));
}
}
if !&plugins_yaml_to_plugins_kdl.0.is_empty() {
plugins_kdl.push_str("}\n")
}
plugins_kdl
}
fn ui_config_yaml_to_ui_config_kdl(ui_config_yaml: &OldUiConfigFromYaml) -> String {
let mut kdl_ui_config = String::new();
if ui_config_yaml.pane_frames.rounded_corners {
kdl_ui_config.push_str("\n");
kdl_ui_config.push_str("ui {\n");
kdl_ui_config.push_str(" pane_frames {\n");
kdl_ui_config.push_str(" rounded_corners true\n");
kdl_ui_config.push_str(" }\n");
kdl_ui_config.push_str("}\n");
} else {
// I'm not sure this is a thing, but since it's possible, why not?
kdl_ui_config.push_str("\n");
kdl_ui_config.push_str("ui {\n");
kdl_ui_config.push_str(" pane_frames {\n");
kdl_ui_config.push_str(" rounded_corners false\n");
kdl_ui_config.push_str(" }\n");
kdl_ui_config.push_str("}\n");
}
kdl_ui_config
}
fn theme_config_yaml_to_theme_config_kdl(
theme_config_yaml: &OldThemesFromYamlIntermediate,
) -> String {
macro_rules! theme_color {
($theme:ident, $color:ident, $color_name:expr, $kdl_theme_config:expr) => {
match $theme.palette.$color {
OldPaletteColorFromYaml::Rgb((r, g, b)) => {
$kdl_theme_config
.push_str(&format!(" {} {} {} {}\n", $color_name, r, g, b));
},
OldPaletteColorFromYaml::EightBit(eight_bit_color) => {
$kdl_theme_config
.push_str(&format!(" {} {}\n", $color_name, eight_bit_color));
},
OldPaletteColorFromYaml::Hex(OldHexColor(r, g, b)) => {
$kdl_theme_config
.push_str(&format!(" {} {} {} {}\n", $color_name, r, g, b));
},
}
};
}
let mut kdl_theme_config = String::new();
if !theme_config_yaml.0.is_empty() {
kdl_theme_config.push_str("themes {\n")
}
let mut themes: Vec<(String, OldTheme)> = theme_config_yaml
.0
.iter()
.map(|(theme_name, theme)| (theme_name.clone(), theme.clone()))
.collect();
themes.sort_by(|a, b| a.0.partial_cmp(&b.0).unwrap());
for (theme_name, theme) in themes {
kdl_theme_config.push_str(&format!(" {} {{\n", theme_name));
theme_color!(theme, fg, "fg", kdl_theme_config);
theme_color!(theme, bg, "bg", kdl_theme_config);
theme_color!(theme, black, "black", kdl_theme_config);
theme_color!(theme, red, "red", kdl_theme_config);
theme_color!(theme, green, "green", kdl_theme_config);
theme_color!(theme, yellow, "yellow", kdl_theme_config);
theme_color!(theme, blue, "blue", kdl_theme_config);
theme_color!(theme, magenta, "magenta", kdl_theme_config);
theme_color!(theme, cyan, "cyan", kdl_theme_config);
theme_color!(theme, white, "white", kdl_theme_config);
theme_color!(theme, orange, "orange", kdl_theme_config);
kdl_theme_config.push_str(" }\n");
}
if !theme_config_yaml.0.is_empty() {
kdl_theme_config.push_str("}\n")
}
kdl_theme_config
}
fn keybinds_yaml_to_keybinds_kdl(keybinds_yaml: &OldKeybindsFromYaml) -> String {
let mut kdl_keybinds = String::new();
let modes = vec![
// mode sort order
OldInputMode::Normal,
OldInputMode::Locked,
OldInputMode::Pane,
OldInputMode::Tab,
OldInputMode::Resize,
OldInputMode::Move,
OldInputMode::Scroll,
OldInputMode::Session,
OldInputMode::Search,
OldInputMode::EnterSearch,
OldInputMode::RenameTab,
OldInputMode::RenamePane,
OldInputMode::Prompt,
OldInputMode::Tmux,
];
// title and global unbinds / clear-defaults
match &keybinds_yaml.unbind {
OldUnbind::Keys(keys_to_unbind) => {
kdl_keybinds.push_str("keybinds {\n");
let key_string: String = keys_to_unbind
.iter()
.map(|k| format!("\"{}\"", k))
.collect::<Vec<String>>()
.join(" ");
kdl_keybinds.push_str(&format!(" unbind {}\n", key_string));
},
OldUnbind::All(should_unbind_all_defaults) => {
if *should_unbind_all_defaults {
kdl_keybinds.push_str("keybinds clear-defaults=true {\n");
} else {
kdl_keybinds.push_str("keybinds {\n");
}
},
}
for mode in modes {
if let Some(mode_keybinds) = keybinds_yaml.keybinds.get(&mode) {
let mut should_clear_mode_defaults = false;
let mut kdl_mode_keybinds = String::new();
for key_action_unbind in mode_keybinds {
match key_action_unbind {
OldKeyActionUnbind::KeyAction(key_action) => {
let keys = &key_action.key;
let actions = &key_action.action;
let key_string: String = keys
.iter()
.map(|k| {
if k == &OldKey::Char('\\') {
format!("r\"{}\"", k)
} else {
format!("\"{}\"", k)
}
})
.collect::<Vec<String>>()
.join(" ");
let actions_string: String = actions
.iter()
.map(|a| format!("{};", a))
.collect::<Vec<String>>()
.join(" ");
kdl_mode_keybinds.push_str(&format!(
" bind {} {{ {} }}\n",
key_string, actions_string
));
},
OldKeyActionUnbind::Unbind(unbind) => match &unbind.unbind {
OldUnbind::Keys(keys_to_unbind) => {
let key_string: String = keys_to_unbind
.iter()
.map(|k| format!("\"{}\"", k))
.collect::<Vec<String>>()
.join(" ");
kdl_mode_keybinds.push_str(&format!(" unbind {}\n", key_string));
},
OldUnbind::All(unbind_all) => {
if *unbind_all {
should_clear_mode_defaults = true;
}
},
},
}
}
if should_clear_mode_defaults {
kdl_keybinds.push_str(&format!(" {} clear-defaults=true {{\n", mode));
} else {
kdl_keybinds.push_str(&format!(" {} {{\n", mode));
}
kdl_keybinds.push_str(&kdl_mode_keybinds);
kdl_keybinds.push_str(" }\n");
}
}
kdl_keybinds.push_str("}\n");
kdl_keybinds
}
pub fn config_yaml_to_config_kdl(
raw_yaml_config: &str,
no_comments: bool,
) -> Result<String, String> {
// returns the raw kdl config
let config_from_yaml: OldConfigFromYaml = serde_yaml::from_str(raw_yaml_config)
.map_err(|e| format!("Failed to parse yaml: {:?}", e))?;
let mut kdl_config = String::new();
if let Some(old_config_keybinds) = config_from_yaml.keybinds.as_ref() {
kdl_config.push_str(&keybinds_yaml_to_keybinds_kdl(old_config_keybinds));
}
if let Some(old_config_options) = config_from_yaml.options.as_ref() {
kdl_config.push_str(&options_yaml_to_options_kdl(
old_config_options,
no_comments,
));
}
if let Some(old_config_env_variables) = config_from_yaml.env.as_ref() {
kdl_config.push_str(&env_yaml_to_env_kdl(old_config_env_variables));
}
kdl_config.push_str(&plugins_yaml_to_plugins_kdl(&config_from_yaml.plugins));
if let Some(old_ui_config) = config_from_yaml.ui.as_ref() {
kdl_config.push_str(&ui_config_yaml_to_ui_config_kdl(old_ui_config));
}
if let Some(old_themes_config) = config_from_yaml.themes.as_ref() {
kdl_config.push_str(&theme_config_yaml_to_theme_config_kdl(old_themes_config));
}
Ok(kdl_config)
}
#[derive(Clone, Default, Debug, Deserialize, Serialize, PartialEq)]
pub struct OldConfigFromYaml {
#[serde(flatten)]
pub options: Option<OldOptions>,
pub keybinds: Option<OldKeybindsFromYaml>,
pub themes: Option<OldThemesFromYamlIntermediate>,
#[serde(flatten)]
pub env: Option<OldEnvironmentVariablesFromYaml>,
#[serde(default)]
pub plugins: OldPluginsConfigFromYaml,
pub ui: Option<OldUiConfigFromYaml>,
}
#[derive(Clone, Debug, PartialEq, Deserialize, Serialize)]
pub struct OldKeybindsFromYaml {
#[serde(flatten)]
keybinds: HashMap<OldInputMode, Vec<OldKeyActionUnbind>>,
#[serde(default)]
unbind: OldUnbind,
}
#[derive(Clone, Debug, PartialEq, Eq, Hash, Deserialize, Serialize)]
#[serde(untagged)]
enum OldUnbind {
// This is the correct order, don't rearrange!
// Suspected Bug in the untagged macro.
// 1. Keys
Keys(Vec<OldKey>),
// 2. All
All(bool),
}
impl Default for OldUnbind {
fn default() -> OldUnbind {
OldUnbind::All(false)
}
}
#[derive(Clone, Debug, PartialEq, Deserialize, Serialize)]
#[serde(untagged)]
enum OldKeyActionUnbind {
KeyAction(OldKeyActionFromYaml),
Unbind(OldUnbindFromYaml),
}
/// Intermediate struct used for deserialisation
#[derive(Clone, Debug, PartialEq, Deserialize, Serialize)]
struct OldKeyActionFromYaml {
action: Vec<OldAction>,
key: Vec<OldKey>,
}
#[derive(Clone, Debug, PartialEq, Deserialize, Serialize)]
struct OldUnbindFromYaml {
unbind: OldUnbind,
}
/// Main configuration.
#[derive(Debug, Clone, PartialEq, Deserialize)]
struct OldConfig {
pub keybinds: OldKeybinds,
pub options: OldOptions,
pub themes: Option<OldThemesFromYamlIntermediate>,
pub plugins: OldPluginsConfig,
pub ui: Option<OldUiConfigFromYaml>,
pub env: OldEnvironmentVariablesFromYaml,
}
#[derive(Clone, Debug, PartialEq, Deserialize, Serialize)]
struct OldKeybinds(HashMap<OldInputMode, OldModeKeybinds>);
#[derive(Clone, Debug, PartialEq, Deserialize, Serialize)]
struct OldModeKeybinds(BTreeMap<OldKey, Vec<OldAction>>);
#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
pub struct OldThemesFromYamlIntermediate(HashMap<String, OldTheme>);
#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq, Hash, Default)]
struct OldPaletteFromYaml {
pub fg: OldPaletteColorFromYaml,
pub bg: OldPaletteColorFromYaml,
pub black: OldPaletteColorFromYaml,
pub red: OldPaletteColorFromYaml,
pub green: OldPaletteColorFromYaml,
pub yellow: OldPaletteColorFromYaml,
pub blue: OldPaletteColorFromYaml,
pub magenta: OldPaletteColorFromYaml,
pub cyan: OldPaletteColorFromYaml,
pub white: OldPaletteColorFromYaml,
pub orange: OldPaletteColorFromYaml,
}
/// Intermediate deserialization enum
// This is here in order to make the untagged enum work
#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq, Hash)]
#[serde(untagged)]
enum OldPaletteColorFromYaml {
Rgb((u8, u8, u8)),
EightBit(u8),
Hex(OldHexColor),
}
impl From<OldHexColor> for (u8, u8, u8) {
fn from(e: OldHexColor) -> (u8, u8, u8) {
let OldHexColor(r, g, b) = e;
(r, g, b)
}
}
struct OldHexColorVisitor();
impl<'de> Visitor<'de> for OldHexColorVisitor {
type Value = OldHexColor;
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
write!(formatter, "a hex color in the format #RGB or #RRGGBB")
}
fn visit_str<E>(self, s: &str) -> Result<Self::Value, E>
where
E: Error,
{
if let Some(stripped) = s.strip_prefix('#') {
return self.visit_str(stripped);
}
if s.len() == 3 {
Ok(OldHexColor(
u8::from_str_radix(&s[0..1], 16).map_err(E::custom)? * 0x11,
u8::from_str_radix(&s[1..2], 16).map_err(E::custom)? * 0x11,
u8::from_str_radix(&s[2..3], 16).map_err(E::custom)? * 0x11,
))
} else if s.len() == 6 {
Ok(OldHexColor(
u8::from_str_radix(&s[0..2], 16).map_err(E::custom)?,
u8::from_str_radix(&s[2..4], 16).map_err(E::custom)?,
u8::from_str_radix(&s[4..6], 16).map_err(E::custom)?,
))
} else {
Err(Error::custom(
"Hex color must be of form \"#RGB\" or \"#RRGGBB\"",
))
}
}
}
impl<'de> Deserialize<'de> for OldHexColor {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
deserializer.deserialize_str(OldHexColorVisitor())
}
}
impl Default for OldPaletteColorFromYaml {
fn default() -> Self {
OldPaletteColorFromYaml::EightBit(0)
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize)]
struct OldHexColor(u8, u8, u8);
#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
struct OldTheme {
#[serde(flatten)]
palette: OldPaletteFromYaml,
}
#[derive(Debug, Default, Clone, Copy, PartialEq, Deserialize, Serialize)]
pub struct OldUiConfigFromYaml {
pub pane_frames: OldFrameConfigFromYaml,
}
#[derive(Debug, Default, Clone, Copy, PartialEq, Deserialize, Serialize)]
pub struct OldFrameConfigFromYaml {
pub rounded_corners: bool,
}
#[derive(Debug, Default, Clone, PartialEq, Serialize, Deserialize)]
pub struct OldEnvironmentVariablesFromYaml {
env: HashMap<String, String>,
}
#[derive(Clone, Debug, Default, PartialEq, Deserialize, Serialize)]
pub struct OldPluginsConfigFromYaml(Vec<OldPluginConfigFromYaml>);
#[derive(Clone, Debug, Default, PartialEq, Deserialize, Serialize)]
struct OldPluginConfigFromYaml {
pub path: PathBuf,
pub tag: OldPluginTag,
#[serde(default)]
pub run: OldPluginTypeFromYaml,
#[serde(default)]
pub config: serde_yaml::Value,
#[serde(default)]
pub _allow_exec_host_cmd: bool,
}
#[derive(Clone, Debug, PartialEq, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case")]
enum OldPluginTypeFromYaml {
Headless,
Pane,
}
impl Default for OldPluginTypeFromYaml {
fn default() -> Self {
Self::Pane
}
}
/// Tag used to identify the plugin in layout and config yaml files
#[derive(Debug, Default, Clone, PartialEq, Eq, Hash, Deserialize, Serialize)]
struct OldPluginTag(String);
#[derive(Clone, Debug, PartialEq, Deserialize, Serialize)]
struct OldPluginsConfig(HashMap<OldPluginTag, OldPluginConfig>);
#[derive(Clone, Debug, PartialEq, Deserialize, Serialize)]
struct OldPluginConfig {
/// Path of the plugin, see resolve_wasm_bytes for resolution semantics
pub path: PathBuf,
/// Plugin type
pub run: OldPluginType,
/// Allow command execution from plugin
pub _allow_exec_host_cmd: bool,
/// Original location of the
pub location: OldRunPluginLocation,
}
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq)]
enum OldRunPluginLocation {
File(PathBuf),
Zellij(OldPluginTag),
}
#[derive(Clone, Debug, PartialEq, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case")]
enum OldPluginType {
/// Starts immediately when Zellij is started and runs without a visible pane
Headless,
/// Runs once per pane declared inside a layout file
Pane(Option<usize>), // tab_index
}
#[derive(Copy, Clone, Debug, PartialEq, Deserialize, Serialize)]
pub enum OldOnForceClose {
#[serde(alias = "quit")]
Quit,
#[serde(alias = "detach")]
Detach,
}
impl std::fmt::Display for OldOnForceClose {
fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
match self {
Self::Quit => write!(f, "quit"),
Self::Detach => write!(f, "detach"),
}
}
}
impl Default for OldOnForceClose {
fn default() -> Self {
Self::Detach
}
}
#[derive(Deserialize, Serialize, Debug, Clone, Copy, PartialEq)]
pub enum OldClipboard {
#[serde(alias = "system")]
System,
#[serde(alias = "primary")]
Primary,
}
impl std::fmt::Display for OldClipboard {
fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
match self {
Self::System => write!(f, "system"),
Self::Primary => write!(f, "primary"),
}
}
}
impl Default for OldClipboard {
fn default() -> Self {
Self::System
}
}
#[derive(Clone, Default, Debug, PartialEq, Deserialize, Serialize)]
pub struct OldOptions {
#[serde(default)]
pub simplified_ui: Option<bool>,
pub theme: Option<String>,
pub default_mode: Option<OldInputMode>,
pub default_shell: Option<PathBuf>,
pub default_layout: Option<PathBuf>,
pub layout_dir: Option<PathBuf>,
pub theme_dir: Option<PathBuf>,
#[serde(default)]
pub mouse_mode: Option<bool>,
#[serde(default)]
pub pane_frames: Option<bool>,
#[serde(default)]
pub mirror_session: Option<bool>,
pub on_force_close: Option<OldOnForceClose>,
pub scroll_buffer_size: Option<usize>,
#[serde(default)]
pub copy_command: Option<String>,
#[serde(default)]
pub copy_clipboard: Option<OldClipboard>,
#[serde(default)]
pub copy_on_select: Option<bool>,
pub scrollback_editor: Option<PathBuf>,
}
/// Describes the different input modes, which change the way that keystrokes will be interpreted.
#[derive(Debug, PartialEq, Eq, Hash, Copy, Clone, Serialize, Deserialize)]
pub enum OldInputMode {
/// In `Normal` mode, input is always written to the terminal, except for the shortcuts leading
/// to other modes
#[serde(alias = "normal")]
Normal,
/// In `Locked` mode, input is always written to the terminal and all shortcuts are disabled
/// except the one leading back to normal mode
#[serde(alias = "locked")]
Locked,
/// `Resize` mode allows resizing the different existing panes.
#[serde(alias = "resize")]
Resize,
/// `Pane` mode allows creating and closing panes, as well as moving between them.
#[serde(alias = "pane")]
Pane,
/// `Tab` mode allows creating and closing tabs, as well as moving between them.
#[serde(alias = "tab")]
Tab,
/// `Scroll` mode allows scrolling up and down within a pane.
#[serde(alias = "scroll")]
Scroll,
/// `EnterSearch` mode allows for typing in the needle for a search in the scroll buffer of a pane.
#[serde(alias = "entersearch")]
EnterSearch,
/// `Search` mode allows for searching a term in a pane (superset of `Scroll`).
#[serde(alias = "search")]
Search,
/// `RenameTab` mode allows assigning a new name to a tab.
#[serde(alias = "renametab")]
RenameTab,
/// `RenamePane` mode allows assigning a new name to a pane.
#[serde(alias = "renamepane")]
RenamePane,
/// `Session` mode allows detaching sessions
#[serde(alias = "session")]
Session,
/// `Move` mode allows moving the different existing panes within a tab
#[serde(alias = "move")]
Move,
/// `Prompt` mode allows interacting with active prompts.
#[serde(alias = "prompt")]
Prompt,
/// `Tmux` mode allows for basic tmux keybindings functionality
#[serde(alias = "tmux")]
Tmux,
}
impl std::fmt::Display for OldInputMode {
fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
match self {
Self::Normal => write!(f, "normal"),
Self::Locked => write!(f, "locked"),
Self::Resize => write!(f, "resize"),
Self::Pane => write!(f, "pane"),
Self::Tab => write!(f, "tab"),
Self::Scroll => write!(f, "scroll"),
Self::EnterSearch => write!(f, "entersearch"),
Self::Search => write!(f, "search"),
Self::RenameTab => write!(f, "RenameTab"),
Self::RenamePane => write!(f, "RenamePane"),
Self::Session => write!(f, "session"),
Self::Move => write!(f, "move"),
Self::Prompt => write!(f, "prompt"),
Self::Tmux => write!(f, "tmux"),
}
}
}
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, Serialize, Deserialize, PartialOrd, Ord)]
enum OldKey {
PageDown,
PageUp,
Left,
Down,
Up,
Right,
Home,
End,
Backspace,
Delete,
Insert,
F(u8),
Char(char),
Alt(OldCharOrArrow),
Ctrl(char),
BackTab,
Null,
Esc,
}
impl std::fmt::Display for OldKey {
fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
match self {
Self::PageDown => write!(f, "PageDown"),
Self::PageUp => write!(f, "PageUp"),
Self::Left => write!(f, "Left"),
Self::Down => write!(f, "Down"),
Self::Up => write!(f, "Up"),
Self::Right => write!(f, "Right"),
Self::Home => write!(f, "Home"),
Self::End => write!(f, "End"),
Self::Backspace => write!(f, "Backspace"),
Self::Delete => write!(f, "Delete"),
Self::Insert => write!(f, "Insert"),
Self::F(index) => write!(f, "F{}", index),
Self::Char(c) => match c {
'\n' => write!(f, "Enter"),
'\t' => write!(f, "Tab"),
'\"' => write!(f, "\\\""), // make sure it is escaped because otherwise it will be
// seen as a KDL string starter/terminator
' ' => write!(f, "Space"),
_ => write!(f, "{}", c),
},
Self::Alt(char_or_arrow) => match char_or_arrow {
OldCharOrArrow::Char(c) => write!(f, "Alt {}", c),
OldCharOrArrow::Direction(direction) => match direction {
OldDirection::Left => write!(f, "Alt Left"),
OldDirection::Right => write!(f, "Alt Right"),
OldDirection::Up => write!(f, "Alt Up"),
OldDirection::Down => write!(f, "Alt Down"),
},
},
Self::Ctrl(c) => write!(f, "Ctrl {}", c),
Self::BackTab => write!(f, "Tab"),
Self::Null => write!(f, "Null"),
Self::Esc => write!(f, "Esc"),
}
}
}
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, Serialize, Deserialize, PartialOrd, Ord)]
#[serde(untagged)]
enum OldCharOrArrow {
Char(char),
Direction(OldDirection),
}
/// The four directions (left, right, up, down).
#[derive(Eq, Clone, Copy, Debug, PartialEq, Hash, Deserialize, Serialize, PartialOrd, Ord)]
enum OldDirection {
Left,
Right,
Up,
Down,
}
impl std::fmt::Display for OldDirection {
fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
match self {
Self::Left => write!(f, "Left"),
Self::Right => write!(f, "Right"),
Self::Up => write!(f, "Up"),
Self::Down => write!(f, "Down"),
}
}
}
impl Default for OldDirection {
fn default() -> Self {
OldDirection::Left
}
}
#[derive(Clone, Debug, PartialEq, Eq, Deserialize, Serialize)]
enum OldAction {
Quit,
Write(Vec<u8>),
WriteChars(String),
SwitchToMode(OldInputMode),
Resize(OldResizeDirection),
FocusNextPane,
FocusPreviousPane,
SwitchFocus,
MoveFocus(OldDirection),
MoveFocusOrTab(OldDirection),
MovePane(Option<OldDirection>),
DumpScreen(String),
EditScrollback,
ScrollUp,
ScrollUpAt(OldPosition),
ScrollDown,
ScrollDownAt(OldPosition),
ScrollToBottom,
PageScrollUp,
PageScrollDown,
HalfPageScrollUp,
HalfPageScrollDown,
ToggleFocusFullscreen,
TogglePaneFrames,
ToggleActiveSyncTab,
NewPane(Option<OldDirection>),
TogglePaneEmbedOrFloating,
ToggleFloatingPanes,
CloseFocus,
PaneNameInput(Vec<u8>),
UndoRenamePane,
NewTab(Option<OldTabLayout>),
NoOp,
GoToNextTab,
GoToPreviousTab,
CloseTab,
GoToTab(u32),
ToggleTab,
TabNameInput(Vec<u8>),
UndoRenameTab,
Run(OldRunCommandAction),
Detach,
LeftClick(OldPosition),
RightClick(OldPosition),
MiddleClick(OldPosition),
LeftMouseRelease(OldPosition),
RightMouseRelease(OldPosition),
MiddleMouseRelease(OldPosition),
MouseHoldLeft(OldPosition),
MouseHoldRight(OldPosition),
MouseHoldMiddle(OldPosition),
Copy,
Confirm,
Deny,
SkipConfirm(Box<OldAction>),
SearchInput(Vec<u8>),
Search(OldSearchDirection),
SearchToggleOption(OldSearchOption),
}
impl std::fmt::Display for OldAction {
fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
match self {
Self::Quit => write!(f, "Quit"),
Self::Write(bytes) => write!(
f,
"Write {}",
bytes
.iter()
.map(|c| format!("{}", *c))
.collect::<Vec<String>>()
.join(" ")
),
Self::WriteChars(chars) => write!(f, "WriteChars \"{}\"", chars),
Self::SwitchToMode(input_mode) => write!(f, "SwitchToMode \"{}\"", input_mode),
Self::Resize(resize_direction) => write!(f, "Resize \"{}\"", resize_direction),
Self::FocusNextPane => write!(f, "FocusNextPane"),
Self::FocusPreviousPane => write!(f, "FocusPreviousPane"),
Self::SwitchFocus => write!(f, "SwitchFocus"),
Self::MoveFocus(direction) => write!(f, "MoveFocus \"{}\"", direction),
Self::MoveFocusOrTab(direction) => write!(f, "MoveFocusOrTab \"{}\"", direction),
Self::MovePane(direction) => match direction {
Some(direction) => write!(f, "MovePane \"{}\"", direction),
None => write!(f, "MovePane"),
},
Self::DumpScreen(file) => write!(f, "DumpScreen \"{}\"", file),
Self::EditScrollback => write!(f, "EditScrollback"),
Self::ScrollUp => write!(f, "ScrollUp"),
Self::ScrollDown => write!(f, "ScrollDown"),
Self::ScrollToBottom => write!(f, "ScrollToBottom"),
Self::PageScrollUp => write!(f, "PageScrollUp"),
Self::PageScrollDown => write!(f, "PageScrollDown"),
Self::HalfPageScrollUp => write!(f, "HalfPageScrollUp"),
Self::HalfPageScrollDown => write!(f, "HalfPageScrollDown"),
Self::ToggleFocusFullscreen => write!(f, "ToggleFocusFullscreen"),
Self::TogglePaneFrames => write!(f, "TogglePaneFrames"),
Self::ToggleActiveSyncTab => write!(f, "ToggleActiveSyncTab"),
Self::NewPane(direction) => match direction {
Some(direction) => write!(f, "NewPane \"{}\"", direction),
None => write!(f, "NewPane"),
},
Self::TogglePaneEmbedOrFloating => write!(f, "TogglePaneEmbedOrFloating"),
Self::ToggleFloatingPanes => write!(f, "ToggleFloatingPanes"),
Self::CloseFocus => write!(f, "CloseFocus"),
Self::PaneNameInput(bytes) => write!(
f,
"PaneNameInput {}",
bytes
.iter()
.map(|c| format!("{}", *c))
.collect::<Vec<String>>()
.join(" ")
),
Self::UndoRenamePane => write!(f, "UndoRenamePane"),
Self::NewTab(_) => write!(f, "NewTab"),
Self::NoOp => write!(f, "NoOp"),
Self::GoToNextTab => write!(f, "GoToNextTab"),
Self::GoToPreviousTab => write!(f, "GoToPreviousTab"),
Self::CloseTab => write!(f, "CloseTab"),
Self::GoToTab(index) => write!(f, "GoToTab {}", index),
Self::ToggleTab => write!(f, "ToggleTab"),
// Self::TabNameInput(bytes) => write!(f, "TabNameInput {}", format!("{}", bytes.iter().map(|c| format!("{}", *c)).collect::<Vec<String>>().join(" "))),
Self::TabNameInput(bytes) => write!(
f,
"TabNameInput {}",
bytes
.iter()
.map(|c| format!("{}", *c))
.collect::<Vec<String>>()
.join(" ")
),
Self::UndoRenameTab => write!(f, "UndoRenameTab"),
Self::Run(run_command_action) => {
let mut run_block_serialized = format!("Run {:?}", run_command_action.command);
for arg in &run_command_action.args {
run_block_serialized.push_str(&format!(" \"{}\"", arg));
}
match (&run_command_action.cwd, run_command_action.direction) {
(Some(cwd), Some(direction)) => {
run_block_serialized.push_str(&format!(
"{{ cwd {:?}; direction \"{}\"; }}",
cwd, direction
));
},
(None, Some(direction)) => {
run_block_serialized
.push_str(&format!("{{ direction \"{}\"; }}", direction));
},
(Some(cwd), None) => {
run_block_serialized.push_str(&format!("{{ cwd {:?}; }}", cwd));
},
(None, None) => {},
}
write!(f, "{}", run_block_serialized)
},
Self::Detach => write!(f, "Detach"),
Self::Copy => write!(f, "Copy"),
Self::Confirm => write!(f, "Confirm"),
Self::Deny => write!(f, "Deny"),
Self::SearchInput(bytes) => write!(
f,
"SearchInput {}",
bytes
.iter()
.map(|c| format!("{}", *c))
.collect::<Vec<String>>()
.join(" ")
),
Self::Search(direction) => write!(f, "Search \"{}\"", direction),
Self::SearchToggleOption(option) => write!(f, "SearchToggleOption \"{}\"", option),
_ => Err(std::fmt::Error),
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Deserialize, Serialize)]
enum OldSearchDirection {
Down,
Up,
}
impl std::fmt::Display for OldSearchDirection {
fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
match self {
Self::Down => write!(f, "Down"),
Self::Up => write!(f, "Up"),
}
}
}
#[derive(Clone, Debug, PartialEq, Eq, Deserialize, Serialize)]
enum OldSearchOption {
CaseSensitivity,
WholeWord,
Wrap,
}
impl std::fmt::Display for OldSearchOption {
fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
match self {
Self::CaseSensitivity => write!(f, "CaseSensitivity"),
Self::WholeWord => write!(f, "WholeWord"),
Self::Wrap => write!(f, "Wrap"),
}
}
}
#[derive(Clone, Debug, PartialEq, Eq, Deserialize, Serialize)]
enum OldResizeDirection {
Left,
Right,
Up,
Down,
Increase,
Decrease,
}
impl std::fmt::Display for OldResizeDirection {
fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
match self {
Self::Left => write!(f, "Left"),
Self::Right => write!(f, "Right"),
Self::Up => write!(f, "Up"),
Self::Down => write!(f, "Down"),
Self::Increase => write!(f, "Increase"),
Self::Decrease => write!(f, "Decrease"),
}
}
}
#[derive(Debug, Hash, Copy, Clone, PartialEq, Eq, PartialOrd, Deserialize, Serialize)]
struct OldPosition {
pub line: OldLine,
pub column: OldColumn,
}
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, Deserialize, Serialize, PartialOrd)]
struct OldLine(pub isize);
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, Deserialize, Serialize, PartialOrd)]
struct OldColumn(pub usize);
#[derive(Clone, Debug, Deserialize, Default, Serialize, PartialEq, Eq)]
struct OldRunCommandAction {
#[serde(rename = "cmd")]
pub command: PathBuf,
#[serde(default)]
pub args: Vec<String>,
#[serde(default)]
pub cwd: Option<PathBuf>,
#[serde(default)]
pub direction: Option<OldDirection>,
}
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq)]
struct OldTabLayout {
#[serde(default)]
pub direction: OldDirection,
pub pane_name: Option<String>,
#[serde(default)]
pub borderless: bool,
#[serde(default)]
pub parts: Vec<OldTabLayout>,
pub split_size: Option<OldSplitSize>,
#[serde(default)]
pub name: String,
pub focus: Option<bool>,
pub run: Option<OldRunFromYaml>,
}
#[derive(Debug, Serialize, Deserialize, Clone, Copy, PartialEq, Eq)]
enum OldSplitSize {
#[serde(alias = "percent")]
Percent(u64), // 1 to 100
#[serde(alias = "fixed")]
Fixed(usize), // An absolute number of columns or rows
}
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq)]
enum OldRunFromYaml {
#[serde(rename = "plugin")]
Plugin(OldRunPluginFromYaml),
#[serde(rename = "command")]
Command(OldRunCommand),
}
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq)]
struct OldRunPluginFromYaml {
#[serde(default)]
pub _allow_exec_host_cmd: bool,
pub location: Url,
}
#[derive(Clone, Debug, Deserialize, Default, Serialize, PartialEq, Eq)]
pub struct OldRunCommand {
#[serde(alias = "cmd")]
pub command: PathBuf,
#[serde(default)]
pub args: Vec<String>,
#[serde(default)]
pub cwd: Option<PathBuf>,
}
// The unit test location.
#[path = "./unit/convert_config_tests.rs"]
#[cfg(test)]
mod convert_config_test;
| true |
68fe71e77dae48c120540483951d543c62a1ee28
|
Rust
|
tomaka/acpi
|
/acpi/src/rsdp_search.rs
|
UTF-8
| 4,387 | 2.703125 | 3 |
[
"MIT",
"Apache-2.0"
] |
permissive
|
use crate::{parse_validated_rsdp, rsdp::Rsdp, Acpi, AcpiError, AcpiHandler};
use core::{mem, ops::RangeInclusive};
use log::warn;
/// The pointer to the EBDA (Extended Bios Data Area) start segment pointer
const EBDA_START_SEGMENT_PTR: usize = 0x40e;
/// The earliest (lowest) memory address an EBDA (Extended Bios Data Area) can start
const EBDA_EARLIEST_START: usize = 0x80000;
/// The end of the EBDA (Extended Bios Data Area)
const EBDA_END: usize = 0x9ffff;
/// The start of the main bios area below 1mb in which to search for the RSDP
/// (Root System Description Pointer)
const RSDP_BIOS_AREA_START: usize = 0xe0000;
/// The end of the main bios area below 1mb in which to search for the RSDP
/// (Root System Description Pointer)
const RSDP_BIOS_AREA_END: usize = 0xfffff;
/// The RSDP (Root System Description Pointer)'s signature, "RSD PTR " (note trailing space)
const RSDP_SIGNATURE: &'static [u8; 8] = b"RSD PTR ";
/// Find the begining of the EBDA (Extended Bios Data Area) and return `None` if the ptr at
/// `0x40e` is invalid.
pub fn find_search_areas<H>(handler: &mut H) -> [RangeInclusive<usize>; 2]
where
H: AcpiHandler,
{
// Read base segment from BIOS area. This is not always given by the bios, so it needs to be
// checked. We left shift 4 because it is a segment ptr.
let ebda_start_mapping = handler.map_physical_region::<u16>(EBDA_START_SEGMENT_PTR, mem::size_of::<u16>());
let ebda_start = (*ebda_start_mapping as usize) << 4;
handler.unmap_physical_region(ebda_start_mapping);
[
// Main bios area below 1 mb
// In practice (from my [Restioson's] testing, at least), the RSDP is more often here than
// the in EBDA. Also, if we cannot find the EBDA, then we don't want to search the largest
// possible EBDA first.
RSDP_BIOS_AREA_START..=RSDP_BIOS_AREA_END,
// Check if base segment ptr is in valid range for EBDA base
if (EBDA_EARLIEST_START..EBDA_END).contains(&ebda_start) {
// First kb of EBDA
ebda_start..=ebda_start + 1024
} else {
// We don't know where the EBDA starts, so just search the largest possible EBDA
EBDA_EARLIEST_START..=EBDA_END
},
]
}
/// This is the entry point of `acpi` if you have no information except that the machine is running
/// BIOS and not UEFI. It maps the RSDP, works out what version of ACPI the hardware supports, and
/// passes the physical address of the RSDT/XSDT to `parse_rsdt`.
///
/// # Unsafety
///
/// This function is unsafe because it may read from protected memory if the computer is using UEFI.
/// Only use this function if you are sure the computer is using BIOS.
pub unsafe fn search_for_rsdp_bios<H>(handler: &mut H) -> Result<Acpi, AcpiError>
where
H: AcpiHandler,
{
// The areas that will be searched for the RSDP
let areas = find_search_areas(handler);
// On x86 it is more efficient to map 4096 bytes at a time because of how paging works
let mut area_mapping = handler.map_physical_region::<[[u8; 8]; 0x1000 / 8]>(
areas[0].clone().next().unwrap() & !0xfff, // Get frame addr
0x1000,
);
// Signature is always on a 16 byte boundary so only search there
for address in areas.iter().flat_map(|i| i.clone()).step_by(16) {
let mut mapping_start = area_mapping.physical_start as usize;
if !(mapping_start..mapping_start + 0x1000).contains(&address) {
handler.unmap_physical_region(area_mapping);
area_mapping = handler.map_physical_region::<[[u8; 8]; 0x1000 / 8]>(
address & !0xfff, // Get frame addr
0x1000,
);
// Update if mapping remapped
mapping_start = area_mapping.physical_start as usize;
}
let index = (address - mapping_start) / 8;
let signature = (*area_mapping)[index];
if signature != *RSDP_SIGNATURE {
continue;
}
let rsdp_mapping = handler.map_physical_region::<Rsdp>(address, mem::size_of::<Rsdp>());
if let Err(e) = (*rsdp_mapping).validate() {
warn!("Invalid RSDP found at 0x{:x}: {:?}", address, e);
continue;
}
handler.unmap_physical_region(area_mapping);
return parse_validated_rsdp(handler, rsdp_mapping);
}
Err(AcpiError::NoValidRsdp)
}
| true |
950fd17b4fb01e7d8dfdcc5cc4543523ecc5fc5b
|
Rust
|
isabella232/BellmanBindings-iOS
|
/cargo/src/filesystem/mod.rs
|
UTF-8
| 849 | 2.703125 | 3 |
[] |
no_license
|
use std::fs::File;
use std::io::{BufReader, Read};
use std::error::Error;
use std::env;
use std::io::prelude::*;
use std::ffi::{CString, CStr};
use bellman::groth16::VerifyingKey;
use bellman::pairing::Engine;
pub extern fn get_verifying_key_from_file<E: Engine>(filename: String) -> Result<VerifyingKey<E>, Box<Error>> {
println!("Start opening file");
let file = match File::open(&filename) {
Err(error) => {
return Result::Err(Box::new(error))
},
Ok(string) => string,
};
println!("Opened file");
let reader = BufReader::new(file);
println!("Start reading");
let verifying_key = match VerifyingKey::read(reader) {
Err(error) => {
return Result::Err(Box::new(error))
},
Ok(vk) => vk,
};
println!("VK is ready");
Ok(verifying_key)
}
| true |
1dbc8c0371301b3667d809941430873ac7dcb80d
|
Rust
|
nervosnetwork/ckb
|
/util/occupied-capacity/core/src/units.rs
|
UTF-8
| 4,389 | 3.640625 | 4 |
[
"MIT"
] |
permissive
|
use serde::{Deserialize, Serialize};
/// CKB capacity.
///
/// It is encoded as the amount of `Shannons` internally.
#[derive(
Debug, Clone, Copy, Default, Hash, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize,
)]
pub struct Capacity(u64);
/// Represents the ratio `numerator / denominator`, where `numerator` and `denominator` are both
/// unsigned 64-bit integers.
#[derive(Clone, PartialEq, Debug, Eq, Copy, Deserialize, Serialize)]
pub struct Ratio {
/// Numerator.
numer: u64,
/// Denominator.
denom: u64,
}
impl Ratio {
/// Creates a ratio numer / denom.
pub const fn new(numer: u64, denom: u64) -> Self {
Self { numer, denom }
}
/// The numerator in ratio numerator / denominator.
pub fn numer(&self) -> u64 {
self.numer
}
/// The denominator in ratio numerator / denominator.
pub fn denom(&self) -> u64 {
self.denom
}
}
/// Conversion into `Capacity`.
pub trait IntoCapacity {
/// Converts `self` into `Capacity`.
fn into_capacity(self) -> Capacity;
}
impl IntoCapacity for Capacity {
fn into_capacity(self) -> Capacity {
self
}
}
impl IntoCapacity for u64 {
fn into_capacity(self) -> Capacity {
Capacity::shannons(self)
}
}
impl IntoCapacity for u32 {
fn into_capacity(self) -> Capacity {
Capacity::shannons(u64::from(self))
}
}
impl IntoCapacity for u16 {
fn into_capacity(self) -> Capacity {
Capacity::shannons(u64::from(self))
}
}
impl IntoCapacity for u8 {
fn into_capacity(self) -> Capacity {
Capacity::shannons(u64::from(self))
}
}
// A `Byte` contains how many `Shannons`.
const BYTE_SHANNONS: u64 = 100_000_000;
/// Numeric errors.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Error {
/// Numeric overflow.
Overflow,
}
impl ::std::fmt::Display for Error {
fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
write!(f, "OccupiedCapacity: overflow")
}
}
impl ::std::error::Error for Error {}
/// Numeric operation result.
pub type Result<T> = ::std::result::Result<T, Error>;
impl Capacity {
/// Capacity of zero Shannons.
pub const fn zero() -> Self {
Capacity(0)
}
/// Capacity of one Shannon.
pub const fn one() -> Self {
Capacity(1)
}
/// Views the capacity as Shannons.
pub const fn shannons(val: u64) -> Self {
Capacity(val)
}
/// Views the capacity as CKBytes.
pub fn bytes(val: usize) -> Result<Self> {
(val as u64)
.checked_mul(BYTE_SHANNONS)
.map(Capacity::shannons)
.ok_or(Error::Overflow)
}
/// Views the capacity as Shannons.
pub fn as_u64(self) -> u64 {
self.0
}
/// Adds self and rhs and checks overflow error.
pub fn safe_add<C: IntoCapacity>(self, rhs: C) -> Result<Self> {
self.0
.checked_add(rhs.into_capacity().0)
.map(Capacity::shannons)
.ok_or(Error::Overflow)
}
/// Subtracts self and rhs and checks overflow error.
pub fn safe_sub<C: IntoCapacity>(self, rhs: C) -> Result<Self> {
self.0
.checked_sub(rhs.into_capacity().0)
.map(Capacity::shannons)
.ok_or(Error::Overflow)
}
/// Multiplies self and rhs and checks overflow error.
pub fn safe_mul<C: IntoCapacity>(self, rhs: C) -> Result<Self> {
self.0
.checked_mul(rhs.into_capacity().0)
.map(Capacity::shannons)
.ok_or(Error::Overflow)
}
/// Multiplies self with a ratio and checks overflow error.
pub fn safe_mul_ratio(self, ratio: Ratio) -> Result<Self> {
self.0
.checked_mul(ratio.numer())
.and_then(|ret| ret.checked_div(ratio.denom()))
.map(Capacity::shannons)
.ok_or(Error::Overflow)
}
}
impl ::std::str::FromStr for Capacity {
type Err = ::std::num::ParseIntError;
fn from_str(s: &str) -> ::std::result::Result<Self, Self::Err> {
Ok(Capacity(s.parse::<u64>()?))
}
}
impl ::std::fmt::Display for Capacity {
fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
self.0.fmt(f)
}
}
impl ::std::fmt::LowerHex for Capacity {
fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
self.0.fmt(f)
}
}
| true |
7e3b470f29f8ba2370610a99c9140bd5ee95860b
|
Rust
|
bing050802/leetcode-rust-repo
|
/1566/main.rs
|
UTF-8
| 530 | 2.765625 | 3 |
[] |
no_license
|
impl Solution {
pub fn contains_pattern(arr: Vec<i32>, m: i32, k: i32) -> bool {
let n = arr.len();
if n < (m * k) as usize {
return false;
}
let end = n - (m * k) as usize;
let m = m as usize;
for i in 0..=end {
let mut res = true;
for j in 1..k as usize {
if arr[i..m + i] != arr[i + m * j..i + m * (j + 1)] {
res = false;
break;
}
}
if res {
return true;
}
}
false
}
}
| true |
16f887cc346fde67625a409d0edc25ebc6039ce1
|
Rust
|
rossmacarthur/sheldon
|
/src/lock/source/local.rs
|
UTF-8
| 2,014 | 3 | 3 |
[
"Apache-2.0",
"MIT"
] |
permissive
|
use std::path::PathBuf;
use anyhow::{anyhow, Result};
use crate::context::Context;
use crate::lock::source::LockedSource;
/// Checks that a Local source directory exists.
pub fn lock(ctx: &Context, dir: PathBuf) -> Result<LockedSource> {
let dir = ctx.expand_tilde(dir);
if dir.exists() && dir.is_dir() {
ctx.log_status("Checked", dir.as_path());
Ok(LockedSource { dir, file: None })
} else if let Ok(walker) = globwalk::glob(dir.to_string_lossy()) {
let mut directories: Vec<_> = walker
.filter_map(|result| match result {
Ok(entry) if entry.path().is_dir() => Some(entry.into_path()),
_ => None,
})
.collect();
if directories.len() == 1 {
let dir = directories.remove(0);
ctx.log_status("Checked", dir.as_path());
Ok(LockedSource { dir, file: None })
} else {
Err(anyhow!(
"`{}` matches {} directories",
dir.display(),
directories.len()
))
}
} else {
Err(anyhow!("`{}` is not a dir", dir.display()))
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::process::Command;
#[test]
fn lock_local() {
let temp = tempfile::tempdir().expect("create temporary directory");
let dir = temp.path();
let _ = git_clone_sheldon_test(&temp);
let locked = lock(&Context::testing(dir), dir.to_path_buf()).unwrap();
assert_eq!(locked.dir, dir);
assert_eq!(locked.file, None);
}
fn git_clone_sheldon_test(temp: &tempfile::TempDir) -> git2::Repository {
let dir = temp.path();
Command::new("git")
.arg("clone")
.arg("https://github.com/rossmacarthur/sheldon-test")
.arg(dir)
.output()
.expect("git clone rossmacarthur/sheldon-test");
git2::Repository::open(dir).expect("open sheldon-test git repository")
}
}
| true |
967892252e4dd2d45643b5e5d710b1f2d8bb27a5
|
Rust
|
tadic-luka/raymarching_sdf
|
/src/shader/mod.rs
|
UTF-8
| 6,398 | 2.59375 | 3 |
[] |
no_license
|
use gl::types::*;
use std::ptr;
use std::ffi::CString;
const GLSL_VERSION: &'static [u8] = b"#version 310 es\nprecision highp float;\n\0";
const VERTEX_SHADER_SOURCE: &'static str = include_str!("../../assets/shaders/main.vert");
const FRAGMENT_SHADER_SOURCE: &'static str = include_str!("../../assets/shaders/main.frag");
#[macro_export]
macro_rules! gen_uniforms {
(
$struct:ident,
$(
$name:ident, $fn_name:ident => $val:tt
),*
) => {
#[derive(Clone, Copy, Debug)]
struct Locs {
$(
$name: GLint,
)*
}
impl Locs {
fn get(prog: GLuint) -> Self {
Locs {
$(
$name: unsafe {
gl::GetUniformLocation(prog, concat!(stringify!($name), "\0").as_bytes().as_ptr() as _)
},
)*
}
}
}
impl $struct {
$(
pub fn $fn_name(&self, $name: $val) {
let _tmp_prog = self.use_program();
send_uniform_to_gl!(self.locs.$name, $val, $name);
}
)*
}
}
}
macro_rules! send_uniform_to_gl {
($loc:expr, [f32; 3], $value:ident) => {
let [x, y, z] = $value;
unsafe {
gl::Uniform3f($loc, x, y, z);
}
};
($loc:expr, [f32; 2], $value:ident) => {
let [x, y] = $value;
unsafe {
gl::Uniform2f($loc, x, y);
}
};
($loc:expr, f32, $value:ident) => {
unsafe {
gl::Uniform1f($loc, $value);
}
};
($loc:expr, bool, $value:ident) => {
let val = $value as _ ;
unsafe {
gl::Uniform1i($loc, val);
}
};
($loc:expr, i32, $value:ident) => {
let val = $value as _ ;
unsafe {
gl::Uniform1i($loc, val);
}
}
}
gen_uniforms!(
Program,
resolution, set_resolution => [f32; 2],
obj, set_obj => i32,
time, set_time => f32,
shininess, set_shininess => f32,
camera_eye, set_camera_eye => [f32; 3]
);
pub struct TmpProgram {
last_program: GLuint
}
impl Drop for TmpProgram {
#[inline(always)]
fn drop(&mut self) {
unsafe {
gl::UseProgram(self.last_program);
}
}
}
pub struct Program {
program: GLuint,
locs: Locs,
}
impl Drop for Program {
#[inline]
fn drop(&mut self) {
unsafe {
gl::DeleteProgram(self.program);
}
}
}
impl Program {
pub fn new() -> Result<Self, String> {
compile_shader::<VertShader>(VERTEX_SHADER_SOURCE)
.and_then(|vshader| compile_shader::<FragShader>(FRAGMENT_SHADER_SOURCE).map(|fshader| (vshader, fshader)))
.and_then(|(vshader, fshader)| create_shader_program(&[vshader, fshader]))
.map(|program| {
let prog = Program {
locs: Locs::get(program),
program,
};
prog
})
}
#[inline]
pub fn use_program(&self) -> TmpProgram {
let mut last_program: GLint = 0;
unsafe {
gl::GetIntegerv(gl::CURRENT_PROGRAM, &mut last_program);
gl::UseProgram(self.program);
}
TmpProgram {
last_program: last_program as GLuint,
}
}
}
struct VertShader{}
struct FragShader{}
trait Shader {
fn shader_type() -> GLenum;
}
impl Shader for VertShader {
fn shader_type() -> GLenum {
gl::VERTEX_SHADER
}
}
impl Shader for FragShader {
fn shader_type() -> GLenum {
gl::FRAGMENT_SHADER
}
}
#[derive(Copy, Clone)]
enum GlObj {
Shader,
Program,
}
impl GlObj {
fn get_info_log(&self, obj: GLuint, buf_size: GLsizei, length: *mut GLsizei, source: *mut GLchar) {
match self {
GlObj::Shader => unsafe { gl::GetShaderInfoLog(obj, buf_size, length, source) },
GlObj::Program => unsafe { gl::GetProgramInfoLog(obj, buf_size, length, source) },
}
}
}
fn get_gl_error(value: GLuint, variant: GlObj) -> Option<String>
where
{
unsafe {
let mut success = gl::FALSE as GLint;
match variant {
GlObj::Shader => gl::GetShaderiv(value, gl::COMPILE_STATUS, &mut success),
GlObj::Program => gl::GetProgramiv(value, gl::LINK_STATUS, &mut success),
}
if success == gl::FALSE as GLint {
let mut max_len: GLint = 0;
match variant {
GlObj::Shader => gl::GetShaderiv(value, gl::INFO_LOG_LENGTH, &mut max_len),
GlObj::Program => gl::GetProgramiv(value, gl::INFO_LOG_LENGTH, &mut max_len),
}
let mut info_log = vec![0; max_len as usize];
variant.get_info_log(
value,
max_len as _,
ptr::null_mut(),
info_log.as_mut_ptr() as *mut GLchar
);
info_log.pop();
return Some(format!(
"ERROR::SHADER::VERTEX::COMPILATION_FAILED\n{}",
std::str::from_utf8(&info_log).unwrap()
));
}
None
}
}
fn compile_shader<S: Shader>(shader_source: &str) -> Result<GLuint, String> {
unsafe {
let shader_source = CString::new(shader_source).unwrap();
let shader = gl::CreateShader(S::shader_type());
let sources = [
GLSL_VERSION.as_ptr() as *const GLchar,
shader_source.as_ptr() as *const GLchar,
];
let sources_len = [
GLSL_VERSION.len() as GLint -1,
shader_source.as_bytes().len() as GLint -1
];
gl::ShaderSource(shader, 2, sources.as_ptr(), sources_len.as_ptr());
gl::CompileShader(shader);
match get_gl_error(shader, GlObj::Shader) {
Some(err) => Err(err),
None => Ok(shader)
}
}
}
fn create_shader_program(shaders: &[GLuint]) -> Result<GLuint, String> {
unsafe {
let prog = gl::CreateProgram();
for shader in shaders {
gl::AttachShader(prog, *shader);
}
gl::LinkProgram(prog);
match get_gl_error(prog, GlObj::Program) {
Some(err) => Err(err),
None => Ok(prog),
}
}
}
| true |
078b00206d879834c279f0aa9f42f1d678027d23
|
Rust
|
rodya-mirov/aoc_2017
|
/src/day04.rs
|
UTF-8
| 1,361 | 3.40625 | 3 |
[] |
no_license
|
use std::collections::HashSet;
const INPUT: &str = include_str!("input/4.txt");
fn is_valid_4a(line: &str) -> bool {
let mut seen: HashSet<String> = HashSet::new();
for token in line.split_whitespace() {
if !seen.insert(token.to_string()) {
return false;
}
}
true
}
fn is_valid_4b(line: &str) -> bool {
let mut seen: HashSet<String> = HashSet::new();
for token in line.split_whitespace() {
let mut chars: Vec<char> = token.chars().collect();
chars.sort();
if !seen.insert(chars.into_iter().collect()) {
return false;
}
}
true
}
pub fn run_4a() -> usize {
INPUT.lines().filter(|line| is_valid_4a(line)).count()
}
pub fn run_4b() -> usize {
INPUT.lines().filter(|line| is_valid_4b(line)).count()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
pub fn samples_4a() {
assert!(is_valid_4a("aa bb cc dd ee"));
assert!(!is_valid_4a("aa bb cc dd aa"));
assert!(is_valid_4a("aa bb cc dd aaa"));
}
#[test]
pub fn samples_4b() {
assert!(is_valid_4b("abcde fghij"));
assert!(!is_valid_4b("abcde xyz ecdab"));
assert!(is_valid_4b("a ab abc abd abf abj"));
assert!(is_valid_4b("iiii oiii ooii oooi oooo"));
assert!(!is_valid_4b("oiii ioii iioi iiio"));
}
}
| true |
8f41612d7e52921d926f3979719f95b2a3c6578d
|
Rust
|
time-rs/time
|
/time/src/parsing/combinator/rfc/iso8601.rs
|
UTF-8
| 5,659 | 3.4375 | 3 |
[
"MIT",
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
//! Rules defined in [ISO 8601].
//!
//! [ISO 8601]: https://www.iso.org/iso-8601-date-and-time-format.html
use core::num::{NonZeroU16, NonZeroU8};
use crate::parsing::combinator::{any_digit, ascii_char, exactly_n_digits, first_match, sign};
use crate::parsing::ParsedItem;
use crate::{Month, Weekday};
/// What kind of format is being parsed. This is used to ensure each part of the format (date, time,
/// offset) is the same kind.
#[derive(Debug, Clone, Copy)]
pub(crate) enum ExtendedKind {
/// The basic format.
Basic,
/// The extended format.
Extended,
/// ¯\_(ツ)_/¯
Unknown,
}
impl ExtendedKind {
/// Is it possible that the format is extended?
pub(crate) const fn maybe_extended(self) -> bool {
matches!(self, Self::Extended | Self::Unknown)
}
/// Is the format known for certain to be extended?
pub(crate) const fn is_extended(self) -> bool {
matches!(self, Self::Extended)
}
/// If the kind is `Unknown`, make it `Basic`. Otherwise, do nothing. Returns `Some` if and only
/// if the kind is now `Basic`.
pub(crate) fn coerce_basic(&mut self) -> Option<()> {
match self {
Self::Basic => Some(()),
Self::Extended => None,
Self::Unknown => {
*self = Self::Basic;
Some(())
}
}
}
/// If the kind is `Unknown`, make it `Extended`. Otherwise, do nothing. Returns `Some` if and
/// only if the kind is now `Extended`.
pub(crate) fn coerce_extended(&mut self) -> Option<()> {
match self {
Self::Basic => None,
Self::Extended => Some(()),
Self::Unknown => {
*self = Self::Extended;
Some(())
}
}
}
}
/// Parse a possibly expanded year.
pub(crate) fn year(input: &[u8]) -> Option<ParsedItem<'_, i32>> {
Some(match sign(input) {
Some(ParsedItem(input, sign)) => exactly_n_digits::<6, u32>(input)?.map(|val| {
let val = val as i32;
if sign == b'-' { -val } else { val }
}),
None => exactly_n_digits::<4, u32>(input)?.map(|val| val as _),
})
}
/// Parse a month.
pub(crate) fn month(input: &[u8]) -> Option<ParsedItem<'_, Month>> {
first_match(
[
(b"01".as_slice(), Month::January),
(b"02".as_slice(), Month::February),
(b"03".as_slice(), Month::March),
(b"04".as_slice(), Month::April),
(b"05".as_slice(), Month::May),
(b"06".as_slice(), Month::June),
(b"07".as_slice(), Month::July),
(b"08".as_slice(), Month::August),
(b"09".as_slice(), Month::September),
(b"10".as_slice(), Month::October),
(b"11".as_slice(), Month::November),
(b"12".as_slice(), Month::December),
],
true,
)(input)
}
/// Parse a week number.
pub(crate) fn week(input: &[u8]) -> Option<ParsedItem<'_, NonZeroU8>> {
exactly_n_digits::<2, _>(input)
}
/// Parse a day of the month.
pub(crate) fn day(input: &[u8]) -> Option<ParsedItem<'_, NonZeroU8>> {
exactly_n_digits::<2, _>(input)
}
/// Parse a day of the week.
pub(crate) fn dayk(input: &[u8]) -> Option<ParsedItem<'_, Weekday>> {
first_match(
[
(b"1".as_slice(), Weekday::Monday),
(b"2".as_slice(), Weekday::Tuesday),
(b"3".as_slice(), Weekday::Wednesday),
(b"4".as_slice(), Weekday::Thursday),
(b"5".as_slice(), Weekday::Friday),
(b"6".as_slice(), Weekday::Saturday),
(b"7".as_slice(), Weekday::Sunday),
],
true,
)(input)
}
/// Parse a day of the year.
pub(crate) fn dayo(input: &[u8]) -> Option<ParsedItem<'_, NonZeroU16>> {
exactly_n_digits::<3, _>(input)
}
/// Parse the hour.
pub(crate) fn hour(input: &[u8]) -> Option<ParsedItem<'_, u8>> {
exactly_n_digits::<2, _>(input)
}
/// Parse the minute.
pub(crate) fn min(input: &[u8]) -> Option<ParsedItem<'_, u8>> {
exactly_n_digits::<2, _>(input)
}
/// Parse a floating point number as its integer and optional fractional parts.
///
/// The number must have two digits before the decimal point. If a decimal point is present, at
/// least one digit must follow.
///
/// The return type is a tuple of the integer part and optional fraction part.
pub(crate) fn float(input: &[u8]) -> Option<ParsedItem<'_, (u8, Option<f64>)>> {
// Two digits before the decimal.
let ParsedItem(input, integer_part) = match input {
[
first_digit @ b'0'..=b'9',
second_digit @ b'0'..=b'9',
input @ ..,
] => ParsedItem(input, (first_digit - b'0') * 10 + (second_digit - b'0')),
_ => return None,
};
if let Some(ParsedItem(input, ())) = decimal_sign(input) {
// Mandatory post-decimal digit.
let ParsedItem(mut input, mut fractional_part) =
any_digit(input)?.map(|digit| ((digit - b'0') as f64) / 10.);
let mut divisor = 10.;
// Any number of subsequent digits.
while let Some(ParsedItem(new_input, digit)) = any_digit(input) {
input = new_input;
divisor *= 10.;
fractional_part += (digit - b'0') as f64 / divisor;
}
Some(ParsedItem(input, (integer_part, Some(fractional_part))))
} else {
Some(ParsedItem(input, (integer_part, None)))
}
}
/// Parse a "decimal sign", which is either a comma or a period.
fn decimal_sign(input: &[u8]) -> Option<ParsedItem<'_, ()>> {
ascii_char::<b'.'>(input).or_else(|| ascii_char::<b','>(input))
}
| true |
74c067e14eab52dfdb517629c465cae85a1a35e6
|
Rust
|
ekarademir/rust-learning
|
/sdl2-base-project/src/rotatingwave/color.rs
|
UTF-8
| 10,880 | 2.703125 | 3 |
[] |
no_license
|
//! # `color`
//! Color related stuff, named colors and themes
#[allow(unused_imports)]
use sdl2::pixels::Color;
pub struct NamedColours;
impl NamedColours {
pub const WHITE: Color = Color {r: 255, g: 255, b: 255, a: 0xff};
pub const BLACK: Color = Color {r: 0, g: 0, b: 0, a: 0xff};
pub const RED: Color = Color {r: 255, g: 0, b: 0, a: 0xff};
pub const GREEN: Color = Color {r: 0, g: 255, b: 0, a: 0xff};
pub const BLUE: Color = Color {r: 0, g: 0, b: 255, a: 0xff};
pub const CYAN: Color = Color {r: 0, g: 255, b: 255, a: 0xff};
pub const YELLOW: Color = Color {r: 255, g: 255, b: 0, a: 0xff};
pub const MAGENTA: Color = Color {r: 255, g: 0, b: 255, a: 0xff};
pub const DARK_FUCHSIA: Color = Color {r: 74, g: 65, b: 95, a: 0xff};
pub const MATTE_FUCHSIA: Color = Color {r: 163, g: 103, b: 135, a: 0xff};
pub const MATTE_PISTACIO: Color = Color {r: 154, g: 202, b: 152, a: 0xff};
pub const LIGHT_WALNUT: Color = Color {r: 177, g: 171, b: 118, a: 0xff};
pub const LIGHT_PISTACIO: Color = Color {r: 222, g: 240, b: 177, a: 0xff};
// Web colors
pub const MAROON: Color = Color {r: 128, g: 0, b: 0, a: 0xff};
pub const DARK_RED: Color = Color {r: 139, g: 0, b: 0, a: 0xff};
pub const BROWN: Color = Color {r: 165, g: 42, b: 42, a: 0xff};
pub const FIREBRICK: Color = Color {r: 178, g: 34, b: 34, a: 0xff};
pub const CRIMSON: Color = Color {r: 220, g: 20, b: 60, a: 0xff};
pub const TOMATO: Color = Color {r: 255, g: 99, b: 71, a: 0xff};
pub const CORAL: Color = Color {r: 255, g: 127, b: 80, a: 0xff};
pub const INDIAN_RED: Color = Color {r: 205, g: 92, b: 92, a: 0xff};
pub const LIGHT_CORAL: Color = Color {r: 240, g: 128, b: 128, a: 0xff};
pub const DARK_SALMON: Color = Color {r: 233, g: 150, b: 122, a: 0xff};
pub const SALMON: Color = Color {r: 250, g: 128, b: 114, a: 0xff};
pub const LIGHT_SALMON: Color = Color {r: 255, g: 160, b: 122, a: 0xff};
pub const ORANGE_RED: Color = Color {r: 255, g: 69, b: 0, a: 0xff};
pub const DARK_ORANGE: Color = Color {r: 255, g: 140, b: 0, a: 0xff};
pub const ORANGE: Color = Color {r: 255, g: 165, b: 0, a: 0xff};
pub const GOLD: Color = Color {r: 255, g: 215, b: 0, a: 0xff};
pub const DARK_GOLDEN_ROD: Color = Color {r: 184, g: 134, b: 11, a: 0xff};
pub const GOLDEN_ROD: Color = Color {r: 218, g: 165, b: 32, a: 0xff};
pub const PALE_GOLDEN_ROD: Color = Color {r: 238, g: 232, b: 170, a: 0xff};
pub const DARK_KHAKI: Color = Color {r: 189, g: 183, b: 107, a: 0xff};
pub const KHAKI: Color = Color {r: 240, g: 230, b: 140, a: 0xff};
pub const OLIVE: Color = Color {r: 128, g: 128, b: 0, a: 0xff};
pub const YELLOW_GREEN: Color = Color {r: 154, g: 205, b: 50, a: 0xff};
pub const DARK_OLIVE_GREEN: Color = Color {r: 85, g: 107, b: 47, a: 0xff};
pub const OLIVE_DRAB: Color = Color {r: 107, g: 142, b: 35, a: 0xff};
pub const LAWN_GREEN: Color = Color {r: 124, g: 252, b: 0, a: 0xff};
pub const CHART_REUSE: Color = Color {r: 127, g: 255, b: 0, a: 0xff};
pub const GREEN_YELLOW: Color = Color {r: 173, g: 255, b: 47, a: 0xff};
pub const DARK_GREEN: Color = Color {r: 0, g: 100, b: 0, a: 0xff};
pub const FOREST_GREEN: Color = Color {r: 34, g: 139, b: 34, a: 0xff};
pub const LIME: Color = Color {r: 0, g: 255, b: 0, a: 0xff};
pub const LIME_GREEN: Color = Color {r: 50, g: 205, b: 50, a: 0xff};
pub const LIGHT_GREEN: Color = Color {r: 144, g: 238, b: 144, a: 0xff};
pub const PALE_GREEN: Color = Color {r: 152, g: 251, b: 152, a: 0xff};
pub const DARK_SEA_GREEN: Color = Color {r: 143, g: 188, b: 143, a: 0xff};
pub const MEDIUM_SPRING_GREEN: Color = Color {r: 0, g: 250, b: 154, a: 0xff};
pub const SPRING_GREEN: Color = Color {r: 0, g: 255, b: 127, a: 0xff};
pub const SEA_GREEN: Color = Color {r: 46, g: 139, b: 87, a: 0xff};
pub const MEDIUM_AQUA_MARINE: Color = Color {r: 102, g: 205, b: 170, a: 0xff};
pub const MEDIUM_SEA_GREEN: Color = Color {r: 60, g: 179, b: 113, a: 0xff};
pub const LIGHT_SEA_GREEN: Color = Color {r: 32, g: 178, b: 170, a: 0xff};
pub const DARK_SLATE_GRAY: Color = Color {r: 47, g: 79, b: 79, a: 0xff};
pub const TEAL: Color = Color {r: 0, g: 128, b: 128, a: 0xff};
pub const DARK_CYAN: Color = Color {r: 0, g: 139, b: 139, a: 0xff};
pub const AQUA: Color = Color {r: 0, g: 255, b: 255, a: 0xff};
pub const LIGHT_CYAN: Color = Color {r: 224, g: 255, b: 255, a: 0xff};
pub const DARK_TURQUOISE: Color = Color {r: 0, g: 206, b: 209, a: 0xff};
pub const TURQUOISE: Color = Color {r: 64, g: 224, b: 208, a: 0xff};
pub const MEDIUM_TURQUOISE: Color = Color {r: 72, g: 209, b: 204, a: 0xff};
pub const PALE_TURQUOISE: Color = Color {r: 175, g: 238, b: 238, a: 0xff};
pub const AQUA_MARINE: Color = Color {r: 127, g: 255, b: 212, a: 0xff};
pub const POWDER_BLUE: Color = Color {r: 176, g: 224, b: 230, a: 0xff};
pub const CADET_BLUE: Color = Color {r: 95, g: 158, b: 160, a: 0xff};
pub const STEEL_BLUE: Color = Color {r: 70, g: 130, b: 180, a: 0xff};
pub const CORN_FLOWER_BLUE: Color = Color {r: 100, g: 149, b: 237, a: 0xff};
pub const DEEP_SKY_BLUE: Color = Color {r: 0, g: 191, b: 255, a: 0xff};
pub const DODGER_BLUE: Color = Color {r: 30, g: 144, b: 255, a: 0xff};
pub const LIGHT_BLUE: Color = Color {r: 173, g: 216, b: 230, a: 0xff};
pub const SKY_BLUE: Color = Color {r: 135, g: 206, b: 235, a: 0xff};
pub const LIGHT_SKY_BLUE: Color = Color {r: 135, g: 206, b: 250, a: 0xff};
pub const MIDNIGHT_BLUE: Color = Color {r: 25, g: 25, b: 112, a: 0xff};
pub const NAVY: Color = Color {r: 0, g: 0, b: 128, a: 0xff};
pub const DARK_BLUE: Color = Color {r: 0, g: 0, b: 139, a: 0xff};
pub const MEDIUM_BLUE: Color = Color {r: 0, g: 0, b: 205, a: 0xff};
pub const ROYAL_BLUE: Color = Color {r: 65, g: 105, b: 225, a: 0xff};
pub const BLUE_VIOLET: Color = Color {r: 138, g: 43, b: 226, a: 0xff};
pub const INDIGO: Color = Color {r: 75, g: 0, b: 130, a: 0xff};
pub const DARK_SLATE_BLUE: Color = Color {r: 72, g: 61, b: 139, a: 0xff};
pub const SLATE_BLUE: Color = Color {r: 106, g: 90, b: 205, a: 0xff};
pub const MEDIUM_SLATE_BLUE: Color = Color {r: 123, g: 104, b: 238, a: 0xff};
pub const MEDIUM_PURPLE: Color = Color {r: 147, g: 112, b: 219, a: 0xff};
pub const DARK_MAGENTA: Color = Color {r: 139, g: 0, b: 139, a: 0xff};
pub const DARK_VIOLET: Color = Color {r: 148, g: 0, b: 211, a: 0xff};
pub const DARK_ORCHID: Color = Color {r: 153, g: 50, b: 204, a: 0xff};
pub const MEDIUM_ORCHID: Color = Color {r: 186, g: 85, b: 211, a: 0xff};
pub const PURPLE: Color = Color {r: 128, g: 0, b: 128, a: 0xff};
pub const THISTLE: Color = Color {r: 216, g: 191, b: 216, a: 0xff};
pub const PLUM: Color = Color {r: 221, g: 160, b: 221, a: 0xff};
pub const VIOLET: Color = Color {r: 238, g: 130, b: 238, a: 0xff};
pub const FUCHSIA: Color = Color {r: 255, g: 0, b: 255, a: 0xff};
pub const ORCHID: Color = Color {r: 218, g: 112, b: 214, a: 0xff};
pub const MEDIUM_VIOLET_RED: Color = Color {r: 199, g: 21, b: 133, a: 0xff};
pub const PALE_VIOLET_RED: Color = Color {r: 219, g: 112, b: 147, a: 0xff};
pub const DEEP_PINK: Color = Color {r: 255, g: 20, b: 147, a: 0xff};
pub const HOT_PINK: Color = Color {r: 255, g: 105, b: 180, a: 0xff};
pub const LIGHT_PINK: Color = Color {r: 255, g: 182, b: 193, a: 0xff};
pub const PINK: Color = Color {r: 255, g: 192, b: 203, a: 0xff};
pub const ANTIQUE_WHITE: Color = Color {r: 250, g: 235, b: 215, a: 0xff};
pub const BEIGE: Color = Color {r: 245, g: 245, b: 220, a: 0xff};
pub const BISQUE: Color = Color {r: 255, g: 228, b: 196, a: 0xff};
pub const BLANCHED_ALMOND: Color = Color {r: 255, g: 235, b: 205, a: 0xff};
pub const WHEAT: Color = Color {r: 245, g: 222, b: 179, a: 0xff};
pub const CORN_SILK: Color = Color {r: 255, g: 248, b: 220, a: 0xff};
pub const LEMON_CHIFFON: Color = Color {r: 255, g: 250, b: 205, a: 0xff};
pub const LIGHT_GOLDEN_ROD_YELLOW: Color = Color {r: 250, g: 250, b: 210, a: 0xff};
pub const LIGHT_YELLOW: Color = Color {r: 255, g: 255, b: 224, a: 0xff};
pub const SADDLE_BROWN: Color = Color {r: 139, g: 69, b: 19, a: 0xff};
pub const SIENNA: Color = Color {r: 160, g: 82, b: 45, a: 0xff};
pub const CHOCOLATE: Color = Color {r: 210, g: 105, b: 30, a: 0xff};
pub const PERU: Color = Color {r: 205, g: 133, b: 63, a: 0xff};
pub const SANDY_BROWN: Color = Color {r: 244, g: 164, b: 96, a: 0xff};
pub const BURLY_WOOD: Color = Color {r: 222, g: 184, b: 135, a: 0xff};
pub const TAN: Color = Color {r: 210, g: 180, b: 140, a: 0xff};
pub const ROSY_BROWN: Color = Color {r: 188, g: 143, b: 143, a: 0xff};
pub const MOCCASIN: Color = Color {r: 255, g: 228, b: 181, a: 0xff};
pub const NAVAJO_WHITE: Color = Color {r: 255, g: 222, b: 173, a: 0xff};
pub const PEACH_PUFF: Color = Color {r: 255, g: 218, b: 185, a: 0xff};
pub const MISTY_ROSE: Color = Color {r: 255, g: 228, b: 225, a: 0xff};
pub const LAVENDER_BLUSH: Color = Color {r: 255, g: 240, b: 245, a: 0xff};
pub const LINEN: Color = Color {r: 250, g: 240, b: 230, a: 0xff};
pub const OLD_LACE: Color = Color {r: 253, g: 245, b: 230, a: 0xff};
pub const PAPAYA_WHIP: Color = Color {r: 255, g: 239, b: 213, a: 0xff};
pub const SEA_SHELL: Color = Color {r: 255, g: 245, b: 238, a: 0xff};
pub const MINT_CREAM: Color = Color {r: 245, g: 255, b: 250, a: 0xff};
pub const SLATE_GRAY: Color = Color {r: 112, g: 128, b: 144, a: 0xff};
pub const LIGHT_SLATE_GRAY: Color = Color {r: 119, g: 136, b: 153, a: 0xff};
pub const LIGHT_STEEL_BLUE: Color = Color {r: 176, g: 196, b: 222, a: 0xff};
pub const LAVENDER: Color = Color {r: 230, g: 230, b: 250, a: 0xff};
pub const FLORAL_WHITE: Color = Color {r: 255, g: 250, b: 240, a: 0xff};
pub const ALICE_BLUE: Color = Color {r: 240, g: 248, b: 255, a: 0xff};
pub const GHOST_WHITE: Color = Color {r: 248, g: 248, b: 255, a: 0xff};
pub const HONEYDEW: Color = Color {r: 240, g: 255, b: 240, a: 0xff};
pub const IVORY: Color = Color {r: 255, g: 255, b: 240, a: 0xff};
pub const AZURE: Color = Color {r: 240, g: 255, b: 255, a: 0xff};
pub const SNOW: Color = Color {r: 255, g: 250, b: 250, a: 0xff};
pub const DIM_GRAY: Color = Color {r: 105, g: 105, b: 105, a: 0xff};
pub const GRAY: Color = Color {r: 128, g: 128, b: 128, a: 0xff};
pub const DARK_GRAY: Color = Color {r: 169, g: 169, b: 169, a: 0xff};
pub const SILVER: Color = Color {r: 192, g: 192, b: 192, a: 0xff};
pub const LIGHT_GRAY: Color = Color {r: 211, g: 211, b: 211, a: 0xff};
pub const GAINSBORO: Color = Color {r: 220, g: 220, b: 220, a: 0xff};
pub const WHITE_SMOKE: Color = Color {r: 245, g: 245, b: 245, a: 0xff};
}
| true |
52c4e284ecfa56201b7e25d111686a2344ac9748
|
Rust
|
bazaah/jaesve
|
/src/models/error.rs
|
UTF-8
| 8,573 | 3.03125 | 3 |
[
"MIT"
] |
permissive
|
use std::{
error, fmt::Debug, io::Error as ioError, process::exit as terminate, str::Utf8Error,
sync::mpsc::SendError,
};
#[cfg(feature = "config-file")]
use toml::de::Error as TomlError;
pub(crate) type Result<T> = std::result::Result<T, Error>;
#[derive(Debug)]
pub struct Error {
kind: ErrorKind,
context: Option<Context>,
}
// 1 => Program failed to correctly execute
// 2 => Thread panicked, potentially leaving OS resources in a dirty state
// 3 => Program partially parsed data but was closed unexpectedly
impl From<Error> for i32 {
fn from(err: Error) -> Self {
match err.kind {
ErrorKind::ThreadFailed => 2,
ErrorKind::ChannelError => 3,
_ => 1,
}
}
}
impl<E, C> From<(E, Option<C>)> for Error
where
E: Into<ErrorKind>,
C: Into<Context>,
{
fn from((err, context): (E, Option<C>)) -> Self {
Error {
kind: err.into(),
context: context.map(|c| c.into()),
}
}
}
impl<E> From<E> for Error
where
E: Into<ErrorKind>,
{
fn from(err: E) -> Self {
Error {
kind: err.into(),
context: None,
}
}
}
impl error::Error for Error {
fn source(&self) -> Option<&(dyn error::Error + 'static)> {
self.kind.source()
}
}
impl std::fmt::Display for Error {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
match self.context {
Some(ref con) => Error::display_with_context(&self.kind, con, f),
None => write!(f, "{}", self.kind),
}
}
}
impl Error {
fn display_with_context(
err: &ErrorKind,
con: &Context,
f: &mut std::fmt::Formatter,
) -> std::fmt::Result {
type E = ErrorKind;
type C = Context;
match (err, con) {
(E::Io(e), C::DataLenEqualLineBufferLen(s)) => {
write!(f, "Input line size is >= input buffer. Input buffer size is adjustable, try adding 'config --buf_in <num>' where <num> > {} (error: {})", s, e)
}
(E::ChannelError, C::UnexpectedMetaChannelClose(n)) => {
write!(f, "A meta channel ({}) closed unexpectedly, normally due to a SIGINT", n)
}
(E::ChannelError, C::UnexpectedDataChannelClose) => {
write!(f, "Unable to send next data packet, receiver quit unexpectedly. This may occur due to a SIGINT, or an internal error")
}
(E::ThreadFailed, C::ThreadPanic(n)) => {
write!(f, "Thread {} has panicked, this is mostly likely caused by an internal logic error, but could also be caused by an external OS error", n)
}
(e, _) => write!(f, "{}", e)
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Context {
Override(String),
DataLenEqualLineBufferLen(usize),
UnexpectedMetaChannelClose(String),
UnexpectedDataChannelClose,
ThreadPanic(String),
}
impl Context {
/// UnexpectedMetaChannelClose
pub fn umcc<T: std::fmt::Display>(recv_name: T) -> Option<Self> {
Some(Self::UnexpectedMetaChannelClose(format!(
"{} -> {}",
std::thread::current().name().unwrap_or("unnamed"),
recv_name
)))
}
/// UnexpectedDataChannelClose
pub fn udcc() -> Option<Self> {
Some(Self::UnexpectedDataChannelClose)
}
/// ThreadPanic
pub fn tp<T: std::fmt::Display>(thread_name: T) -> Option<Self> {
Some(Self::ThreadPanic(format!("{}", thread_name)))
}
/// DataLenEqualLineBufferLen
pub fn dlelbl(data_len: usize) -> Option<Self> {
Some(Context::DataLenEqualLineBufferLen(data_len))
}
}
impl<T: AsRef<str>> From<T> for Context {
fn from(s: T) -> Self {
Context::Override(s.as_ref().to_string())
}
}
/// Contains any error emitted by this program
#[derive(Debug)]
pub enum ErrorKind {
// Catch all
Generic,
Message(String),
// Handles in-thread panics
ThreadFailed,
// Handles fatal channel closes
ChannelError,
// Wrapper for any IO / Json serde errors
Io(ioError),
// For byte to str casts
UTF8(Utf8Error),
// Handles missing fields during output streaming
MissingField(String),
}
// IO Error => ErrorKind
impl From<ioError> for ErrorKind {
fn from(err: ioError) -> Self {
ErrorKind::Io(err)
}
}
// json Error => IO error => ErrorKind
impl From<serde_json::Error> for ErrorKind {
fn from(err: serde_json::Error) -> Self {
use serde_json::error::Category;
match err.classify() {
Category::Io | Category::Data | Category::Syntax | Category::Eof => {
ErrorKind::Io(err.into())
}
}
}
}
#[cfg(feature = "config-file")]
impl From<TomlError> for ErrorKind {
fn from(err: TomlError) -> Self {
ErrorKind::Io(err.into())
}
}
impl From<Utf8Error> for ErrorKind {
fn from(err: Utf8Error) -> Self {
ErrorKind::UTF8(err)
}
}
impl<T> From<SendError<T>> for ErrorKind {
fn from(_: SendError<T>) -> Self {
ErrorKind::ChannelError
}
}
// E => ErrorKind, where E implements Error
impl From<Box<dyn error::Error>> for ErrorKind {
fn from(e: Box<dyn error::Error>) -> Self {
ErrorKind::Message(format!("{}", e))
}
}
impl From<std::fmt::Error> for ErrorKind {
fn from(e: std::fmt::Error) -> Self {
ErrorKind::Message(format!("{}", e))
}
}
impl std::fmt::Display for ErrorKind {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
match self {
ErrorKind::Generic => write!(f, "Generic Error"),
ErrorKind::Message(m) => write!(f, "{}", m),
ErrorKind::ThreadFailed => write!(f, "A program thread has failed"),
ErrorKind::ChannelError => write!(f, "A channel quit unexpectedly"),
ErrorKind::Io(e) => write!(f, "An underlying IO error occurred: {}", e),
ErrorKind::UTF8(e) => write!(f, "Invalid or incomplete UTF-8: {}", e),
ErrorKind::MissingField(e) => write!(f, "Missing required field: {}", e),
}
}
}
impl error::Error for ErrorKind {
fn source(&self) -> Option<&(dyn error::Error + 'static)> {
match self {
ErrorKind::Io(e) => Some(e),
ErrorKind::UTF8(e) => Some(e),
_ => None,
}
}
}
pub(crate) trait ErrContext<T, E> {
fn context<C>(self, context: Option<C>) -> std::result::Result<T, (E, Option<C>)>;
}
impl<T, E> ErrContext<T, E> for std::result::Result<T, E> {
fn context<C>(self, context: Option<C>) -> std::result::Result<T, (E, Option<C>)> {
match self {
Ok(res) => Ok(res),
Err(err) => Err((err, context)),
}
}
}
/// Handles program return codes
pub(crate) enum ProgramExit<T>
where
T: error::Error,
{
Success,
Failure(T),
}
impl<T> ProgramExit<T>
where
T: Into<i32> + Debug + error::Error,
{
pub fn exit(self) -> ! {
match self {
Self::Success => terminate(0),
Self::Failure(err) => {
error!("Program exited with error: {}", err);
terminate(err.into())
}
}
}
}
impl From<Result<()>> for ProgramExit<Error> {
fn from(res: Result<()>) -> Self {
match res {
Ok(_) => ProgramExit::Success,
Err(e) => ProgramExit::Failure(e),
}
}
}
/*
// Unstable implementation that is much prettier and doesn't require a try_main()
// Once Termination + Try have been stabilized re-enable
// Option::None => ErrorKind
impl From<std::option::NoneError> for ErrorKind {
fn from(_: std::option::NoneError) -> Self {
ErrorKind::Generic
}
}
impl<T: Into<i32> + Debug + Error> Termination for ProgramExit<T> {
fn report(self) -> i32 {
match self {
ProgramExit::Success => 0,
ProgramExit::Failure(err) => {
error!("Program exited with error: {}", err);
err.into()
}
}
}
}
impl<T: Error> Try for ProgramExit<T> {
type Ok = ();
type Error = T;
fn into_result(self) -> std::result::Result<Self::Ok, Self::Error> {
match self {
ProgramExit::Success => Ok(()),
ProgramExit::Failure(err) => Err(err),
}
}
fn from_error(err: Self::Error) -> Self {
ProgramExit::Failure(err)
}
fn from_ok(_: Self::Ok) -> Self {
ProgramExit::Success
}
}
*/
| true |
ca16f9236310232a751288b52bc8f0e8f695d0f2
|
Rust
|
Hbowers/sneat
|
/src/sneat.rs
|
UTF-8
| 3,691 | 2.59375 | 3 |
[] |
no_license
|
use amethyst::{
core::transform::Transform,
input::{is_key_down, VirtualKeyCode},
prelude::*,
};
use serde::{Deserialize, Serialize};
use std::env;
use std::fs;
use std::path::PathBuf;
use crate::components::{Animation, Barrel, Coverable, Covers, Floor, Shape, Sneatling, Velocity};
use crate::constants::{ARENA_HEIGHT, ARENA_WIDTH};
use crate::entities::{barrel, camera, camera_focus, cover, floor, sneatling};
use crate::resources::assets;
pub struct Sneat;
pub struct Paused;
#[derive(Serialize, Deserialize)]
pub enum EntityType {
Sneatling,
Barrel,
}
#[derive(Serialize, Deserialize)]
pub struct EntityDetail {
entity_type: EntityType,
health: f32,
x: f32,
y: f32,
}
#[derive(Serialize, Deserialize)]
pub struct FloorDetail {
y: f32,
x_start: f32,
x_end: f32,
}
#[derive(Serialize, Deserialize)]
pub struct CoverDetail {
y: f32,
x_start: f32,
x_end: f32,
}
#[derive(Serialize, Deserialize)]
pub struct Level {
entities: Vec<EntityDetail>,
floors: Vec<FloorDetail>,
cover: Vec<CoverDetail>,
}
impl SimpleState for Sneat {
fn on_start(&mut self, data: StateData<'_, GameData<'_, '_>>) {
let world = data.world;
let mut app_root = env::current_exe().expect("Cannot get current path");
app_root.pop();
let level_path = app_root.join("levels").join("level_1.ron");
println!("Loading level 1 from: {:?}", level_path);
let s = fs::read_to_string(level_path).expect("Could not find file");
let level: Level = ron::de::from_str(&s).expect("ITS THIS ERROR");
let sneatling_sprite_sheet_handle =
assets::load_sprite_sheet_by_asset(world, assets::AssetType::Sneatling);
let environment_sprite_sheet_handle =
assets::load_sprite_sheet_by_asset(world, assets::AssetType::EnvironmentBlock);
let barrel_sprite_sheet_handle =
assets::load_sprite_sheet_by_asset(world, assets::AssetType::Barrel);
world.register::<Sneatling>();
world.register::<Velocity>();
world.register::<Barrel>();
world.register::<Floor>();
world.register::<Animation>();
world.register::<Shape>();
world.register::<Covers>();
world.register::<Coverable>();
let focus = camera_focus::initialise_camera_focus(
world,
ARENA_WIDTH * 0.5,
ARENA_HEIGHT * 0.5,
1.0,
);
camera::initialise_camera(world, focus, ARENA_WIDTH, ARENA_HEIGHT);
for floor in level.floors {
floor::initialise_flooring(
world,
floor.x_start,
floor.x_end,
floor.y,
environment_sprite_sheet_handle.clone(),
);
}
for cover in level.cover {
cover::initialise_covering(
world,
cover.x_start,
cover.x_end,
cover.y,
environment_sprite_sheet_handle.clone(),
);
}
for ent in level.entities {
match ent.entity_type {
EntityType::Sneatling => {
sneatling::initialise_sneatling(
world,
sneatling_sprite_sheet_handle.clone(),
ent.health,
);
}
EntityType::Barrel => {
barrel::initialise_barrel(
world,
(ent.x, ent.y),
barrel_sprite_sheet_handle.clone(),
);
}
}
}
}
}
| true |
26dc87890b82e7c24642f92afdc30d57803d7bd3
|
Rust
|
Mountlex/kserver
|
/serverlib/src/request.rs
|
UTF-8
| 2,548 | 3.796875 | 4 |
[] |
no_license
|
/// Represents a request for a server problem on the line.
///
/// A request consists of two parts: `s` and `t`. If `s==t`, the requests is called simple, other wise relocating.
/// For the k-server problem on the line, only simple requests are allowed. The k-taxi problem allows both types of requests.
/// If a server wants to server a request, it has to move to `s` and then gets relocated to `t`.
///
/// ## Examples
///
/// Requests can directly be derived from single integers or tuples:
/// ```
/// # use serversim::request::Request;
/// let simple_req = Request::from(4);
/// assert_eq!(Request::Simple(4.0), simple_req);
/// let relocation_req = Request::from((2,4));
/// assert_eq!(Request::Relocation(2.0, 4.0), relocation_req);
/// ```
#[derive(Copy, Clone, Debug, PartialEq)]
pub enum Request {
Simple(f32),
Relocation(f32, f32),
}
impl Request {
pub fn pos(&self) -> &f32 {
match self {
Request::Simple(x) => x,
Request::Relocation(x,_) => x,
}
}
pub fn is_simple(&self) -> bool {
matches!(*self, Request::Simple(_))
}
pub fn distance_to(&self, other: &f32) -> f32 {
match self {
Request::Simple(x) => (x - other).abs(),
Request::Relocation(_, y) => (y - other).abs(),
}
}
pub fn distance_to_req(&self, other: &Request) -> f32 {
let pos = other.distance_from(&0.0);
match self {
Request::Simple(x) => (x - pos).abs(),
Request::Relocation(_, y) => (y - pos).abs(),
}
}
pub fn distance_from(&self, other: &f32) -> f32 {
match self {
Request::Simple(x) => (x - other).abs(),
Request::Relocation(x, _) => (x - other).abs(),
}
}
}
impl std::fmt::Display for Request {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
match self {
Request::Simple(x) => write!(f, "{}", x),
Request::Relocation(x, y) => write!(f, "{}->{}", x, y),
}
}
}
impl From<f32> for Request {
fn from(pos: f32) -> Self {
Request::Simple(pos)
}
}
impl From<(f32, f32)> for Request {
fn from(relocation: (f32, f32)) -> Self {
Request::Relocation(relocation.0, relocation.1)
}
}
impl From<i32> for Request {
fn from(pos: i32) -> Self {
Request::Simple(pos as f32)
}
}
impl From<(i32, i32)> for Request {
fn from(relocation: (i32, i32)) -> Self {
Request::Relocation(relocation.0 as f32, relocation.1 as f32)
}
}
| true |
0e18ce803fcbbec19d4ec6258e472e3ace93d087
|
Rust
|
happyborg/gitoxide
|
/git-packetline/src/provider/read.rs
|
UTF-8
| 5,259 | 2.578125 | 3 |
[
"MIT",
"Apache-2.0"
] |
permissive
|
use crate::{
borrowed::{Band, Text},
PacketLine, Provider, MAX_DATA_LEN,
};
use std::io;
/// Note: Reading from this intermediary copies bytes 3 times:
/// OS -> (parent) line provider buffer -> our buffer -> caller's output buffer
pub struct ReadWithSidebands<'a, T, F>
where
T: io::Read,
{
parent: &'a mut Provider<T>,
handle_progress: Option<F>,
buf: Vec<u8>,
pos: usize,
cap: usize,
}
impl<'a, T, F> Drop for ReadWithSidebands<'a, T, F>
where
T: io::Read,
{
fn drop(&mut self) {
self.parent.reset();
}
}
impl<'a, T> ReadWithSidebands<'a, T, fn(bool, &[u8])>
where
T: io::Read,
{
pub fn new(parent: &'a mut Provider<T>) -> Self {
ReadWithSidebands {
parent,
handle_progress: None,
buf: vec![0; MAX_DATA_LEN],
pos: 0,
cap: 0,
}
}
}
impl<'a, T, F> ReadWithSidebands<'a, T, F>
where
T: io::Read,
F: FnMut(bool, &[u8]),
{
pub fn with_progress_handler(parent: &'a mut Provider<T>, handle_progress: F) -> Self {
ReadWithSidebands {
parent,
handle_progress: Some(handle_progress),
buf: vec![0; MAX_DATA_LEN],
pos: 0,
cap: 0,
}
}
pub fn without_progress_handler(parent: &'a mut Provider<T>) -> Self {
ReadWithSidebands {
parent,
handle_progress: None,
buf: vec![0; MAX_DATA_LEN],
pos: 0,
cap: 0,
}
}
pub fn reset_with(&mut self, delimiters: &'static [PacketLine<'static>]) {
self.parent.reset_with(delimiters)
}
pub fn stopped_at(&self) -> Option<PacketLine<'static>> {
self.parent.stopped_at
}
pub fn set_progress_handler(&mut self, handle_progress: Option<F>) {
self.handle_progress = handle_progress;
}
pub fn peek_data_line(&mut self) -> Option<io::Result<Result<&[u8], crate::decode::Error>>> {
match self.parent.peek_line() {
Some(Ok(Ok(line))) => match line {
crate::PacketLine::Data(line) => Some(Ok(Ok(line))),
_ => None,
},
Some(Ok(Err(err))) => Some(Ok(Err(err))),
Some(Err(err)) => Some(Err(err)),
None => None,
}
}
}
impl<'a, T, F> io::BufRead for ReadWithSidebands<'a, T, F>
where
T: io::Read,
F: FnMut(bool, &[u8]),
{
fn fill_buf(&mut self) -> io::Result<&[u8]> {
use io::Read;
if self.pos >= self.cap {
debug_assert!(self.pos == self.cap);
self.cap = loop {
let line = match self.parent.read_line() {
Some(line) => line?.map_err(|err| io::Error::new(io::ErrorKind::Other, err))?,
None => break 0,
};
match self.handle_progress.as_mut() {
Some(handle_progress) => {
let mut band = line
.decode_band()
.map_err(|err| io::Error::new(io::ErrorKind::Other, err))?;
match band {
Band::Data(ref mut d) => break d.read(&mut self.buf)?,
Band::Progress(d) => {
let text = Text::from(d).0;
handle_progress(false, text);
}
Band::Error(d) => {
let text = Text::from(d).0;
handle_progress(true, text);
}
};
}
None => {
break match line.as_slice() {
Some(ref mut d) => d.read(&mut self.buf)?,
None => {
return Err(io::Error::new(
io::ErrorKind::UnexpectedEof,
"encountered non-data line in a data-line only context",
))
}
}
}
}
};
self.pos = 0;
}
Ok(&self.buf[self.pos..self.cap])
}
fn consume(&mut self, amt: usize) {
self.pos = std::cmp::min(self.pos + amt, self.cap);
}
fn read_line(&mut self, buf: &mut String) -> io::Result<usize> {
assert_eq!(
self.cap, 0,
"we don't support partial buffers right now - read-line must be used consistently"
);
let line = std::str::from_utf8(self.fill_buf()?)
.map_err(|err| io::Error::new(io::ErrorKind::Other, err))
.unwrap();
buf.push_str(line);
let bytes = line.len();
self.cap = 0;
Ok(bytes)
}
}
impl<'a, T, F> io::Read for ReadWithSidebands<'a, T, F>
where
T: io::Read,
F: FnMut(bool, &[u8]),
{
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
use std::io::BufRead;
let nread = {
let mut rem = self.fill_buf()?;
rem.read(buf)?
};
self.consume(nread);
Ok(nread)
}
}
| true |
17b8a96a810a612acf9b4da9f725b1bafa031ca2
|
Rust
|
jsim2010/paper
|
/src/io/ui/error.rs
|
UTF-8
| 2,036 | 3.078125 | 3 |
[
"MIT"
] |
permissive
|
//! Implements errors thrown by the user interface.
#![allow(clippy::module_name_repetitions)] // It is appropriate for items to end with `Error`.
use {crossterm::ErrorKind, thiserror::Error as ThisError};
/// An error creating a [`Terminal`].
#[derive(Debug, ThisError)]
#[error(transparent)]
pub enum CreateTerminalError {
/// An error initializing the terminal output.
Init(#[from] InitError),
}
/// A failure consuming a [`UserAction`].
#[derive(Debug, market::ConsumeFault, ThisError)]
#[error(transparent)]
pub enum UserActionFailure {
/// A failure polling for a [`UserAction`].
Poll(#[from] PollFailure),
/// A failure reading a [`UserAction`].
Read(#[from] ReadFailure),
}
/// A failure producing terminal output.
#[derive(Debug, market::ProduceFault, ThisError)]
#[error(transparent)]
pub enum DisplayCmdFailure {
/// A failure writing text.
Write(#[from] WriteFailure),
/// A failure incrementing a row.
End(#[from] ReachedEnd),
}
/// A failure writing to stdout.
#[derive(Debug, ThisError)]
#[error("writing: {error}")]
pub struct WriteFailure {
/// The error.
#[from]
error: ErrorKind,
}
/// An error initializing the terminal.
#[derive(Debug, ThisError)]
#[error("clearing screen: {error}")]
pub struct InitError {
/// The error.
#[from]
error: ErrorKind,
}
/// An error polling for a [`UserAction`].
#[derive(Debug, ThisError)]
#[error("unable to poll: {error}")]
pub struct PollFailure {
/// The error.
#[from]
error: ErrorKind,
}
/// An error reading a [`UserAction`].
#[derive(Debug, ThisError)]
#[error("unable to read: {error}")]
pub struct ReadFailure {
/// The error.
#[from]
error: ErrorKind,
}
/// An error destroying the terminal.
#[derive(Debug, ThisError)]
#[error("leaving alternate screen: {error}")]
pub(crate) struct DestroyError {
/// The error.
#[from]
error: ErrorKind,
}
/// When the [`RowId`] has reached its end.
#[derive(Clone, Copy, Debug, ThisError)]
#[error("")]
pub struct ReachedEnd;
| true |
14c805397ea793cab15ec01b079aa5fd68dcce4d
|
Rust
|
vinc/level
|
/src/device.rs
|
UTF-8
| 164 | 2.53125 | 3 |
[
"MIT"
] |
permissive
|
use std::thread::JoinHandle;
pub trait Device {
fn name(&self) -> String;
fn level(&self) -> u64;
fn set_level(&self, level: u64) -> JoinHandle<()>;
}
| true |
ea43733c329dff20d4afaf2839601d6e9e249b64
|
Rust
|
travisjeffery/showrss-to-magnet
|
/src/main.rs
|
UTF-8
| 2,498 | 2.890625 | 3 |
[] |
no_license
|
use clap::{App, Arg};
use log::info;
use quick_xml::de::from_str;
use serde::Deserialize;
use std::fs::File;
use std::io::prelude::*;
use std::path::Path;
use std::{str, thread, time};
#[derive(Debug, Deserialize, PartialEq)]
struct Item {
title: String,
link: String,
guid: String,
}
#[derive(Debug, Deserialize, PartialEq)]
struct Channel {
#[serde(rename = "item", default)]
items: Vec<Item>,
}
#[derive(Debug, Deserialize, PartialEq)]
struct Rss {
channel: Channel,
}
fn main() -> Result<(), Box<dyn std::error::Error>> {
env_logger::init();
let matches = App::new("showrss-to-magnet")
.version("0.1.0")
.author("Travis Jeffery <[email protected]>")
.about("Download magnet files from showrss feed")
.arg(
Arg::with_name("dst")
.short("d")
.long("dst")
.takes_value(true)
.default_value("/tmp")
.env("DST")
.help("Directory to write magnet files"),
)
.arg(
Arg::with_name("rss")
.short("r")
.long("rss")
.takes_value(true)
.env("RSS")
.help("showrss rss url"),
)
.arg(
Arg::with_name("interval")
.short("i")
.long("interval")
.default_value("5")
.takes_value(true)
.env("INTERVAL")
.help("interval to process rss in seconds"),
)
.get_matches();
let dst = matches.value_of("dst").unwrap();
let dir = Path::new(dst);
let url = matches.value_of("rss").unwrap();
let i = matches
.value_of("interval")
.unwrap()
.parse::<u64>()
.unwrap();
let interval = time::Duration::from_secs(i);
info!("config dst: {}, rss: {}", dst, url);
loop {
info!("fetching rss");
let xml = reqwest::blocking::get(url)?.text()?;
let rss: Rss = from_str(&xml).unwrap_or_else(|error| {
panic!("{:?}: {}", error, xml);
});
for item in rss.channel.items.iter() {
let path = dir.join(format!("{}.magnet", item.guid));
if path.exists() {
continue;
}
let mut file = File::create(&path)?;
file.write_all(item.link.as_bytes())?;
info!("wrote: {}", path.display());
}
thread::sleep(interval);
}
}
| true |
6fa7d27ce96e86bf5ee63770a4e26d6a0d848d4e
|
Rust
|
lpenet/advent_of_code_2019
|
/2/2a.rs
|
UTF-8
| 1,084 | 3.09375 | 3 |
[] |
no_license
|
use std::fs;
fn main() {
let input_filename = "input.txt";
let content = fs::read_to_string(input_filename)
.expect(&format!("Something went wrong reading {}", input_filename));
let mut input_vector: Vec<u64> = content.split(",").map(str::parse::<u64>).filter_map(Result::ok).collect();
input_vector[1] = 12;
input_vector[2] = 2;
for cur_inst in 0..input_vector.len()/4 {
let cur_base_index = cur_inst*4;
let op_code = input_vector[cur_base_index];
let op1 = input_vector[input_vector[cur_base_index + 1] as usize];
let op2 = input_vector[input_vector[cur_base_index + 2] as usize];
let res;
if op_code == 1 {
res = op1 + op2;
} else if op_code == 2 {
res = op1 * op2;
} else if op_code == 99 {
break;
} else {
panic!(format!("unknown op code: {}", op_code));
}
let res_index = input_vector[cur_base_index + 3] as usize;
input_vector[res_index] = res;
}
println!("result: {}", input_vector[0]);
}
| true |
1111d7dc4379d0eb9e3edcca84c0a18f8989383c
|
Rust
|
tearne/library
|
/rust/20_command/src/bin/test.rs
|
UTF-8
| 333 | 2.90625 | 3 |
[] |
no_license
|
#![allow(unused)]
fn main() {
use std::process::{Command, Stdio};
use std::io::{self, Write};
let output = Command::new("rev")
.stdin(Stdio::inherit())
.stdout(Stdio::piped())
.output()
.expect("Failed to execute command");
print!("You piped in the reverse of: ");
io::stdout().write_all(&output.stdout).unwrap();
}
| true |
bbf665037e92751046724dd6f138a85b0f74e4d3
|
Rust
|
CommunityDragon/cdragon-rs
|
/cdragon-hashes/src/lib.rs
|
UTF-8
| 10,081 | 3.53125 | 4 |
[] |
no_license
|
//! Tools to work with hashes, as used by cdragon
//!
//! Actual hash values are created with [crate::define_hash_type!()], which implements [HashDef] and
//! conversions.
//!
//! [HashMapper] manages a mapping to retrieve a string from a hash value.
//! The type provides methods to load mapping files, check for known hashes, etc.
//! update mapping files, etc.
use std::fmt;
use std::fs::File;
use std::io::{BufReader, BufRead, BufWriter, Write};
use std::collections::HashMap;
use std::path::Path;
use std::hash::Hash;
use num_traits::Num;
use thiserror::Error;
use cdragon_utils::GuardedFile;
#[cfg(feature = "bin")]
pub mod bin;
#[cfg(feature = "wad")]
pub mod wad;
type Result<T, E = HashError> = std::result::Result<T, E>;
/// Hash related error
///
/// For now, it is only used when parsing hash mappings.
#[allow(missing_docs)]
#[derive(Error, Debug)]
pub enum HashError {
#[error(transparent)]
Io(#[from] std::io::Error),
#[error("invalid hash line: {0:?}")]
InvalidHashLine(String),
#[error("invalid hash value: {0:?}")]
InvalidHashValue(String),
}
/// Store hash-to-string association for a hash value
///
/// A hash mapping can be loaded from and written to files.
/// Such files store one line per hash, formatted as `<hex-value> <string>`.
#[derive(Default)]
pub struct HashMapper<T> where T: Hash {
map: HashMap<T, String>,
}
impl<T> HashMapper<T> where T: Eq + Hash + Copy {
/// Length of the hexadecimal representation of the hash
///
/// Always equal to two times the byte size of the hash value.
pub const HASH_HEX_LEN: usize = std::mem::size_of::<T>() * 2;
/// Create a new, empty mapping
pub fn new() -> Self {
Self { map: HashMap::<T, String>::new() }
}
/// Get a value from the mapping
pub fn get(&self, hash: T) -> Option<&str> {
self.map.get(&hash).map(|v| v.as_ref())
}
/// Return a matching string (if known) or the hash
///
/// Use this method to get a string representation with a fallback for unknown hashes.
/// ```
/// # use cdragon_hashes::HashMapper;
/// let mut mapper = HashMapper::<u16>::new();
/// mapper.insert(42, "forty-two".to_string());
/// assert_eq!(format!("{}", mapper.seek(42)), "forty-two");
/// assert_eq!(format!("{}", mapper.seek(0x1234)), "{1234}");
/// ```
pub fn seek(&self, hash: T) -> HashOrStr<T, &str> {
match self.map.get(&hash) {
Some(s) => HashOrStr::Str(s.as_ref()),
None => HashOrStr::Hash(hash),
}
}
/// Return `true` if the mapping is empty
pub fn is_empty(&self) -> bool {
self.map.is_empty()
}
/// Return `true` if the given hash is known
pub fn is_known(&self, hash: T) -> bool {
self.map.contains_key(&hash)
}
/// Add a hash to the mapper
///
/// **Important:** the caller must ensure the value matches the hash.
pub fn insert(&mut self, hash: T, value: String) {
self.map.insert(hash, value);
}
}
impl<T> HashMapper<T> where T: Num + Eq + Hash + Copy {
/// Create a new mapping, loaded from a reader
pub fn from_reader<R: BufRead>(reader: R) -> Result<Self> {
let mut this = Self::new();
this.load_reader(reader)?;
Ok(this)
}
/// Create a new mapping, loaded from a file
pub fn from_path<P: AsRef<Path>>(path: P) -> Result<Self> {
let mut this = Self::new();
this.load_path(&path)?;
Ok(this)
}
/// Load hash mapping from a reader
pub fn load_reader<R: BufRead>(&mut self, reader: R) -> Result<(), HashError> {
for line in reader.lines() {
let l = line?;
if l.len() < Self::HASH_HEX_LEN + 2 {
return Err(HashError::InvalidHashLine(l));
}
let hash = T::from_str_radix(&l[..Self::HASH_HEX_LEN], 16).map_err(|_e| {
HashError::InvalidHashValue(l[..Self::HASH_HEX_LEN].to_string())
})?;
self.map.insert(hash, l[Self::HASH_HEX_LEN+1..].to_string());
}
Ok(())
}
/// Load hash mapping from a file
pub fn load_path<P: AsRef<Path>>(&mut self, path: P) -> Result<()> {
let file = File::open(&path)?;
self.load_reader(BufReader::new(file))?;
Ok(())
}
}
impl<T> HashMapper<T> where T: Eq + Hash + Copy + fmt::LowerHex {
/// Write hash mapping to a writer
pub fn write<W: Write>(&self, writer: &mut W) -> std::io::Result<()> {
let mut entries: Vec<_> = self.map.iter().collect();
entries.sort_by_key(|kv| kv.1);
for (h, s) in entries {
writeln!(writer, "{:0w$x} {}", h, s, w = Self::HASH_HEX_LEN)?;
}
Ok(())
}
/// Write hash map to a file
///
/// File is upadeted atomically.
pub fn write_path<P: AsRef<Path>>(&self, path: P) -> std::io::Result<()> {
GuardedFile::for_scope(path, |file| {
self.write(&mut BufWriter::new(file))
})
}
}
/// Trait for hash values types
///
/// This trait is implemented by types created with [crate::define_hash_type!()].
pub trait HashDef: Sized {
/// Type of hash values (integer type)
type Hash: Sized;
/// Hashing method
const HASHER: fn(&str) -> Self::Hash;
/// Create a new hash value from an integer
fn new(hash: Self::Hash) -> Self;
/// Convert a string into a hash by hashing it
#[inline]
fn hashed(s: &str) -> Self {
Self::new(Self::HASHER(s))
}
/// Return true if hash is the null hash (0)
fn is_null(&self) -> bool;
}
/// Either a hash or its associated string
///
/// This enum is intended to be used along with a [HashMapper] for display.
/// If string is unknown, the hash value is written as `{hex-value}`
pub enum HashOrStr<H, S>
where H: Copy, S: AsRef<str> {
/// Hash value, string is unknown
Hash(H),
/// String value matching the hash
Str(S),
}
impl<H, S> fmt::Display for HashOrStr<H, S>
where H: Copy + fmt::LowerHex, S: AsRef<str> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
Self::Hash(h) => write!(f, "{{{:0w$x}}}", h, w = std::mem::size_of::<H>() * 2),
Self::Str(s) => write!(f, "{}", s.as_ref()),
}
}
}
/// Define a hash type wrapping an integer hash value
///
/// The created type provides
/// - a `hash` field, with the hash numeric value
/// - [HashDef] implementation
/// - conversion from a string, using the hasher method (`From<&str>` implementation that calls the hasher method
/// - implicit conversion from/to hash integer type (`From<T>`)
/// - [std::fmt::Debug] implementation
/// - [std::fmt::LowerHex] implementation
#[macro_export]
macro_rules! define_hash_type {
(
$(#[$meta:meta])*
$name:ident($T:ty) => $hasher:expr
) => {
$(#[$meta])*
#[derive(Default, PartialEq, Eq, PartialOrd, Ord, Hash, Copy, Clone)]
pub struct $name {
/// Hash value
pub hash: $T,
}
impl $crate::HashDef for $name {
type Hash = $T;
const HASHER: fn(&str) -> Self::Hash = $hasher;
#[inline]
fn new(hash: Self::Hash) -> Self {
Self { hash }
}
#[inline]
fn is_null(&self) -> bool {
self.hash == 0
}
}
impl From<$T> for $name {
fn from(v: $T) -> Self {
Self { hash: v }
}
}
impl std::fmt::Debug for $name {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(f, concat!(stringify!($name), "({:x})"), self)
}
}
impl std::fmt::LowerHex for $name {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(f, "{:0w$x}", self.hash, w = std::mem::size_of::<$T>() * 2)
}
}
}
}
/// Each kind of hash handled by CDragon
///
/// See also [bin::BinHashKind] for a kind limited to bin hashes.
#[derive(Debug, PartialEq, Eq, Hash, Copy, Clone)]
pub enum HashKind {
/// Hash for game WAD entries (`.wad.client`)
WadGame,
/// Hash for launcher WAD entries (`.wad`)
WadLcu,
/// Hash of an bin entry path
BinEntryPath,
/// Hash of a bin class name
BinClassName,
/// Hash of a bin field name
BinFieldName,
/// Hash of a bin hash value
BinHashValue,
/// Hash of RST files (translation files)
Rst,
}
impl HashKind {
/// Return filename used by CDragon to store the mapping this kind of hash
///
/// ```
/// use cdragon_hashes::HashKind;
/// assert_eq!(HashKind::WadLcu.mapping_path(), "hashes.lcu.txt");
/// assert_eq!(HashKind::BinEntryPath.mapping_path(), "hashes.binentries.txt");
/// ```
pub fn mapping_path(&self) -> &'static str {
match self {
Self::WadGame => "hashes.game.txt",
Self::WadLcu => "hashes.lcu.txt",
Self::BinEntryPath => "hashes.binentries.txt",
Self::BinClassName => "hashes.bintypes.txt",
Self::BinFieldName => "hashes.binfields.txt",
Self::BinHashValue => "hashes.binhashes.txt",
Self::Rst => "hashes.rst.txt",
}
}
/// Return WAD hash kind from a WAD path
///
/// The path is assumed to be a "regular" WAD path that follows Riot conventions.
/// ```
/// use cdragon_hashes::HashKind;
/// assert_eq!(HashKind::from_wad_path("Global.wad.client"), Some(HashKind::WadGame));
/// assert_eq!(HashKind::from_wad_path("assets.wad"), Some(HashKind::WadLcu));
/// assert_eq!(HashKind::from_wad_path("unknown"), None);
/// ```
pub fn from_wad_path<P: AsRef<Path>>(path: P) -> Option<Self> {
let path = path.as_ref().to_str()?;
if path.ends_with(".wad.client") {
Some(Self::WadGame)
} else if path.ends_with(".wad") {
Some(Self::WadLcu)
} else {
None
}
}
}
| true |
317f7d9ab9803e1f80ba6ecc675a955d54244add
|
Rust
|
finnbear/rustrict
|
/src/buffer_proxy_iterator.rs
|
UTF-8
| 2,097 | 3.609375 | 4 |
[
"Apache-2.0",
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
use std::collections::VecDeque;
use std::iter::Iterator;
use std::ops::RangeInclusive;
/// This iterator buffers characters until they can be determined to be clean of profanity.
pub(crate) struct BufferProxyIterator<I: Iterator<Item = char>> {
iter: I,
/// The index into iter of the start of buffer.
buffer_start_position: usize,
/// Staging area (to possibly censor).
buffer: VecDeque<I::Item>,
}
impl<I: Iterator<Item = char>> BufferProxyIterator<I> {
pub fn new(iter: I) -> Self {
BufferProxyIterator {
iter,
buffer_start_position: 0,
buffer: VecDeque::new(),
}
}
/// Returns index of the last character read, or None if nothing has been read yet.
pub fn index(&self) -> Option<usize> {
if self.buffer_start_position + self.buffer.len() == 0 {
// Didn't read anything yet.
return None;
}
Some(self.buffer_start_position + self.buffer.len() - 1)
}
/// Returns index of the next character that can be spied, or empty if no characters can be spied.
pub fn spy_next_index(&self) -> Option<usize> {
if self.buffer.is_empty() {
None
} else {
Some(self.buffer_start_position)
}
}
/// Spies one one more character.
pub fn spy_next(&mut self) -> Option<char> {
let ret = self.buffer.pop_front();
if ret.is_some() {
self.buffer_start_position += 1;
}
ret
}
/// Censors a given range (must be fully resident in the buffer).
pub fn censor(&mut self, range: RangeInclusive<usize>, replacement: char) {
let start = self.buffer_start_position;
for i in range {
self.buffer[i - start] = replacement;
}
}
}
impl<I: Iterator<Item = char>> Iterator for BufferProxyIterator<I> {
type Item = I::Item;
fn next(&mut self) -> Option<Self::Item> {
let ret = self.iter.next();
if let Some(val) = ret.as_ref() {
self.buffer.push_back(*val);
}
ret
}
}
| true |
e86750456cfcea11c15fdaab937a0bfc63502cca
|
Rust
|
andrew4fr/dwemthys
|
/src/movement/mod.rs
|
UTF-8
| 2,958 | 3.109375 | 3 |
[] |
no_license
|
use crate::game::Game;
use crate::util::Contains::{DoesContain, DoesNotContain};
use crate::util::{Bound, Point, XPointRelation, YPointRelation, PointEquality};
use rand::prelude::*;
use tcod::input::KeyCode::{Down, Left, Right, Up};
pub trait MovementComponent {
fn update(&self, p: Point) -> Point;
}
pub struct RandomMovementComponent {
pub window_bound: Bound,
}
pub struct TcodUserMovementComponent {
pub window_bound: Bound,
}
pub struct AggroMovementComponent {
pub window_bound: Bound,
}
impl MovementComponent for RandomMovementComponent {
fn update(&self, p: Point) -> Point {
let mut rng = rand::thread_rng();
let mut offset = Point { x: p.x, y: p.y };
let offset_x = rng.gen_range(0, 3i32) - 1;
match self.window_bound.contains(offset.offset_x(offset_x)) {
DoesContain => offset = offset.offset_x(offset_x),
DoesNotContain => {
return p;
}
}
let offset_y = rng.gen_range(0, 3i32) - 1;
match self.window_bound.contains(offset.offset_y(offset_y)) {
DoesContain => offset = offset.offset_y(offset_y),
DoesNotContain => {
return p;
}
}
offset
}
}
impl MovementComponent for TcodUserMovementComponent {
fn update(&self, p: Point) -> Point {
let mut offset = Point { x: p.x, y: p.y };
offset = match Game::get_last_keypress() {
Some(key) => match key.code {
Up => offset.offset_y(-1),
Down => offset.offset_y(1),
Left => offset.offset_x(-1),
Right => offset.offset_x(1),
_ => offset,
},
None => offset,
};
match self.window_bound.contains(offset) {
DoesContain => offset,
DoesNotContain => p,
}
}
}
impl MovementComponent for AggroMovementComponent {
fn update(&self, p: Point) -> Point {
let char_pos = Game::get_character_point();
let mut offset = Point{ x: 0, y: 0 };
match p.compare_x(char_pos) {
XPointRelation::RightOfPoint => offset = offset.offset_x(-1),
XPointRelation::LeftOfPoint => offset = offset.offset_x(1),
XPointRelation::OnPointX => {},
}
match p.compare_y(char_pos) {
YPointRelation::BelowPoint => offset = offset.offset_y(-1),
YPointRelation::AbovePoint => offset = offset.offset_y(1),
YPointRelation::OnPointY => {},
}
match p.offset(offset).compare(char_pos) {
PointEquality::PointsEqual => return p,
PointEquality::PointsNotEqual => {
match self.window_bound.contains(p.offset(offset)) {
DoesContain => { return p.offset(offset); },
DoesNotContain => { return p; },
}
}
}
}
}
| true |
13d4ba8fac19f0cfd6403dfc2af9ed92f1f021b7
|
Rust
|
Tzian/octothorp
|
/src/octree.rs
|
UTF-8
| 7,205 | 3.6875 | 4 |
[] |
no_license
|
use error::OctreeError;
use node::{NodeLoc, OctreeNode};
use serde::{Serialize, Deserialize};
use std::{fmt, u8};
/// Octree structure
#[derive(Serialize, Deserialize)]
pub struct Octree<T> {
dimension: u16,
max_depth: u8,
root: OctreeNode<T>,
}
impl<T> Octree<T>
where
T: Copy + PartialEq,
{
/// Constructs a new `Octree<T>`.
///
/// # Examples
///
/// ```
/// # use octo::octree::Octree;
/// let octree = Octree::<u8>::new(16).unwrap();
/// ```
///
pub fn new(dimension: u16) -> Result<Octree<T>, OctreeError> {
let depth = f64::from(dimension).sqrt();
let remainder = depth.fract();
if remainder == 0.0 && ((depth as u8) < core::u8::MAX) {
Ok(Octree {
dimension,
max_depth: depth as u8,
root: OctreeNode::construct_root(dimension),
})
} else {
Err(OctreeError::DimensionError)
}
}
/// Insert a new `OctreeNode<T>` into the `Octree<T>`
/// If this is called on a location where a node already exists, just set the `data` field
///
/// # Examples
///
/// ```
/// # use octo::octree::Octree;
/// #
/// # let mut octree = Octree::<u8>::new(16).unwrap();
/// octree.insert([0, 0, 0], 255).unwrap();
/// ```
///
pub fn insert(&mut self, loc: [u16; 3], data: T) -> Result<(), OctreeError> {
let mut node_loc = self.loc_from_array(loc);
if self.contains_loc(&node_loc) {
self.root.insert(&mut node_loc, data);
Ok(())
} else {
Err(OctreeError::OutOfBoundsError)
}
}
/// Get the value stored by the `Octree<T>` at a given node
///
/// # Examples
///
/// ```
/// # use octo::octree::Octree;
/// #
/// # let mut octree = Octree::<u8>::new(16).unwrap();
/// octree.insert([0, 0, 0], 255).unwrap();
/// assert_eq!(octree.at([0, 0, 0]), Some(255));
/// ```
///
pub fn at(&self, loc: [u16; 3]) -> Option<T> {
let mut node_loc = self.loc_from_array(loc);
self.root.at(&mut node_loc)
}
/// Get the value stored by the `Octree<T>` at a given node, and replace with `None`
///
/// # Examples
///
/// ```
/// # use octo::octree::Octree;
/// #
/// # let mut octree = Octree::<u8>::new(16).unwrap();
/// octree.insert([0, 0, 0], 255).unwrap();
/// let val = octree.take([0, 0, 0]);
///
/// assert_eq!(octree.at([0, 0, 0]), None);
/// assert_eq!(val, Some(255));
/// ```
pub fn take(&mut self, loc: [u16; 3]) -> Option<T> {
let mut node_loc = self.loc_from_array(loc);
self.root.take(&mut node_loc)
}
/// Insert `None` into the `Octree<T>` at a given node
///
/// # Examples
///
/// ```
/// # use octo::octree::Octree;
/// #
/// # let mut octree = Octree::<u8>::new(16).unwrap();
/// octree.insert([0, 0, 0], 255).unwrap();
/// octree.insert_none([0, 0, 0]);
///
/// assert_eq!(octree.at([0, 0, 0]), None);
/// ```
///
pub fn insert_none(&mut self, loc: [u16; 3]) {
let mut node_loc = self.loc_from_array(loc);
self.root.insert_none(&mut node_loc);
}
/// Returns the x/y/z dimension of an `Octree<T>`
pub fn dimension(&self) -> u16 {
self.dimension
}
/// Returns the maximum depth of an `Octree<T>`
pub fn max_depth(&self) -> u8 {
self.max_depth
}
/// Get a shared reference to a given `OctreeNode<T>`
pub fn node_as_ref(&self, loc: [u16; 3]) -> Option<&OctreeNode<T>> {
let mut node_loc = self.loc_from_array(loc);
self.root.node_as_ref(&mut node_loc)
}
/// Transform the `Octree<T>` into an iterator, consuming the `Octree<T>`
///
/// # Examples
///
/// ```
/// # use octo::octree::Octree;
/// #
/// # let mut octree = Octree::<u8>::new(16).unwrap();
/// octree.insert([0, 0, 0], 255).unwrap();
/// octree.insert([12, 10, 6], 128).unwrap();
///
/// // This will print "255, 128"
/// for val in octree.iter() {
/// print!("{:?}", val);
/// }
/// ```
///
pub fn iter(&mut self) -> OctreeIterator<T> {
OctreeIterator::new_from_ref(&self)
}
/// Create a NodeLoc from a 3-index co-ordinate array
fn loc_from_array(&self, array: [u16; 3]) -> NodeLoc {
NodeLoc::new((array[0], array[1], array[2]))
}
/// Test if the `Octree<T>` bounds the given `NodeLoc`
fn contains_loc(&self, loc: &NodeLoc) -> bool {
loc.x() < self.dimension && loc.y() < self.dimension && loc.z() < self.dimension
}
}
/// Struct providing iterator functionality for `Octree<T>`
pub struct OctreeIterator<T> {
node_stack: Vec<OctreeNode<T>>,
value_stack: Vec<T>,
}
impl<T> IntoIterator for Octree<T>
where
T: Copy + PartialEq,
{
type Item = T;
type IntoIter = OctreeIterator<T>;
/// Transform the `Octree<T>` into an iterator, consuming the `Octree<T>`
///
/// # Examples
///
/// ```
/// # use octo::octree::Octree;
/// #
/// # let mut octree = Octree::<u8>::new(16).unwrap();
/// octree.insert([0, 0, 0], 255).unwrap();
/// let mut iter = octree.into_iter();
///
/// assert_eq!(iter.nth(0), Some(255));
/// ```
///
fn into_iter(self) -> OctreeIterator<T> {
OctreeIterator::new(self)
}
}
impl<T> OctreeIterator<T>
where
T: Copy + PartialEq,
{
/// Create a new `OctreeIterator<T>` from an `Octree<T>`, consuming it in the process
fn new(octree: Octree<T>) -> OctreeIterator<T> {
let mut iter = OctreeIterator {
node_stack: vec![],
value_stack: vec![],
};
iter.node_stack.push(octree.root.clone());
iter.dfs();
iter
}
/// Create a new `OctreeIterator<T>` from an `Octree<T>`, without consuming it
fn new_from_ref(octree: &Octree<T>) -> OctreeIterator<T> {
let mut iter = OctreeIterator {
node_stack: vec![],
value_stack: vec![],
};
iter.node_stack.push(octree.root.clone());
iter.dfs();
iter
}
/// Iterator implementation using depth-first search
fn dfs(&mut self) {
while !self.node_stack.is_empty() {
if let Some(curr_node) = self.node_stack.pop() {
if let Some(data) = curr_node.get() {
self.value_stack.push(data);
};
for child in curr_node.children() {
if let Some(child_node) = child {
self.node_stack.push(child_node);
};
}
};
}
}
}
impl<T> Iterator for OctreeIterator<T>
where
T: Copy,
{
type Item = T;
/// Essential `Iterator` implementation
fn next(&mut self) -> Option<T> {
self.value_stack.pop()
}
}
/// Debug printing
impl<T> fmt::Debug for Octree<T>
where
T: Copy + PartialEq + fmt::Debug,
{
fn fmt(&self, _f: &mut fmt::Formatter) -> fmt::Result {
println!("{:?}", self.root);
Ok(())
}
}
| true |
0e0aa676023a4af85b67a30e64484130ab3c1038
|
Rust
|
ComplicatedPhenomenon/flashlight
|
/preparation/format.rs
|
UTF-8
| 549 | 3.125 | 3 |
[] |
no_license
|
use std::fmt;
use std::collections::HashSet;
fn main(){
let s = fmt::format(format_args!("hello {}", "world"));
println!("{}", s);
let name = "szaghi";
let s1 = fmt::format(format_args!("https://github.com/{}?tab=following", name));
println!("{}", s1);
let mut names = HashSet::new();
names.insert("szaghi".to_string());
names.insert("reinh-bader".to_string());
for name in &names {
let tem = fmt::format(format_args!("https://github.com/{}?tab=following", name));
println!("{}", tem);
}
}
| true |
10e920e199698798dbaafed9cf2bde1bbc85bf98
|
Rust
|
etherbanking/wasm-utils
|
/build/src/main.rs
|
UTF-8
| 3,558 | 2.546875 | 3 |
[] |
no_license
|
//! Experimental build tool for cargo
extern crate glob;
extern crate wasm_utils;
extern crate clap;
extern crate parity_wasm;
use std::{fs, io};
use std::path::PathBuf;
use clap::{App, Arg};
#[derive(Debug)]
pub enum Error {
Io(io::Error),
NoSuitableFile(String),
TooManyFiles(String),
NoEnvVar,
}
impl From<io::Error> for Error {
fn from(err: io::Error) -> Self {
Error::Io(err)
}
}
pub fn wasm_path(target_dir: &str, bin_name: &str) -> String {
let mut path = PathBuf::from(target_dir);
path.push(format!("{}.wasm", bin_name));
path.to_string_lossy().to_string()
}
pub fn process_output(target_dir: &str, bin_name: &str) -> Result<(), Error> {
let mut path = PathBuf::from(target_dir);
let wasm_name = bin_name.to_string().replace("-", "_");
path.push("wasm32-unknown-emscripten");
path.push("release");
path.push("deps");
path.push(format!("{}-*.wasm", wasm_name));
let mut files = glob::glob(path.to_string_lossy().as_ref()).expect("glob err")
.collect::<Vec<Result<PathBuf, glob::GlobError>>>();
if files.len() == 0 {
return Err(Error::NoSuitableFile(path.to_string_lossy().to_string()));
} else if files.len() > 1 {
return Err(Error::TooManyFiles(
files.into_iter().map(|f| f.expect("glob err").to_string_lossy().to_string())
.fold(String::new(), |mut a, b| { a.push_str(", "); a.push_str(&b); a })
))
} else {
let file = files.drain(..).nth(0).expect("0th element exists").expect("glob err");
let mut path = PathBuf::from(target_dir);
path.push(format!("{}.wasm", bin_name));
fs::copy(file, path)?;
}
Ok(())
}
fn main() {
wasm_utils::init_log();
let matches = App::new("wasm-opt")
.arg(Arg::with_name("target")
.index(1)
.required(true)
.help("Cargo target directory"))
.arg(Arg::with_name("wasm")
.index(2)
.required(true)
.help("Wasm binary name"))
.arg(Arg::with_name("skip_optimization")
.help("Skip symbol optimization step producing final wasm")
.long("skip-optimization"))
.arg(Arg::with_name("skip_alloc")
.help("Skip allocator externalizer step producing final wasm")
.long("skip-externalize"))
.arg(Arg::with_name("runtime_type")
.help("Injects RUNTIME_TYPE global export")
.takes_value(true)
.long("runtime-type"))
.arg(Arg::with_name("runtime_version")
.help("Injects RUNTIME_VERSION global export")
.takes_value(true)
.long("runtime-version"))
.get_matches();
let target_dir = matches.value_of("target").expect("is required; qed");
let wasm_binary = matches.value_of("wasm").expect("is required; qed");
process_output(target_dir, wasm_binary).expect("Failed to process cargo target directory");
let path = wasm_path(target_dir, wasm_binary);
let mut module = parity_wasm::deserialize_file(&path).unwrap();
if !matches.is_present("skip_alloc") {
module = wasm_utils::externalize(
module,
vec!["_free", "_malloc"],
);
}
if !matches.is_present("skip_optimization") {
wasm_utils::optimize(&mut module, vec!["_call", "setTempRet0"]).expect("Optimizer to finish without errors");
}
if let Some(runtime_type) = matches.value_of("runtime_type") {
let runtime_type: &[u8] = runtime_type.as_bytes();
if runtime_type.len() != 4 {
panic!("--runtime-type should be equal to 4 bytes");
}
let runtime_version: u32 = matches.value_of("runtime_version").unwrap_or("1").parse()
.expect("--runtime-version should be a positive integer");
module = wasm_utils::inject_runtime_type(module, &runtime_type, runtime_version);
}
parity_wasm::serialize_to_file(&path, module).unwrap();
}
| true |
16d89ffdc93520d25f97615ea35771ab3357d228
|
Rust
|
matthiasSchedel/RustAirHockey
|
/src/airhockey/player.rs
|
UTF-8
| 4,918 | 2.859375 | 3 |
[
"LicenseRef-scancode-unknown-license-reference",
"MIT",
"Apache-2.0"
] |
permissive
|
//! Airhockey Player.
use super::helper;
/// player radius
pub const RADIUS: u16 = 30;
/// player fill color
pub const COLOR: u32 = 0xfff000;
/// player radius
pub const STROKE_COLOR: u32 = 0xfff000;
/// has the player stroke?
pub const HAS_STROKE: bool = false;
use super::field;
use super::graphics_handler::GraphicsHandler;
use super::input_handler::{self, InputHandler};
use super::init::Handler;
/// Player
pub struct Player {
player_id: u8,
current_pos: (u16, u16),
radius: u16,
color: u32,
///Defining the half of the field where the player can move
x_min: u16,
x_max: u16,
///The player is following the user's input (given by target_position)ar
target_pos: (u16, u16),
///The speed the player is moving towards the target position
speed: (i32, i32),
}
impl Player {
/// Create new player
pub fn new(player_id: u8) -> Player {
let radius = RADIUS;
let color = COLOR;
//This has to be changed if more than two players exist
if player_id == 0 {
Player {
player_id: player_id,
current_pos: (field::WIDTH_MAX / 4, field::HEIGHT_MAX / 2),
radius: radius,
color: color,
x_min: 0,
x_max: field::WIDTH_MAX / 2,
///The target position is the same as the current position at initialization
target_pos: (field::WIDTH_MAX / 4, field::HEIGHT_MAX / 2),
speed: (0, 0),
}
} else {
//TODO zusammenfassen!
Player {
player_id: player_id,
current_pos: (3 * field::WIDTH_MAX / 4, field::HEIGHT_MAX / 2),
radius: radius,
color: color,
x_min: (field::WIDTH_MAX / 2) + 1,
x_max: field::WIDTH_MAX - 1,
///The target position is the same as the current position at initialization
target_pos: (3 * field::WIDTH_MAX / 4, field::HEIGHT_MAX / 2),
speed: (0, 0),
}
}
}
pub fn draw(&self, handler: &mut Handler) {
handler.graphics_handler.draw_player(
self.color,
[self.current_pos.0, self.current_pos.1],
self.radius,
);
}
///Move the player according to the target position
pub fn move_player(&mut self) {
let mut x = 0;
let mut y = 0;
if i32::from(self.current_pos.0) - i32::from(self.target_pos.0) <= self.speed.0
&& i32::from(self.current_pos.1) - i32::from(self.target_pos.1) <= self.speed.1
{
self.speed = (0, 0);
x = i32::from(self.target_pos.0);
y = i32::from(self.target_pos.1);
} else {
x = i32::from(self.current_pos.0) + self.speed.0;
y = i32::from(self.current_pos.1) + self.speed.1;
}
//Always has to be inside the field borders
self.current_pos = field::get_position_still_in_field(
(i32::from(self.x_min), i32::from(self.x_max)),
(x, y),
self.current_pos,
self.radius,
);
}
///update player on user input
pub fn update_on_user_input(&mut self, handler: &mut Handler) {
if self.player_id == 0 {
handler.input_handler.fetch_input();
}
let (is_touched, pos) = handler.input_handler.get_target_position(
self.current_pos,
self.radius,
self.x_min,
self.x_max,
);
//Important! Only perform when there are touches!
if is_touched {
self.target_pos = field::get_position_still_in_field(
(i32::from(self.x_min), i32::from(self.x_max)),
(i32::from(pos.0), i32::from(pos.1)),
self.current_pos,
self.radius,
);
}
self.speed = (
((f32::from(self.target_pos.0) - f32::from(self.current_pos.0)) / 1.5) as i32,
((f32::from(self.target_pos.1) - f32::from(self.current_pos.1)) / 1.5) as i32,
);
}
///Get the player id
pub fn get_id(&self) -> u8 {
self.player_id
}
///Get the current position of the player
pub fn get_position(&self) -> (u16, u16) {
(self.current_pos.0, self.current_pos.1)
}
///set the current position of the player
pub fn set_position(&mut self, x: u16, y: u16) {
self.current_pos.0 = x;
self.current_pos.1 = y;
}
pub fn get_speed(&self) -> (i32, i32) {
self.speed
}
pub fn get_radius(&self) -> u16 {
self.radius
}
pub fn get_color(&self) -> u32 {
self.color
}
pub fn setColor(&mut self, color: u32) {
self.color = color;
}
pub fn setRadius(&mut self, radius: u16) {
self.radius = radius;
}
}
| true |
320357ee93b685d54951c14ff3272081c642b91a
|
Rust
|
andrewdupont/rust-tutorial
|
/fizzbuzz2.rs
|
UTF-8
| 341 | 3.3125 | 3 |
[] |
no_license
|
fn fizz_buzz(count: i32) -> String {
if count % 15 == 0 {
"FizzBuzz".to_string()
} else if count % 3 == 0 {
"Buzz".to_string()
} else if count % 5 == 0 {
"Fizz".to_string()
}
else {
count.to_string()
}
}
fn main() {
for i in 1..101 {
println!("{}", fizz_buzz(i));
}
}
| true |
15809caefa03cbfa2a522072d9735779fb7c63f7
|
Rust
|
rust-in-action/code
|
/ch5/ch5-int-vs-int.rs
|
UTF-8
| 152 | 2.53125 | 3 |
[] |
no_license
|
fn main() {
let a: u16 = 50115;
let b: i16 = -15421;
println!("a: {:016b} {}", a, a); // <1>
println!("b: {:016b} {}", b, b); // <1>
}
| true |
452b285b84ed58b25a8f024c570a9286f9e3a157
|
Rust
|
dialtone/aoc
|
/src/solutions/year2022/day11.rs
|
UTF-8
| 6,607 | 2.796875 | 3 |
[
"MIT"
] |
permissive
|
// use crate::solutions::clear_screen;
// use crate::solutions::go_to_top;
pub struct Monkey {
pub stack: Vec<u64>,
pub op: Op,
pub div: u64,
pub conditions: (usize, usize),
}
#[derive(Clone, Copy)]
pub enum Op {
Square,
Add(u64),
Mul(u64),
}
pub fn parse(input: &[u8]) -> Vec<Monkey> {
let mut monkeys = vec![];
let mut input = input.split(|c| c == &b'\n');
while let Some(mut line) = input.next() {
if line.is_empty() {
// end monkey
continue;
}
// monkey name skip
line = input.next().unwrap();
// items
let stack = line[line.iter().position(|c| c == &b':').unwrap() + 1..]
.split(|c| c == &b',')
.map(|it| if it[0] == b' ' { &it[1..] } else { it })
.map(|it| atoi::atoi(it).unwrap())
.collect();
// ops
line = input.next().unwrap();
let mut op_and_num = line[23..].split(|c| c == &b' ');
let op = op_and_num.next().unwrap();
let num = op_and_num.next().unwrap();
let operation: Op = match (op[0], num) {
(b'*', b"old") => Op::Square,
(b'*', n) => Op::Mul(atoi::atoi(n).unwrap()),
(b'+', n) => Op::Add(atoi::atoi(n).unwrap()),
_ => {
unreachable!();
}
};
// divisible test
line = input.next().unwrap();
let divisible = atoi::atoi(&line[21..]).unwrap();
// true condition
line = input.next().unwrap();
let condition = atoi::atoi(&line[29..]).unwrap();
// false condition
line = input.next().unwrap();
let conditions = (condition, atoi::atoi(&line[30..]).unwrap());
monkeys.push(Monkey {
stack,
op: operation,
div: divisible,
conditions,
});
}
monkeys
}
// year 22 day11 part 1 time: [4.7589 µs 4.7724 µs 4.7906 µs]
pub fn part1(input: &[u8]) -> usize {
let mut monkeys = parse(input);
let mut inspections: Vec<usize> = vec![0; monkeys.len()];
for _ in 0..20 {
for i in 0..monkeys.len() {
let len = monkeys[i].stack.len();
for j in 0..len {
let item = monkeys[i].stack[j];
inspections[i] += 1;
let new_item = match monkeys[i].op {
Op::Square => item * item / 3,
Op::Mul(n) => item * n / 3,
Op::Add(n) => (item + n) / 3,
};
let throw_to = if new_item % monkeys[i].div == 0 {
monkeys[i].conditions.0
} else {
monkeys[i].conditions.1
};
monkeys[throw_to].stack.push(new_item);
}
monkeys[i].stack.clear();
}
}
inspections.sort();
inspections.iter().rev().take(2).product::<usize>()
}
// year 22 day11 part 2 time: [1.4882 ms 1.4896 ms 1.4911 ms]
pub fn part2(input: &[u8]) -> usize {
let monkeys = parse(input);
let mut inspections: Vec<usize> = vec![0; monkeys.len()];
let mut items = [[0u64; 50]; 8];
// pointer to last item in items for each monkey
let mut m_cnt = [0usize; 8];
let mcm = monkeys.iter().map(|m| m.div).product::<u64>();
for (n, m) in monkeys.iter().enumerate() {
for i in m.stack.iter() {
items[n][m_cnt[n]] = *i;
m_cnt[n] += 1;
}
}
for _ in 0..10_000 {
for i in 0..monkeys.len() {
let mut itz = items[i];
let l = m_cnt[i];
inspections[i] += l;
let test = monkeys[i].div;
match monkeys[i].op {
Op::Square => {
for it in itz.iter_mut().take(l) {
*it *= *it;
*it %= mcm;
let throw_to = if *it % test == 0 {
monkeys[i].conditions.0
} else {
monkeys[i].conditions.1
};
let c = &mut m_cnt[throw_to];
items[throw_to][*c] = *it;
*c += 1;
}
}
Op::Mul(n) => {
for it in itz.iter_mut().take(l) {
*it *= n;
*it %= mcm;
let throw_to = if *it % test == 0 {
monkeys[i].conditions.0
} else {
monkeys[i].conditions.1
};
let c = &mut m_cnt[throw_to];
items[throw_to][*c] = *it;
*c += 1;
}
}
Op::Add(n) => {
for it in itz.iter_mut().take(l) {
*it += n;
*it %= mcm;
let throw_to = if *it % test == 0 {
monkeys[i].conditions.0
} else {
monkeys[i].conditions.1
};
let c = &mut m_cnt[throw_to];
items[throw_to][*c] = *it;
*c += 1;
}
}
}
m_cnt[i] = 0;
}
}
inspections.sort();
inspections.iter().rev().take(2).product::<usize>()
}
#[cfg(test)]
mod tests {
use super::*;
use crate::solutions::*;
#[test]
fn day11_test() {
let input = "Monkey 0:
Starting items: 79, 98
Operation: new = old * 19
Test: divisible by 23
If true: throw to monkey 2
If false: throw to monkey 3
Monkey 1:
Starting items: 54, 65, 75, 74
Operation: new = old + 6
Test: divisible by 19
If true: throw to monkey 2
If false: throw to monkey 0
Monkey 2:
Starting items: 79, 60, 97
Operation: new = old * old
Test: divisible by 13
If true: throw to monkey 1
If false: throw to monkey 3
Monkey 3:
Starting items: 74
Operation: new = old + 3
Test: divisible by 17
If true: throw to monkey 0
If false: throw to monkey 1";
assert_eq!(part1(input.as_bytes()), 10605);
assert_eq!(part2(input.as_bytes()), 2713310158);
}
#[test]
fn day11() {
let input = get_input(2022, 11).unwrap();
assert_eq!(part1(input.as_bytes()), 58786);
assert_eq!(part2(input.as_bytes()), 14952185856);
}
}
| true |
02066d07d96a9241a3e17c415ecdbdd2d92b09de
|
Rust
|
ExcaliburZero/chip8_interpreter
|
/src/bit_operations.rs
|
UTF-8
| 3,500 | 3.84375 | 4 |
[
"MIT"
] |
permissive
|
//! Bit-based operations for u8 and u16 values.
pub type InstructionNibbles = (u8, u8, u8, u8);
/// Returns the nth bit of the given byte as a bool.
///
/// Indexed with 0 being the last bit of the byte.
///
/// ```rust
/// # use chip8_interpreter::bit_operations::get_nth_bit;
/// assert_eq!(Ok(true), get_nth_bit(1, 0b00000010));
/// assert_eq!(Ok(false), get_nth_bit(2, 0b00000010));
/// ```
pub fn get_nth_bit(n: u8, byte: u8) -> Result<bool, String> {
if n >= 8 {
return Err(format!("Invalid byte bit index: {}", n));
}
let mask = 1 << n;
Ok(((byte & mask) >> n) == 1)
}
/// Returns the last two nibbles of the given u16.
///
/// ```rust
/// # use chip8_interpreter::bit_operations::get_last_two_nibbles;
/// assert_eq!(0xCD, get_last_two_nibbles(0xABCD));
/// ```
pub fn get_last_two_nibbles(bytes: u16) -> u8 {
(bytes & 0x00FF) as u8
}
/// Returns the last three nibbles of the given u16.
///
/// ```rust
/// # use chip8_interpreter::bit_operations::get_last_three_nibbles;
/// assert_eq!(0x0BCD, get_last_three_nibbles(0xABCD));
/// ```
pub fn get_last_three_nibbles(bytes: u16) -> u16 {
bytes & 0x0FFF
}
/// Returns the first nibble of the given u16.
///
/// ```rust
/// # use chip8_interpreter::bit_operations::get_first_nibble;
/// assert_eq!(0x0A, get_first_nibble(0xABCD));
/// ```
pub fn get_first_nibble(bytes: u16) -> u8 {
let three_nibbles_len = 4 * 3;
((bytes & 0xF000) >> three_nibbles_len) as u8
}
/// Returns the second nibble of the given u16.
///
/// ```rust
/// # use chip8_interpreter::bit_operations::get_second_nibble;
/// assert_eq!(0x0B, get_second_nibble(0xABCD));
/// ```
pub fn get_second_nibble(bytes: u16) -> u8 {
let two_nibbles_len = 4 * 2;
((bytes & 0x0F00) >> two_nibbles_len) as u8
}
/// Returns the third nibble of the given u16.
///
/// ```rust
/// # use chip8_interpreter::bit_operations::get_third_nibble;
/// assert_eq!(0x0C, get_third_nibble(0xABCD));
/// ```
pub fn get_third_nibble(bytes: u16) -> u8 {
let one_nibble_len = 4;
((bytes & 0x00F0) >> one_nibble_len) as u8
}
/// Returns the fourth nibble of the given u16.
///
/// ```rust
/// # use chip8_interpreter::bit_operations::get_fourth_nibble;
/// assert_eq!(0x0D, get_fourth_nibble(0xABCD));
/// ```
pub fn get_fourth_nibble(bytes: u16) -> u8 {
(bytes & 0x000F) as u8
}
/// Breaks down the given u16 into a tuple of nibbles.
///
/// ```rust
/// # use chip8_interpreter::bit_operations::break_into_nibbles;
/// assert_eq!((0x0A, 0x0B, 0x0C, 0x0D), break_into_nibbles(0xABCD));
/// ```
pub fn break_into_nibbles(bytes: u16) -> InstructionNibbles {
let first = get_first_nibble(bytes);
let second = get_second_nibble(bytes);
let third = get_third_nibble(bytes);
let fourth = get_fourth_nibble(bytes);
(first, second, third, fourth)
}
#[test]
fn get_nth_bit_all() {
assert_eq!(Ok(false), get_nth_bit(0, 0b00000000));
assert_eq!(Ok(true), get_nth_bit(0, 0b00000001));
assert_eq!(Ok(true), get_nth_bit(1, 0b00000010));
assert_eq!(Ok(true), get_nth_bit(2, 0b00000100));
assert_eq!(Ok(true), get_nth_bit(3, 0b00001000));
assert_eq!(Ok(true), get_nth_bit(4, 0b00010000));
assert_eq!(Ok(true), get_nth_bit(5, 0b00100000));
assert_eq!(Ok(true), get_nth_bit(6, 0b01000000));
assert_eq!(Ok(true), get_nth_bit(7, 0b10000000));
}
#[test]
fn get_nth_bit_invalid_bit() {
assert_eq!(
Err("Invalid byte bit index: 8".to_string()),
get_nth_bit(8, 0b00000000)
);
}
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.