<commit_before>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

extern crate string_cache_codegen;

use std::env;
use std::fs::File;
use std::io::{BufReader, BufRead};
use std::path::Path;

fn main() {
    let static_atoms = Path::new(&env::var_os("CARGO_MANIFEST_DIR").unwrap()).join("static_atoms.txt");
    let static_atoms = BufReader::new(File::open(&static_atoms).unwrap());
    let mut atom_type = string_cache_codegen::AtomType::new("Atom", "atom!");

    macro_rules! predefined {
        ($($name: expr,)+) => {
            {
                $(
                    atom_type.atom($name);
                )+
            }
        }
    }
    include!("../style/counter_style/predefined.rs");

    atom_type
        .atoms(static_atoms.lines().map(Result::unwrap))
        .write_to_file(&Path::new(&env::var_os("OUT_DIR").unwrap()).join("atom.rs"))
        .unwrap();
}
<commit_msg>Format components atoms #21373<commit_after>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

extern crate string_cache_codegen;

use std::env;
use std::fs::File;
use std::io::{BufReader, BufRead};
use std::path::Path;

fn main() {
    let static_atoms =
        Path::new(&env::var_os("CARGO_MANIFEST_DIR").unwrap()).join("static_atoms.txt");
    let static_atoms = BufReader::new(File::open(&static_atoms).unwrap());
    let mut atom_type = string_cache_codegen::AtomType::new("Atom", "atom!");

    macro_rules! predefined {
        ($($name: expr,)+) => {
            {
                $(
                    atom_type.atom($name);
                )+
            }
        }
    }
    include!("../style/counter_style/predefined.rs");

    atom_type
        .atoms(static_atoms.lines().map(Result::unwrap))
        .write_to_file(&Path::new(&env::var_os("OUT_DIR").unwrap()).join("atom.rs"))
        .unwrap();
}
<|endoftext|>


<commit_before>use proc_macro::TokenStream;
use std::convert::TryFrom;

use quote::quote;
use ruma_identifiers::{
    DeviceKeyId, EventId, RoomAliasId, RoomId, RoomVersionId, ServerKeyId, ServerName, UserId,
};
use syn::{parse_macro_input, LitStr};

#[proc_macro]
pub fn device_id(input: TokenStream) -> TokenStream {
    let id = parse_macro_input!(input as LitStr);
    let output = quote! {
        ::std::boxed::Box<::ruma::identifiers::DeviceId>::from(#id)
    };

    output.into()
}

// w/o macro:  UserId::try_from("@user:example.org").unwrap()
// w/ macro:   user_id!("@user:example.org")

#[proc_macro]
pub fn device_key_id(input: TokenStream) -> TokenStream {
    let id = parse_macro_input!(input as LitStr);
    assert!(DeviceKeyId::try_from(id.value()).is_ok(), "Invalid device key id");

    let output = quote! {
        <::ruma::identifiers::DeviceKeyId as ::std::convert::TryFrom<&str>>::try_from(#id).unwrap()
    };

    output.into()
}

#[proc_macro]
pub fn event_id(input: TokenStream) -> TokenStream {
    let id = parse_macro_input!(input as LitStr);
    assert!(EventId::try_from(id.value()).is_ok(), "Invalid event id");

    let output = quote! {
        <::ruma::identifiers::EventId as ::std::convert::TryFrom<&str>>::try_from(#id).unwrap()
    };

    output.into()
}

#[proc_macro]
pub fn room_alias_id(input: TokenStream) -> TokenStream {
    let id = parse_macro_input!(input as LitStr);
    assert!(RoomAliasId::try_from(id.value()).is_ok(), "Invalid room_alias_id");

    let output = quote! {
        <::ruma::identifiers::RoomAliasId as ::std::convert::TryFrom<&str>>::try_from(#id).unwrap()
    };

    output.into()
}

#[proc_macro]
pub fn room_id(input: TokenStream) -> TokenStream {
    let id = parse_macro_input!(input as LitStr);
    assert!(RoomId::try_from(id.value()).is_ok(), "Invalid room_id");

    let output = quote! {
        <::ruma::identifiers::RoomId as ::std::convert::TryFrom<&str>>::try_from(#id).unwrap()
    };

    output.into()
}

#[proc_macro]
pub fn room_version_id(input: TokenStream) -> TokenStream {
    let id = parse_macro_input!(input as LitStr);
    assert!(RoomVersionId::try_from(id.value()).is_ok(), "Invalid room_version_id");

    let output = quote! {
        <::ruma::identifiers::RoomVersionId as ::std::convert::TryFrom<&str>>::try_from(#id).unwrap()
    };

    output.into()
}

#[proc_macro]
pub fn server_key_id(input: TokenStream) -> TokenStream {
    let id = parse_macro_input!(input as LitStr);
    assert!(ServerKeyId::try_from(id.value()).is_ok(), "Invalid server_key_id");

    let output = quote! {
        <::ruma::identifiers::ServerKeyId as ::std::convert::TryFrom<&str>>::try_from(#id).unwrap()
    };

    output.into()
}

#[proc_macro]
pub fn server_name(input: TokenStream) -> TokenStream {
    let id = parse_macro_input!(input as LitStr);
    assert!(<&ServerName>::try_from(id.value().as_str()).is_ok(), "Invalid server_name");

    let output = quote! {
        <::std::boxed::Box::<::ruma::identifiers::ServerName> as ::std::convert::TryFrom<&str>>::try_from(#id).unwrap()
    };

    output.into()
}

#[proc_macro]
pub fn user_id(input: TokenStream) -> TokenStream {
    let id = parse_macro_input!(input as LitStr);
    assert!(UserId::try_from(id.value()).is_ok(), "Invalid user_id");

    let output = quote! {
        <::ruma::identifiers::UserId as ::std::convert::TryFrom<&str>>::try_from(#id).unwrap()
    };

    output.into()
}
<commit_msg>Remove old comment<commit_after>use proc_macro::TokenStream;
use std::convert::TryFrom;

use quote::quote;
use ruma_identifiers::{
    DeviceKeyId, EventId, RoomAliasId, RoomId, RoomVersionId, ServerKeyId, ServerName, UserId,
};
use syn::{parse_macro_input, LitStr};

#[proc_macro]
pub fn device_id(input: TokenStream) -> TokenStream {
    let id = parse_macro_input!(input as LitStr);
    let output = quote! {
        ::std::boxed::Box<::ruma::identifiers::DeviceId>::from(#id)
    };

    output.into()
}

#[proc_macro]
pub fn device_key_id(input: TokenStream) -> TokenStream {
    let id = parse_macro_input!(input as LitStr);
    assert!(DeviceKeyId::try_from(id.value()).is_ok(), "Invalid device key id");

    let output = quote! {
        <::ruma::identifiers::DeviceKeyId as ::std::convert::TryFrom<&str>>::try_from(#id).unwrap()
    };

    output.into()
}

#[proc_macro]
pub fn event_id(input: TokenStream) -> TokenStream {
    let id = parse_macro_input!(input as LitStr);
    assert!(EventId::try_from(id.value()).is_ok(), "Invalid event id");

    let output = quote! {
        <::ruma::identifiers::EventId as ::std::convert::TryFrom<&str>>::try_from(#id).unwrap()
    };

    output.into()
}

#[proc_macro]
pub fn room_alias_id(input: TokenStream) -> TokenStream {
    let id = parse_macro_input!(input as LitStr);
    assert!(RoomAliasId::try_from(id.value()).is_ok(), "Invalid room_alias_id");

    let output = quote! {
        <::ruma::identifiers::RoomAliasId as ::std::convert::TryFrom<&str>>::try_from(#id).unwrap()
    };

    output.into()
}

#[proc_macro]
pub fn room_id(input: TokenStream) -> TokenStream {
    let id = parse_macro_input!(input as LitStr);
    assert!(RoomId::try_from(id.value()).is_ok(), "Invalid room_id");

    let output = quote! {
        <::ruma::identifiers::RoomId as ::std::convert::TryFrom<&str>>::try_from(#id).unwrap()
    };

    output.into()
}

#[proc_macro]
pub fn room_version_id(input: TokenStream) -> TokenStream {
    let id = parse_macro_input!(input as LitStr);
    assert!(RoomVersionId::try_from(id.value()).is_ok(), "Invalid room_version_id");

    let output = quote! {
        <::ruma::identifiers::RoomVersionId as ::std::convert::TryFrom<&str>>::try_from(#id).unwrap()
    };

    output.into()
}

#[proc_macro]
pub fn server_key_id(input: TokenStream) -> TokenStream {
    let id = parse_macro_input!(input as LitStr);
    assert!(ServerKeyId::try_from(id.value()).is_ok(), "Invalid server_key_id");

    let output = quote! {
        <::ruma::identifiers::ServerKeyId as ::std::convert::TryFrom<&str>>::try_from(#id).unwrap()
    };

    output.into()
}

#[proc_macro]
pub fn server_name(input: TokenStream) -> TokenStream {
    let id = parse_macro_input!(input as LitStr);
    assert!(<&ServerName>::try_from(id.value().as_str()).is_ok(), "Invalid server_name");

    let output = quote! {
        <::std::boxed::Box::<::ruma::identifiers::ServerName> as ::std::convert::TryFrom<&str>>::try_from(#id).unwrap()
    };

    output.into()
}

#[proc_macro]
pub fn user_id(input: TokenStream) -> TokenStream {
    let id = parse_macro_input!(input as LitStr);
    assert!(UserId::try_from(id.value()).is_ok(), "Invalid user_id");

    let output = quote! {
        <::ruma::identifiers::UserId as ::std::convert::TryFrom<&str>>::try_from(#id).unwrap()
    };

    output.into()
}
<|endoftext|>


<commit_before>mod gildedrose;

use gildedrose::{GildedRose, Item};

fn main() {
    let items = vec![
        Item::new(String::from("+5 Dexterity Vest"), 10, 20),
        Item::new(String::from("Aged Brie"), 2, 0),
        Item::new(String::from("Elixir of the Mongoose"), 5, 7),
        Item::new(String::from("Sulfuras, Hand of Ragnaros"), 0, 80),
        Item::new(String::from("Sulfuras, Hand of Ragnaros"), -1, 80),
        Item::new(
            String::from("Backstage passes to a TAFKAL80ETC concert"),
            15,
            20,
        ),
        Item::new(
            String::from("Backstage passes to a TAFKAL80ETC concert"),
            10,
            49,
        ),
        Item::new(
            String::from("Backstage passes to a TAFKAL80ETC concert"),
            5,
            49,
        ),
        // this conjured item does not work properly yet
        Item::new(String::from("Conjured Mana Cake"), 3, 6),
    ];
    let mut rose = GildedRose::new(items);

    println!("OMGHAI!");
    for i in (0..30) {
        println!("-------- day {} --------", i);
        println!("name, sellIn, quality");
        for item in &rose.items {
            println!("{}, {}, {}", item.name, item.sell_in, item.quality);
        }
        println!("");
        rose.update_quality();
    }
}
<commit_msg>Make main.rs clippy-clean<commit_after>mod gildedrose;

use gildedrose::{GildedRose, Item};

fn main() {
    let items = vec![
        Item::new(String::from("+5 Dexterity Vest"), 10, 20),
        Item::new(String::from("Aged Brie"), 2, 0),
        Item::new(String::from("Elixir of the Mongoose"), 5, 7),
        Item::new(String::from("Sulfuras, Hand of Ragnaros"), 0, 80),
        Item::new(String::from("Sulfuras, Hand of Ragnaros"), -1, 80),
        Item::new(
            String::from("Backstage passes to a TAFKAL80ETC concert"),
            15,
            20,
        ),
        Item::new(
            String::from("Backstage passes to a TAFKAL80ETC concert"),
            10,
            49,
        ),
        Item::new(
            String::from("Backstage passes to a TAFKAL80ETC concert"),
            5,
            49,
        ),
        // this conjured item does not work properly yet
        Item::new(String::from("Conjured Mana Cake"), 3, 6),
    ];
    let mut rose = GildedRose::new(items);

    println!("OMGHAI!");
    for i in 0..30 {
        println!("-------- day {} --------", i);
        println!("name, sellIn, quality");
        for item in &rose.items {
            println!("{}, {}, {}", item.name, item.sell_in, item.quality);
        }
        println!();
        rose.update_quality();
    }
}
<|endoftext|>


<commit_before>use std::time::Instant;

use regex::Regex;

fn measure(data: &str, pattern: &str) {
    let start = Instant::now();

    let regex = Regex::new(pattern).unwrap();
    let count = regex.find_iter(data).count();

    let elapsed = Instant::now().duration_since(start);

    println!("{} - {}", elapsed.as_secs_f64() * 1e3, count);
}

fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
    let path = match std::env::args_os().nth(1) {
        None => return Err(From::from("Usage: benchmark <filename>")),
        Some(path) => path,
    };
    let data = std::fs::read_to_string(path)?;

    // Email
    measure(&data, r"[\w\.+-]+@[\w\.-]+\.[\w\.-]+");

    // URI
    measure(&data, r"[\w]+://[^/\s?#]+[^\s?#]+(?:\?[^\s#]*)?(?:#[^\s]*)?");

    // IP
    measure(&data, r"(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9])");

    Ok(())
}
<commit_msg>rust: disable Unicode mode<commit_after>use std::time::Instant;

use regex::bytes::RegexBuilder;

fn measure(data: &str, pattern: &str) {
    let start = Instant::now();

    let regex = RegexBuilder::new(pattern).unicode(false).build().unwrap();
    let count = regex.find_iter(data.as_bytes()).count();

    let elapsed = Instant::now().duration_since(start);

    println!("{} - {}", elapsed.as_secs_f64() * 1e3, count);
}

fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
    let path = match std::env::args_os().nth(1) {
        None => return Err(From::from("Usage: benchmark <filename>")),
        Some(path) => path,
    };
    let data = std::fs::read_to_string(path)?;

    // Email
    measure(&data, r"[\w\.+-]+@[\w\.-]+\.[\w\.-]+");

    // URI
    measure(&data, r"[\w]+://[^/\s?#]+[^\s?#]+(?:\?[^\s#]*)?(?:#[^\s]*)?");

    // IP
    measure(&data, r"(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9])");

    Ok(())
}
<|endoftext|>


<commit_before>use core::cmp::{Eq, Ord};
use std::list;
use std::list::{List, Cons, Nil};

// I would really love for these to return Heaps but my knowledge
// of Rust is too limited to make that work.
pub trait Heap<E: Copy Eq Ord> {
  pure fn is_empty() -> bool;
  pure fn insert(elem: E) -> PairingHeap<E>;
  pure fn find_min() -> (Option<E>, PairingHeap<E>);
  pure fn delete_min() -> (Option<E>, PairingHeap<E>);
}

/**
 * A purely functional Pairing Heap [FSST86]
 *
 * Our implementation uses Linked List (cons cells) so may not be the
 * fastest way to implement this in Rust.
 *
 * This implementation is a port of the Standard ML found in Okasaki's
 * Purely Functional Data Structures.
 */
pub enum PairingHeap<E: Copy Eq Ord> {
  Empty_,
  PairingHeap_(@{
    head: E,
    rest: @List<PairingHeap<E>>
  })
}

pure fn Empty<E: Copy Eq Ord>() -> PairingHeap<E> {
  return Empty_;
}

pure fn PairingHeap<E: Copy Eq Ord>(initial_value: E) -> PairingHeap<E> {
  return PairingHeap_(@{
    head: initial_value,
    rest: @Nil
  });
}

impl<E: Copy Eq Ord> PairingHeap<E> : Eq {
  pure fn eq(other: &PairingHeap<E>) -> bool {
    match (self, *other) {
      (Empty_, Empty_) => {true}
      (PairingHeap_(heapA), PairingHeap_(heapB)) => {
        return (heapA.head == heapB.head) && (heapA.rest == heapB.rest);
      }
      //(Empty_, PairingHeap_(_)) => {false} // why are these unreachable?
      //(PairingHeap_(_), Empty) => {false}
      (_, _) => {false}
    }
  }

  pure fn ne(other: &PairingHeap<E>) -> bool { !(self).eq(other) }
}

impl<E: Copy Eq Ord> PairingHeap<E> : Heap<E> {
  pure fn is_empty() -> bool {
    match self {
      Empty_ => { return true; }
      _ => {return false; }
    };
  }

  pure fn insert(e: E) -> PairingHeap<E> {
    return self.merge(PairingHeap(e));
  }

  pure fn find_min() -> (Option<E>, PairingHeap<E>) {
    match self {
      Empty_ => { return (None, self); }
      p@PairingHeap_(heap) => { return (Some(heap.head), p); }
    }
  }

  // Deletes the minimum item without returning it
  pure fn delete_min() -> (Option<E>, PairingHeap<E>) {
    match self {
      Empty_ => {(None, self)}
      PairingHeap_(heap) => {(Some(heap.head), self.mergePairs(heap.rest))}
    }
  }

  pure fn merge(other: PairingHeap<E>) -> PairingHeap<E> {
    match (self, other) {
      (Empty_, b) => { return b; }
      (a, Empty_) => { return a; }
      (x@PairingHeap_(heapA), y@PairingHeap_(heapB)) => {
        if (heapA.head.le(&heapB.head)) {
          return PairingHeap_(@{
            head: heapA.head,
            rest: @Cons(y, heapA.rest)
          });
        } else {
          return PairingHeap_(@{
            head: heapB.head,
            rest: @Cons(x, heapB.rest)
          });
        }
      }
    }
  }

  pure fn mergePairs(heaps: @List<PairingHeap<E>>) -> PairingHeap<E> {
    match heaps {
      // Why are @-signs required for pattern matching here?
      @Cons(a, @Cons(b, xs)) => {a.merge(b).merge(self.mergePairs(xs))}
      @Cons(elem, @Nil) => {elem}
      @Nil => {Empty()}
    }
  }
}

#[test]
fn test_heap_create() {
  let heap = PairingHeap(1);
  assert(!heap.is_empty());

  // inference fails on this without a type declaration.
  let heap : PairingHeap<()> = Empty();
  assert(heap.is_empty());
}

fn test_heap_insert() {
  let v1 = PairingHeap(10);
  let v2 = v1.insert(1);
  let (one, v3) = v2.delete_min();
  let (ten, v4) = v3.delete_min();
  let (e, v5) = v4.delete_min();

  assert(one == Some(1));
  assert(ten == Some(10));
  assert(v4 == Empty_);
  assert(e == None);
  assert(v5 == Empty_);
}

fn test_heap_insert_delete_interleved() {
  let v1 = PairingHeap(10);
  let (a, v2) = v1.delete_min();
  assert(a == Some(10));
  assert(v2 == Empty_);

  let v3 = v2.insert(9);
  let v4 = v3.insert(8);
  let v5 = v4.insert(11);

  let (b, v6) = v5.delete_min();
  assert(b == Some(8));

  let v7 = v6.insert(7);
  let v8 = v7.insert(12);

  let (c, v9) = v8.delete_min();
  assert(c == Some(7));

  let (d, v10) = v9.delete_min();
  assert(d == Some(9));

  let (e, v11) = v10.delete_min();
  assert(e == Some(11));

  let (f, v12) = v11.delete_min();
  assert(f == Some(12));

  let (g, v13) = v12.delete_min();
  assert(g == None);
  assert(v13 == Empty_);
}

fn test_immutable_heap() {
  let heap = PairingHeap(10);
  let x1 = heap.insert(1);

  let (a, v1) = heap.delete_min();
  assert(a == Some(10));
  assert(v1 == Empty_);

  let (b, x2) = x1.delete_min();
  assert(b == Some(1));
  assert(x2 != Empty_);
}

<commit_msg>forgot to mark my tests as #[test]<commit_after>use core::cmp::{Eq, Ord};
use std::list;
use std::list::{List, Cons, Nil};

// I would really love for these to return Heaps but my knowledge
// of Rust is too limited to make that work.
pub trait Heap<E: Copy Eq Ord> {
  pure fn is_empty() -> bool;
  pure fn insert(elem: E) -> PairingHeap<E>;
  pure fn find_min() -> (Option<E>, PairingHeap<E>);
  pure fn delete_min() -> (Option<E>, PairingHeap<E>);
}

/**
 * A purely functional Pairing Heap [FSST86]
 *
 * Our implementation uses Linked List (cons cells) so may not be the
 * fastest way to implement this in Rust.
 *
 * This implementation is a port of the Standard ML found in Okasaki's
 * Purely Functional Data Structures.
 */
pub enum PairingHeap<E: Copy Eq Ord> {
  Empty_,
  PairingHeap_(@{
    head: E,
    rest: @List<PairingHeap<E>>
  })
}

pure fn Empty<E: Copy Eq Ord>() -> PairingHeap<E> {
  return Empty_;
}

pure fn PairingHeap<E: Copy Eq Ord>(initial_value: E) -> PairingHeap<E> {
  return PairingHeap_(@{
    head: initial_value,
    rest: @Nil
  });
}

impl<E: Copy Eq Ord> PairingHeap<E> : Eq {
  pure fn eq(other: &PairingHeap<E>) -> bool {
    match (self, *other) {
      (Empty_, Empty_) => {true}
      (PairingHeap_(heapA), PairingHeap_(heapB)) => {
        return (heapA.head == heapB.head) && (heapA.rest == heapB.rest);
      }
      //(Empty_, PairingHeap_(_)) => {false} // why are these unreachable?
      //(PairingHeap_(_), Empty) => {false}
      (_, _) => {false}
    }
  }

  pure fn ne(other: &PairingHeap<E>) -> bool { !(self).eq(other) }
}

impl<E: Copy Eq Ord> PairingHeap<E> : Heap<E> {
  pure fn is_empty() -> bool {
    match self {
      Empty_ => { return true; }
      _ => {return false; }
    };
  }

  pure fn insert(e: E) -> PairingHeap<E> {
    return self.merge(PairingHeap(e));
  }

  pure fn find_min() -> (Option<E>, PairingHeap<E>) {
    match self {
      Empty_ => { return (None, self); }
      p@PairingHeap_(heap) => { return (Some(heap.head), p); }
    }
  }

  // Deletes the minimum item without returning it
  pure fn delete_min() -> (Option<E>, PairingHeap<E>) {
    match self {
      Empty_ => {(None, self)}
      PairingHeap_(heap) => {(Some(heap.head), self.mergePairs(heap.rest))}
    }
  }

  pure fn merge(other: PairingHeap<E>) -> PairingHeap<E> {
    match (self, other) {
      (Empty_, b) => { return b; }
      (a, Empty_) => { return a; }
      (x@PairingHeap_(heapA), y@PairingHeap_(heapB)) => {
        if (heapA.head.le(&heapB.head)) {
          return PairingHeap_(@{
            head: heapA.head,
            rest: @Cons(y, heapA.rest)
          });
        } else {
          return PairingHeap_(@{
            head: heapB.head,
            rest: @Cons(x, heapB.rest)
          });
        }
      }
    }
  }

  pure fn mergePairs(heaps: @List<PairingHeap<E>>) -> PairingHeap<E> {
    match heaps {
      // Why are @-signs required for pattern matching here?
      @Cons(a, @Cons(b, xs)) => {a.merge(b).merge(self.mergePairs(xs))}
      @Cons(elem, @Nil) => {elem}
      @Nil => {Empty()}
    }
  }
}

#[test]
fn test_heap_create() {
  let heap = PairingHeap(1);
  assert(!heap.is_empty());

  // inference fails on this without a type declaration.
  let heap : PairingHeap<()> = Empty();
  assert(heap.is_empty());
}

#[test]
fn test_heap_insert() {
  let v1 = PairingHeap(10);
  let v2 = v1.insert(1);
  let (one, v3) = v2.delete_min();
  let (ten, v4) = v3.delete_min();
  let (e, v5) = v4.delete_min();

  assert(one == Some(1));
  assert(ten == Some(10));
  assert(v4 == Empty_);
  assert(e == None);
  assert(v5 == Empty_);
}

#[test]
fn test_heap_insert_delete_interleved() {
  let v1 = PairingHeap(10);
  let (a, v2) = v1.delete_min();
  assert(a == Some(10));
  assert(v2 == Empty_);

  let v3 = v2.insert(9);
  let v4 = v3.insert(8);
  let v5 = v4.insert(11);

  let (b, v6) = v5.delete_min();
  assert(b == Some(8));

  let v7 = v6.insert(7);
  let v8 = v7.insert(12);

  let (c, v9) = v8.delete_min();
  assert(c == Some(7));

  let (d, v10) = v9.delete_min();
  assert(d == Some(9));

  let (e, v11) = v10.delete_min();
  assert(e == Some(11));

  let (f, v12) = v11.delete_min();
  assert(f == Some(12));

  let (g, v13) = v12.delete_min();
  assert(g == None);
  assert(v13 == Empty_);
}

#[test]
fn test_immutable_heap() {
  let heap = PairingHeap(10);
  let x1 = heap.insert(1);

  let (a, v1) = heap.delete_min();
  assert(a == Some(10));
  assert(v1 == Empty_);

  let (b, x2) = x1.delete_min();
  assert(b == Some(1));
  assert(x2 != Empty_);
}

<|endoftext|>


<commit_before>use crate::clean;
use crate::docfs::PathError;
use crate::error::Error;
use crate::fold::DocFolder;
use crate::html::format::Buffer;
use crate::html::highlight;
use crate::html::layout;
use crate::html::render::{SharedContext, BASIC_KEYWORDS};
use rustc_hir::def_id::LOCAL_CRATE;
use rustc_session::Session;
use rustc_span::edition::Edition;
use rustc_span::source_map::FileName;
use std::ffi::OsStr;
use std::fs;
use std::path::{Component, Path, PathBuf};

crate fn render(
    dst: &Path,
    scx: &mut SharedContext<'_>,
    krate: clean::Crate,
) -> Result<clean::Crate, Error> {
    info!("emitting source files");
    let dst = dst.join("src").join(&*krate.name.as_str());
    scx.ensure_dir(&dst)?;
    let mut folder = SourceCollector { dst, scx };
    Ok(folder.fold_crate(krate))
}

/// Helper struct to render all source code to HTML pages
struct SourceCollector<'a, 'tcx> {
    scx: &'a mut SharedContext<'tcx>,

    /// Root destination to place all HTML output into
    dst: PathBuf,
}

impl DocFolder for SourceCollector<'_, '_> {
    fn fold_item(&mut self, item: clean::Item) -> Option<clean::Item> {
        // If we're not rendering sources, there's nothing to do.
        // If we're including source files, and we haven't seen this file yet,
        // then we need to render it out to the filesystem.
        if self.scx.include_sources
            // skip all synthetic "files"
            && item.span.filename(self.sess()).is_real()
            // skip non-local files
            && item.span.cnum(self.sess()) == LOCAL_CRATE
        {
            let filename = item.span.filename(self.sess());
            // If it turns out that we couldn't read this file, then we probably
            // can't read any of the files (generating html output from json or
            // something like that), so just don't include sources for the
            // entire crate. The other option is maintaining this mapping on a
            // per-file basis, but that's probably not worth it...
            self.scx.include_sources = match self.emit_source(&filename) {
                Ok(()) => true,
                Err(e) => {
                    println!(
                        "warning: source code was requested to be rendered, \
                         but processing `{}` had an error: {}",
                        filename, e
                    );
                    println!("         skipping rendering of source code");
                    false
                }
            };
        }
        // FIXME: if `include_sources` isn't set and DocFolder didn't require consuming the crate by value,
        // we could return None here without having to walk the rest of the crate.
        Some(self.fold_item_recur(item))
    }
}

impl SourceCollector<'_, 'tcx> {
    fn sess(&self) -> &'tcx Session {
        &self.scx.tcx.sess
    }

    /// Renders the given filename into its corresponding HTML source file.
    fn emit_source(&mut self, filename: &FileName) -> Result<(), Error> {
        let p = match *filename {
            FileName::Real(ref file) => file.local_path().to_path_buf(),
            _ => return Ok(()),
        };
        if self.scx.local_sources.contains_key(&*p) {
            // We've already emitted this source
            return Ok(());
        }

        let contents = match fs::read_to_string(&p) {
            Ok(contents) => contents,
            Err(e) => {
                return Err(Error::new(e, &p));
            }
        };

        // Remove the utf-8 BOM if any
        let contents = if contents.starts_with('\u{feff}') { &contents[3..] } else { &contents };

        // Create the intermediate directories
        let mut cur = self.dst.clone();
        let mut root_path = String::from("../../");
        let mut href = String::new();
        clean_path(&self.scx.src_root, &p, false, |component| {
            cur.push(component);
            root_path.push_str("../");
            href.push_str(&component.to_string_lossy());
            href.push('/');
        });
        self.scx.ensure_dir(&cur)?;

        let src_fname = p.file_name().expect("source has no filename").to_os_string();
        let mut fname = src_fname.clone();
        fname.push(".html");
        cur.push(&fname);
        href.push_str(&fname.to_string_lossy());

        let title = format!("{} - source", src_fname.to_string_lossy());
        let desc = format!("Source of the Rust file `{}`.", filename);
        let page = layout::Page {
            title: &title,
            css_class: "source",
            root_path: &root_path,
            static_root_path: self.scx.static_root_path.as_deref(),
            description: &desc,
            keywords: BASIC_KEYWORDS,
            resource_suffix: &self.scx.resource_suffix,
            extra_scripts: &[&format!("source-files{}", self.scx.resource_suffix)],
            static_extra_scripts: &[&format!("source-script{}", self.scx.resource_suffix)],
        };
        let v = layout::render(
            &self.scx.layout,
            &page,
            "",
            |buf: &mut _| print_src(buf, contents, self.scx.edition),
            &self.scx.style_files,
        );
        self.scx.fs.write(&cur, v.as_bytes())?;
        self.scx.local_sources.insert(p, href);
        Ok(())
    }
}

/// Takes a path to a source file and cleans the path to it. This canonicalizes
/// things like ".." to components which preserve the "top down" hierarchy of a
/// static HTML tree. Each component in the cleaned path will be passed as an
/// argument to `f`. The very last component of the path (ie the file name) will
/// be passed to `f` if `keep_filename` is true, and ignored otherwise.
crate fn clean_path<F>(src_root: &Path, p: &Path, keep_filename: bool, mut f: F)
where
    F: FnMut(&OsStr),
{
    // make it relative, if possible
    let p = p.strip_prefix(src_root).unwrap_or(p);

    let mut iter = p.components().peekable();

    while let Some(c) = iter.next() {
        if !keep_filename && iter.peek().is_none() {
            break;
        }

        match c {
            Component::ParentDir => f("up".as_ref()),
            Component::Normal(c) => f(c),
            _ => continue,
        }
    }
}

/// Wrapper struct to render the source code of a file. This will do things like
/// adding line numbers to the left-hand side.
fn print_src(buf: &mut Buffer, s: &str, edition: Edition) {
    let lines = s.lines().count();
    let mut cols = 0;
    let mut tmp = lines;
    while tmp > 0 {
        cols += 1;
        tmp /= 10;
    }
    buf.write_str("
");
    for i in 1..=lines {
        write!(buf, "{0:1$}\n", i, cols);
    }
    buf.write_str("
");
    highlight::render_with_highlighting(s, buf, None, None, None, edition);
}
<commit_msg>rustdoc: Use diagnostics for error when including sources<commit_after>use crate::clean;
use crate::docfs::PathError;
use crate::error::Error;
use crate::fold::DocFolder;
use crate::html::format::Buffer;
use crate::html::highlight;
use crate::html::layout;
use crate::html::render::{SharedContext, BASIC_KEYWORDS};
use rustc_hir::def_id::LOCAL_CRATE;
use rustc_session::Session;
use rustc_span::edition::Edition;
use rustc_span::source_map::FileName;
use std::ffi::OsStr;
use std::fs;
use std::path::{Component, Path, PathBuf};

crate fn render(
    dst: &Path,
    scx: &mut SharedContext<'_>,
    krate: clean::Crate,
) -> Result<clean::Crate, Error> {
    info!("emitting source files");
    let dst = dst.join("src").join(&*krate.name.as_str());
    scx.ensure_dir(&dst)?;
    let mut folder = SourceCollector { dst, scx };
    Ok(folder.fold_crate(krate))
}

/// Helper struct to render all source code to HTML pages
struct SourceCollector<'a, 'tcx> {
    scx: &'a mut SharedContext<'tcx>,

    /// Root destination to place all HTML output into
    dst: PathBuf,
}

impl DocFolder for SourceCollector<'_, '_> {
    fn fold_item(&mut self, item: clean::Item) -> Option<clean::Item> {
        // If we're not rendering sources, there's nothing to do.
        // If we're including source files, and we haven't seen this file yet,
        // then we need to render it out to the filesystem.
        if self.scx.include_sources
            // skip all synthetic "files"
            && item.span.filename(self.sess()).is_real()
            // skip non-local files
            && item.span.cnum(self.sess()) == LOCAL_CRATE
        {
            let filename = item.span.filename(self.sess());
            // If it turns out that we couldn't read this file, then we probably
            // can't read any of the files (generating html output from json or
            // something like that), so just don't include sources for the
            // entire crate. The other option is maintaining this mapping on a
            // per-file basis, but that's probably not worth it...
            self.scx.include_sources = match self.emit_source(&filename) {
                Ok(()) => true,
                Err(e) => {
                    self.scx.tcx.sess.span_err(
                        item.span.inner(),
                        &format!("failed to render source code for `{}`: {}", filename, e),
                    );
                    false
                }
            };
        }
        // FIXME: if `include_sources` isn't set and DocFolder didn't require consuming the crate by value,
        // we could return None here without having to walk the rest of the crate.
        Some(self.fold_item_recur(item))
    }
}

impl SourceCollector<'_, 'tcx> {
    fn sess(&self) -> &'tcx Session {
        &self.scx.tcx.sess
    }

    /// Renders the given filename into its corresponding HTML source file.
    fn emit_source(&mut self, filename: &FileName) -> Result<(), Error> {
        let p = match *filename {
            FileName::Real(ref file) => file.local_path().to_path_buf(),
            _ => return Ok(()),
        };
        if self.scx.local_sources.contains_key(&*p) {
            // We've already emitted this source
            return Ok(());
        }

        let contents = match fs::read_to_string(&p) {
            Ok(contents) => contents,
            Err(e) => {
                return Err(Error::new(e, &p));
            }
        };

        // Remove the utf-8 BOM if any
        let contents = if contents.starts_with('\u{feff}') { &contents[3..] } else { &contents };

        // Create the intermediate directories
        let mut cur = self.dst.clone();
        let mut root_path = String::from("../../");
        let mut href = String::new();
        clean_path(&self.scx.src_root, &p, false, |component| {
            cur.push(component);
            root_path.push_str("../");
            href.push_str(&component.to_string_lossy());
            href.push('/');
        });
        self.scx.ensure_dir(&cur)?;

        let src_fname = p.file_name().expect("source has no filename").to_os_string();
        let mut fname = src_fname.clone();
        fname.push(".html");
        cur.push(&fname);
        href.push_str(&fname.to_string_lossy());

        let title = format!("{} - source", src_fname.to_string_lossy());
        let desc = format!("Source of the Rust file `{}`.", filename);
        let page = layout::Page {
            title: &title,
            css_class: "source",
            root_path: &root_path,
            static_root_path: self.scx.static_root_path.as_deref(),
            description: &desc,
            keywords: BASIC_KEYWORDS,
            resource_suffix: &self.scx.resource_suffix,
            extra_scripts: &[&format!("source-files{}", self.scx.resource_suffix)],
            static_extra_scripts: &[&format!("source-script{}", self.scx.resource_suffix)],
        };
        let v = layout::render(
            &self.scx.layout,
            &page,
            "",
            |buf: &mut _| print_src(buf, contents, self.scx.edition),
            &self.scx.style_files,
        );
        self.scx.fs.write(&cur, v.as_bytes())?;
        self.scx.local_sources.insert(p, href);
        Ok(())
    }
}

/// Takes a path to a source file and cleans the path to it. This canonicalizes
/// things like ".." to components which preserve the "top down" hierarchy of a
/// static HTML tree. Each component in the cleaned path will be passed as an
/// argument to `f`. The very last component of the path (ie the file name) will
/// be passed to `f` if `keep_filename` is true, and ignored otherwise.
crate fn clean_path<F>(src_root: &Path, p: &Path, keep_filename: bool, mut f: F)
where
    F: FnMut(&OsStr),
{
    // make it relative, if possible
    let p = p.strip_prefix(src_root).unwrap_or(p);

    let mut iter = p.components().peekable();

    while let Some(c) = iter.next() {
        if !keep_filename && iter.peek().is_none() {
            break;
        }

        match c {
            Component::ParentDir => f("up".as_ref()),
            Component::Normal(c) => f(c),
            _ => continue,
        }
    }
}

/// Wrapper struct to render the source code of a file. This will do things like
/// adding line numbers to the left-hand side.
fn print_src(buf: &mut Buffer, s: &str, edition: Edition) {
    let lines = s.lines().count();
    let mut cols = 0;
    let mut tmp = lines;
    while tmp > 0 {
        cols += 1;
        tmp /= 10;
    }
    buf.write_str("
");
    for i in 1..=lines {
        write!(buf, "{0:1$}\n", i, cols);
    }
    buf.write_str("
");
    highlight::render_with_highlighting(s, buf, None, None, None, edition);
}
<|endoftext|>


<commit_before>#![feature(test)]
#[macro_use]
extern crate adapton ;

mod fact {
    #[cfg(test)]
    mod no_caching {
        extern crate test;
        use self::test::Bencher;

        pub fn fact (x:u64) -> u64 {
            if x == 0 { 1 } else { x * fact(x-1) }
        }

        pub fn fact_repeat (x:u64, n:u64) -> u64 {
            for _ in 1..(n-1) {
                fact(x);
            }
            fact(x)
        }

        #[test]
        fn it_works() {
            assert_eq!(120 as u64, fact(5));
        }

        #[bench]
        fn bench_fact(b: &mut Bencher) {
            b.iter(|| fact(1000));
        }

        #[bench]
        fn bench_fact_repeat(b: &mut Bencher) {
            b.iter(|| fact_repeat(100, 1000));
        }
    }

    #[cfg(test)]
    mod pure_caching {
        extern crate test;
        use self::test::Bencher;

        use std::mem::replace;
        use std::rc::Rc;

        use adapton::adapton_syntax::* ;
        use adapton::adapton_sigs::* ;
        use adapton::adapton_state::* ;

        pub fn fact<A:Adapton> (st:&mut A, x:u64, _n:() ) -> u64 {
            if x == 0 { 1 } else { x * (memo!(st, fact, x:x-1, _n:())) }
        }

        pub fn run_fact (x:u64) -> u64 {
            let mut st = &mut (AdaptonState::new()) ;
            memo!(st, fact, x:x, _n:())
        }

        pub fn run_fact_repeat (x:u64, n:u64) -> u64 {
            let mut st = &mut (AdaptonState::new()) ;
            for _ in 1..(n-1) {
                memo!(st, fact, x:x, _n:());
            }
            memo!(st, fact, x:x, _n:())
        }

        #[test]
        fn it_works() {
            assert_eq!(120 as u64, run_fact(5));
        }

        #[bench]
        fn bench_fact(b: &mut Bencher) {
            b.iter(|| run_fact(100));
        }

        #[bench]
        fn bench_fact_repeat(b: &mut Bencher) {
            b.iter(|| run_fact_repeat(100, 100));
        }
    }
}
<commit_msg>fixed unwanted opt on benches<commit_after>#![feature(test)]
#[macro_use]
extern crate adapton ;

mod fact {
    #[cfg(test)]
    mod no_caching {
        extern crate test;
        use self::test::Bencher;

        pub fn fact (x:u64) -> u64 {
            if x == 0 { 1 } else { test::black_box(x) * fact(x-1) }
        }

        pub fn fact_repeat (x:u64, n:u64) -> u64 {
            for _ in 1..(n-1) {
                test::black_box(fact(x));
            }
            fact(x)
        }

        #[test]
        fn it_works() {
            assert_eq!(120 as u64, fact(5));
        }

        #[bench]
        fn bench_fact(b: &mut Bencher) {
            b.iter(|| test::black_box(fact(100)));
        }

        #[bench]
        fn bench_fact_repeat(b: &mut Bencher) {
            b.iter(|| test::black_box(fact_repeat(100, 100)));
        }
    }

    #[cfg(test)]
    mod pure_caching {
        extern crate test;
        use self::test::Bencher;

        use std::mem::replace;
        use std::rc::Rc;

        use adapton::adapton_syntax::* ;
        use adapton::adapton_sigs::* ;
        use adapton::adapton_state::* ;

        pub fn fact<A:Adapton> (st:&mut A, x:u64, _n:() ) -> u64 {
            if x == 0 { 1 } else { x * (memo!(st, fact, x:x-1, _n:())) }
        }

        pub fn run_fact (x:u64) -> u64 {
            let mut st = &mut (AdaptonState::new()) ;
            memo!(st, fact, x:x, _n:())
        }

        pub fn run_fact_repeat (x:u64, n:u64) -> u64 {
            let mut st = &mut (AdaptonState::new()) ;
            for _ in 1..(n-1) {
                memo!(st, fact, x:x, _n:());
            }
            memo!(st, fact, x:x, _n:())
        }

        #[test]
        fn it_works() {
            assert_eq!(120 as u64, run_fact(5));
        }

        #[bench]
        fn bench_fact(b: &mut Bencher) {
            b.iter(|| test::black_box(run_fact(100)));
        }

        #[bench]
        fn bench_fact_repeat(b: &mut Bencher) {
            b.iter(|| test::black_box(run_fact_repeat(100, 100)));
        }
    }
}
<|endoftext|>


<commit_before>#![feature(test)]
extern crate test;
extern crate rustfft;

use test::Bencher;
use rustfft::num_complex::Complex;

/// Times just the FFT execution (not allocation and pre-calculation)
/// for a given length
fn bench_fft(b: &mut Bencher, len: usize) {

    let mut planner = rustfft::FFTplanner::new(false);
    let fft = planner.plan_fft(len);

    let mut signal = vec![Complex{re: 0_f32, im: 0_f32}; len];
    let mut spectrum = signal.clone();
    b.iter(|| {fft.process(&mut signal, &mut spectrum);} );
}

// Powers of 4
#[bench] fn complex_p2_00000032(b: &mut Bencher) { bench_fft(b,       32); }
#[bench] fn complex_p2_00000064(b: &mut Bencher) { bench_fft(b,       64); }
#[bench] fn complex_p2_00000256(b: &mut Bencher) { bench_fft(b,      256); }
#[bench] fn complex_p2_00001024(b: &mut Bencher) { bench_fft(b,     1024); }
#[bench] fn complex_p2_00004096(b: &mut Bencher) { bench_fft(b,     4096); }
#[bench] fn complex_p2_00016384(b: &mut Bencher) { bench_fft(b,    16384); }
#[bench] fn complex_p2_00065536(b: &mut Bencher) { bench_fft(b,    65536); }
#[bench] fn complex_p2_01048576(b: &mut Bencher) { bench_fft(b,  1048576); }
#[bench] fn complex_p2_08388608(b: &mut Bencher) { bench_fft(b,  8388608); }
#[bench] fn complex_p2_16777216(b: &mut Bencher) { bench_fft(b, 16777216); }

// Powers of 7
#[bench] fn complex_p7_00343(b: &mut Bencher) { bench_fft(b,   343); }
#[bench] fn complex_p7_02401(b: &mut Bencher) { bench_fft(b,  2401); }
#[bench] fn complex_p7_16807(b: &mut Bencher) { bench_fft(b, 16807); }

// Prime lengths
#[bench] fn complex_prime_0019(b: &mut Bencher) { bench_fft(b, 19); }
#[bench] fn complex_prime_0151(b: &mut Bencher) { bench_fft(b, 151); }
#[bench] fn complex_prime_1009(b: &mut Bencher) { bench_fft(b, 1009); }
#[bench] fn complex_prime_2017(b: &mut Bencher) { bench_fft(b, 2017); }

//primes raised to a power
#[bench] fn complex_primepower_44521(b: &mut Bencher) { bench_fft(b, 44521); } // 211^2
#[bench] fn complex_primepower_160801(b: &mut Bencher) { bench_fft(b, 160801); } // 401^2

// numbers times powers of two
#[bench] fn complex_composite_24576(b: &mut Bencher) { bench_fft(b,  24576); }
#[bench] fn complex_composite_20736(b: &mut Bencher) { bench_fft(b,  20736); }

// power of 2 times large prime
#[bench] fn complex_composite_32192(b: &mut Bencher) { bench_fft(b,  32192); }
#[bench] fn complex_composite_24028(b: &mut Bencher) { bench_fft(b,  24028); }

// small mixed composites times a large prime
#[bench] fn complex_composite_30270(b: &mut Bencher) { bench_fft(b,  30270); }<commit_msg>Removed unnecessary benchmarks<commit_after>#![feature(test)]
extern crate test;
extern crate rustfft;

use test::Bencher;
use rustfft::num_complex::Complex;

/// Times just the FFT execution (not allocation and pre-calculation)
/// for a given length
fn bench_fft(b: &mut Bencher, len: usize) {

    let mut planner = rustfft::FFTplanner::new(false);
    let fft = planner.plan_fft(len);

    let mut signal = vec![Complex{re: 0_f32, im: 0_f32}; len];
    let mut spectrum = signal.clone();
    b.iter(|| {fft.process(&mut signal, &mut spectrum);} );
}

// Powers of 4
#[bench] fn complex_p2_00000064(b: &mut Bencher) { bench_fft(b,       64); }
#[bench] fn complex_p2_00000256(b: &mut Bencher) { bench_fft(b,      256); }
#[bench] fn complex_p2_00001024(b: &mut Bencher) { bench_fft(b,     1024); }
#[bench] fn complex_p2_00004096(b: &mut Bencher) { bench_fft(b,     4096); }
#[bench] fn complex_p2_00016384(b: &mut Bencher) { bench_fft(b,    16384); }
#[bench] fn complex_p2_00065536(b: &mut Bencher) { bench_fft(b,    65536); }
#[bench] fn complex_p2_01048576(b: &mut Bencher) { bench_fft(b,  1048576); }
#[bench] fn complex_p2_16777216(b: &mut Bencher) { bench_fft(b, 16777216); }

// Powers of 7
#[bench] fn complex_p7_00343(b: &mut Bencher) { bench_fft(b,   343); }
#[bench] fn complex_p7_02401(b: &mut Bencher) { bench_fft(b,  2401); }
#[bench] fn complex_p7_16807(b: &mut Bencher) { bench_fft(b, 16807); }

// Prime lengths
#[bench] fn complex_prime_0019(b: &mut Bencher) { bench_fft(b, 19); }
#[bench] fn complex_prime_0151(b: &mut Bencher) { bench_fft(b, 151); }
#[bench] fn complex_prime_1009(b: &mut Bencher) { bench_fft(b, 1009); }
#[bench] fn complex_prime_2017(b: &mut Bencher) { bench_fft(b, 2017); }

//primes raised to a power
#[bench] fn complex_primepower_44521(b: &mut Bencher) { bench_fft(b, 44521); } // 211^2
#[bench] fn complex_primepower_160801(b: &mut Bencher) { bench_fft(b, 160801); } // 401^2

// numbers times powers of two
#[bench] fn complex_composite_24576(b: &mut Bencher) { bench_fft(b,  24576); }
#[bench] fn complex_composite_20736(b: &mut Bencher) { bench_fft(b,  20736); }

// power of 2 times large prime
#[bench] fn complex_composite_32192(b: &mut Bencher) { bench_fft(b,  32192); }
#[bench] fn complex_composite_24028(b: &mut Bencher) { bench_fft(b,  24028); }

// small mixed composites times a large prime
#[bench] fn complex_composite_30270(b: &mut Bencher) { bench_fft(b,  30270); }<|endoftext|>


<commit_before>#[derive(Debug)]
enum Direction {
    Diagonal,
    Up,
    Left,
}

use Direction::*;
use std::cmp::max;

fn get_hsp(w1: &String, w2: &String, match_scr: i32, mism_scr: i32, gap_scr: i32) -> i32 {
    let mut hsp = 0;

    let mut chars2 = w2.chars();
    for c1 in w1.chars() {
        let c2 = chars2.next().unwrap();
        hsp += if c1 == c2 {
            match_scr
        } else if c1 == '_' || c2 == '_' {
            gap_scr
        } else {
            mism_scr
        }
    }

    hsp
}

fn get_score(a: char, b: char) -> i32 {
    if a == b { 1 } else { -1 }
}

fn align_secuence(sec_1: &str, sec_2: &str) -> (String, String) {
    let len_1 = sec_1.len() + 1;
    let len_2 = sec_2.len() + 1;

    /********* Initialize matrix **********/
    let mut matrix: Vec<Vec<i32>> = vec![vec![0; len_1]; len_2];

    let mut init_val = -5;
    for i in 1..len_1 {
        matrix[0][i] = init_val;
        init_val -= 5;
    }

    init_val = -5;
    for i in 1..len_2 {
        matrix[i][0] = init_val;
        init_val -= 5;
    }
    /**************************************/

    let mut diag_val;
    let mut left_val;
    let mut uppr_val;

    let mut i = 1;
    let mut j;
    for c2 in sec_2.chars() {
        j = 1;
        for c1 in sec_1.chars() {
            let score = get_score(c2, c1);
            diag_val = score + matrix[i - 1][j - 1];
            left_val = -2 + matrix[i][j - 1];
            uppr_val = -2 + matrix[i - 1][j];
            matrix[i][j] = max(diag_val, max(left_val, uppr_val));
            j += 1;
        }
        i += 1;
    }

    /************** Alignment **************/
    let mut align1 = String::new();
    let mut align2 = String::new();

    i = sec_2.len();
    j = sec_1.len();

    let mut direct = Diagonal;
    let mut greater;
    loop {
        if i == 0 || j == 0 {
            break;
        }

        diag_val = matrix[i - 1][j - 1];
        left_val = matrix[i][j - 1];
        uppr_val = matrix[i - 1][j];
        greater = max(diag_val, max(left_val, uppr_val));

        match direct {
            Diagonal => {
                align1.push(sec_1.as_bytes()[j - 1] as char);
                align2.push(sec_2.as_bytes()[i - 1] as char);
            }
            Up => {
                align1.push('_');
                align2.push(sec_2.as_bytes()[i - 1] as char);
            }
            Left => {
                align1.push(sec_1.as_bytes()[j - 1] as char);
                align2.push('_');
            }
        }

        if greater == diag_val {
            direct = Diagonal;
            i -= 1;
            j -= 1;
        } else if greater == left_val {
            direct = Left;
            j -= 1;
        } else if greater == uppr_val {
            direct = Up;
            i -= 1;
        }
    }
    /****************************************/

    align1 = align1.chars().rev().collect::<String>();
    align2 = align2.chars().rev().collect::<String>();

    (align2, align1)
}

fn tps_alignment(seqs: Vec<&str>) {
    let len = seqs.len();

    let m
    for i in 0..len {
        let mut j = i + 1;
        while j < len {
            let aligns = align_secuence(seqs[i], seqs[j]);
            println!("{}", get_hsp(&aligns.0, &aligns.1, 0, 3, 2));
            j += 1;
        }
    }
}

fn main() {
    let seqs: Vec<&str> = vec!["ACTCAT",
                               "AGTCAT",
                               "ACGTCCT"];
    tps_alignment(seqs);
}
<commit_msg>Actualiado<commit_after>#[derive(Debug)]
enum Direction {
    Diagonal,
    Up,
    Left,
}

use Direction::*;
use std::cmp::max;

fn get_hsp(w1: &String, w2: &String, match_scr: i32, mism_scr: i32, gap_scr: i32) -> i32 {
    let mut hsp = 0;

    let mut chars2 = w2.chars();
    for c1 in w1.chars() {
        let c2 = chars2.next().unwrap();
        hsp += if c1 == c2 {
            match_scr
        } else if c1 == '_' || c2 == '_' {
            gap_scr
        } else {
            mism_scr
        }
    }

    hsp
}

fn get_score(a: char, b: char) -> i32 {
    if a == b { 1 } else { -1 }
}

// fn print_matrix(seq_vec: &Vec<String>, seq: &String, mtrx: &Vec<Vec<i32>>) {
//     print!("\t\t");
//     for chr in sec_1.chars() {
//         print!(" {}\t", chr);
//     }
//     print!("\n\t");

//     for elem in mtrx[0].iter() {
//         print!("{}\t", elem);
//     }
//     println!("");

//     let mut i: usize = 1;
//     for chr in sec_2.chars() {
//         print!("{}\t", chr);
//         for elem in mtrx[i].iter() {
//             print!("{}\t", elem);
//         }
//         println!("");
//         i += 1;
//     }
// }

fn align_secuence(sec_1: &str, sec_2: &str) -> (String, String) {
    let len_1 = sec_1.len() + 1;
    let len_2 = sec_2.len() + 1;

    /********* Initialize matrix **********/
    let mut matrix: Vec<Vec<i32>> = vec![vec![0; len_1]; len_2];

    let mut init_val = -5;
    for i in 1..len_1 {
        matrix[0][i] = init_val;
        init_val -= 5;
    }

    init_val = -5;
    for i in 1..len_2 {
        matrix[i][0] = init_val;
        init_val -= 5;
    }
    /**************************************/

    let mut diag_val;
    let mut left_val;
    let mut uppr_val;

    let mut i = 1;
    let mut j;
    for c2 in sec_2.chars() {
        j = 1;
        for c1 in sec_1.chars() {
            let score = get_score(c2, c1);
            diag_val = score + matrix[i - 1][j - 1];
            left_val = -2 + matrix[i][j - 1];
            uppr_val = -2 + matrix[i - 1][j];
            matrix[i][j] = max(diag_val, max(left_val, uppr_val));
            j += 1;
        }
        i += 1;
    }

    /************** Alignment **************/
    let mut align1 = String::new();
    let mut align2 = String::new();

    i = sec_2.len();
    j = sec_1.len();

    let mut direct = Diagonal;
    let mut greater;
    loop {
        if i == 0 || j == 0 {
            break;
        }

        diag_val = matrix[i - 1][j - 1];
        left_val = matrix[i][j - 1];
        uppr_val = matrix[i - 1][j];
        greater = max(diag_val, max(left_val, uppr_val));

        match direct {
            Diagonal => {
                align1.push(sec_1.as_bytes()[j - 1] as char);
                align2.push(sec_2.as_bytes()[i - 1] as char);
            }
            Up => {
                align1.push('_');
                align2.push(sec_2.as_bytes()[i - 1] as char);
            }
            Left => {
                align1.push(sec_1.as_bytes()[j - 1] as char);
                align2.push('_');
            }
        }

        if greater == diag_val {
            direct = Diagonal;
            i -= 1;
            j -= 1;
        } else if greater == left_val {
            direct = Left;
            j -= 1;
        } else if greater == uppr_val {
            direct = Up;
            i -= 1;
        }
    }
    /****************************************/

    align1 = align1.chars().rev().collect::<String>();
    align2 = align2.chars().rev().collect::<String>();

    (align2, align1)
}

fn align_seqs(mut seq_vec: Vec<String>, mut seq: String) {
    /********* Initialize sequences **********/
    seq = String::from("_") + seq.as_ref();

    for sec in seq_vec.iter_mut() {
        *sec = String::from("_") + sec.as_ref();
    }
    /********* Initialize matrix **********/
    let len_1 = seq_vec[0].len();
    let len_2 = seq.len();

    let mut matrix: Vec<Vec<i32>> = vec![vec![0; len_1]; len_2];
    /**************************************/

    println!("{}", seq);
    println!("{:?}", seq_vec);
}

fn tps_alignment(seqs: Vec<&str>) {
    let len = seqs.len();

    let mut my_vec = Vec::new();
    for i in 0..len {
        let mut j = i + 1;
        while j < len {
            let aligns = align_secuence(seqs[i], seqs[j]);
            my_vec.push((get_hsp(&aligns.0, &aligns.1, 0, 3, 2), i, j, aligns.0, aligns.1));
            j += 1;
        }
    }

    my_vec.sort_by(|a, b| a.0.cmp(&b.0));
    // println!("{:?}", my_vec);

    let mut first = Vec::new();
    first.push(my_vec[0].4.clone());
    first.push(my_vec[0].3.clone());
    let second = my_vec[2].3.clone();

    align_seqs(first, second);
}

fn main() {
    let seqs: Vec<&str> = vec!["ACTCAT",
                               "AGTCAT",
                               "ACGTCCT"];

    tps_alignment(seqs);
}
<|endoftext|>


<commit_before>#![allow(missing_docs)]

use std::cmp;
use std::io;
use std::slice;

trait IntoBufRead {
    type IntoBuf: io::BufRead + BufReadExt;

    fn into_buf_read(self) -> Self::IntoBuf;
}

trait BufReadExt {
    fn get_buf(&self) -> &[u8];
    fn read_u8(&mut self) -> io::Result<Option<u8>>;
}

struct SliceReader<'a> {
    buf: &'a [u8],
}

impl<'a> io::Read for SliceReader<'a> {
    #[inline]
    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
        let amt = cmp::min(buf.len(), self.buf.len());
        let (a, b) = self.buf.split_at(amt);
        slice::bytes::copy_memory(buf, a);
        *self.buf = b;
        Ok(amt)
    }
}

impl<'a> io::BufRead for SliceReader<'a> {
    fn fill_buf(&mut self) -> io::Result<&[u8]> { Ok(*self) }
    fn consume(&mut self, amt: usize) { *self.buf = &self.buf[amt..]; }
}

impl<'a> BufReadExt for SliceReader<'a> {
    fn get_buf(&self) -> &[u8] { self.buf }
    fn read_u8(&mut self) -> io::Result<Option<u8>> {
        let byte = self.buf.get(0);
        *self.buf = &self.buf[1..];
        byte
    }
}

struct BufReader<R> {
    inner: R,
    buf: io::Cursor<Vec<u8>>,
}

impl<R> BufReader<R> where R: io::Read {
    fn new(inner: R) -> Self {
        BufferedReader::with_capacity(io::DEFAULT_BUF_SIZE, inner)
    }

    fn new(cap: usize, inner: R) -> Self {
        BufferedReader {
            inner: inner,
            buf: io::Cursor::new(Vec::with_capacity(cap)),
        }
    }

    fn into_inner(self) -> R {
        self.inner
    }
}

impl<R> Read for BufReader<R> where R: io::Read {
    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
        // If we don't have any buffered data and we're doing a massive read
        // (larger than our internal buffer), bypass our internal buffer
        // entirely.
        if self.buf.get_ref().len() == self.buf.position() as usize &&
            buf.len() >= self.buf.get_ref().capacity() {
            return self.inner.read(buf);
        }
        try!(self.fill_buf());
        self.buf.read(buf)
    }
}

impl<R> BufReadExt for BufReader<R> {
    fn get_buf(&self) -> &[u8] {
        self.buf.get_ref()
    }

    fn read_u8(&mut self) -> io::Result<Option<u8>> {
        if self.buf.get_ref().len() == self.buf.position() as usize {

        }
        let byte = self.buf.get(0);
        *self.buf = &self.buf[1..];
        byte
    }
}
<commit_msg>Remove unused buf module.<commit_after><|endoftext|>


<commit_before>extern crate odbc_sys;
extern crate odbc_safe;

use odbc_safe::*;

#[test]
fn allocate_environment() {
    Environment::new().unwrap();
}

#[test]
fn allocate_connection() {
    let env = Environment::new().unwrap();
    let env: Environment<Odbc3> = env.declare_version().unwrap();
    Connection::with_parent(&env).unwrap();
}

#[test]
#[should_panic]
fn wrong_datasource() {
    let env = Environment::new().unwrap();
    let env: Environment<Odbc3> = env.declare_version().unwrap();
    let dbc = Connection::with_parent(&env).unwrap();
    dbc.connect(b"DoesntExist" as &[u8], b"" as &[u8], b"" as &[u8])
        .unwrap();
}

#[test]
fn diagnostics() {

    let expected = if cfg!(target_os = "windows") {
        "[Microsoft][ODBC Driver Manager] Data source name not found and no default driver \
         specified"
    } else {
        "[unixODBC][Driver Manager]Data source name not found, and no default driver specified"
    };

    use std::str;

    let env = Environment::new().unwrap();
    let env: Environment<Odbc3> = env.declare_version().unwrap();

    let dbc = Connection::with_parent(&env).unwrap();
    let dbc = dbc.connect(b"DoesntExist" as &[u8], b"" as &[u8], b"" as &[u8]);
    if let Error(d) = dbc {
        let mut message = [0; 512];
        match d.diagnostics(1, &mut message) {
            DiagReturn::Success(rec) => {
                let message = str::from_utf8(&mut message[..(rec.text_length as usize)]).unwrap();
                assert_eq!(expected, message);
            }
            _ => panic!("Error retriving diagnostics"),
        }
    }
}

#[cfg_attr(not(feature = "travis"), ignore)]
#[test]
fn connect_to_postgres() {
    let env = Environment::new().unwrap();
    let env: Environment<Odbc3> = env.declare_version().unwrap();
    let dbc = Connection::with_parent(&env).unwrap();
    let dbc = dbc.connect(b"PostgreSQL" as &[u8], b"postgres" as &[u8], b"" as &[u8]);
    match dbc {
        Success(c) => panic_with_diagnostic(&c.disconnect()),
        Info(c) => panic_with_diagnostic(&c),
        Error(c) => panic_with_diagnostic(&c),
    };
}

#[cfg_attr(not(feature = "travis"), ignore)]
#[test]
fn query_result() {
    let env = Environment::new().unwrap();
    let env: Environment<Odbc3> = env.declare_version().unwrap();
    let dbc = Connection::with_parent(&env).unwrap();
    let dbc = dbc.connect(b"PostgreSQL" as &[u8], b"postgres" as &[u8], b"" as &[u8])
        .unwrap();
    {
        let stmt = Statement::with_parent(&dbc).unwrap();
        match stmt.exec_direct(b"SELECT * FROM information_schema.tables" as &[u8]) {
            ReturnNoData::Success(s) |
            ReturnNoData::Info(s) => {
                panic_with_diagnostic(&s);
                assert_eq!(0, s.num_result_cols());
            }
            ReturnNoData::NoData(_) => panic!("No Data"),
            ReturnNoData::Error(s) => {
                panic_with_diagnostic(&s);
            }
        }
    }
    dbc.disconnect().unwrap();
}

/// Checks for a diagnstic record. Should one be present this function panics printing the contents
/// of said record.
fn panic_with_diagnostic(diag: &Diagnostics) {
    use std::str;
    let mut buffer = [0; 512];
    match diag.diagnostics(1, &mut buffer) {
        DiagReturn::Success(dr) |
        DiagReturn::Info(dr) => {
            panic!(
                "{}",
                str::from_utf8(&buffer[0..(dr.text_length as usize)]).unwrap()
            )
        }
        DiagReturn::Error => panic!("Error during fetching diagnostic record"),
        DiagReturn::NoData => (),
    }
}
<commit_msg>unwrap result<commit_after>extern crate odbc_sys;
extern crate odbc_safe;

use odbc_safe::*;

#[test]
fn allocate_environment() {
    Environment::new().unwrap();
}

#[test]
fn allocate_connection() {
    let env = Environment::new().unwrap();
    let env: Environment<Odbc3> = env.declare_version().unwrap();
    Connection::with_parent(&env).unwrap();
}

#[test]
#[should_panic]
fn wrong_datasource() {
    let env = Environment::new().unwrap();
    let env: Environment<Odbc3> = env.declare_version().unwrap();
    let dbc = Connection::with_parent(&env).unwrap();
    dbc.connect(b"DoesntExist" as &[u8], b"" as &[u8], b"" as &[u8])
        .unwrap();
}

#[test]
fn diagnostics() {

    let expected = if cfg!(target_os = "windows") {
        "[Microsoft][ODBC Driver Manager] Data source name not found and no default driver \
         specified"
    } else {
        "[unixODBC][Driver Manager]Data source name not found, and no default driver specified"
    };

    use std::str;

    let env = Environment::new().unwrap();
    let env: Environment<Odbc3> = env.declare_version().unwrap();

    let dbc = Connection::with_parent(&env).unwrap();
    let dbc = dbc.connect(b"DoesntExist" as &[u8], b"" as &[u8], b"" as &[u8]);
    if let Error(d) = dbc {
        let mut message = [0; 512];
        match d.diagnostics(1, &mut message) {
            DiagReturn::Success(rec) => {
                let message = str::from_utf8(&mut message[..(rec.text_length as usize)]).unwrap();
                assert_eq!(expected, message);
            }
            _ => panic!("Error retriving diagnostics"),
        }
    }
}

#[cfg_attr(not(feature = "travis"), ignore)]
#[test]
fn connect_to_postgres() {
    let env = Environment::new().unwrap();
    let env: Environment<Odbc3> = env.declare_version().unwrap();
    let dbc = Connection::with_parent(&env).unwrap();
    let dbc = dbc.connect(b"PostgreSQL" as &[u8], b"postgres" as &[u8], b"" as &[u8]);
    match dbc {
        Success(c) => panic_with_diagnostic(&c.disconnect()),
        Info(c) => panic_with_diagnostic(&c),
        Error(c) => panic_with_diagnostic(&c),
    };
}

#[cfg_attr(not(feature = "travis"), ignore)]
#[test]
fn query_result() {
    let env = Environment::new().unwrap();
    let env: Environment<Odbc3> = env.declare_version().unwrap();
    let dbc = Connection::with_parent(&env).unwrap();
    let dbc = dbc.connect(b"PostgreSQL" as &[u8], b"postgres" as &[u8], b"" as &[u8])
        .unwrap();
    {
        let stmt = Statement::with_parent(&dbc).unwrap();
        match stmt.exec_direct(b"SELECT * FROM information_schema.tables" as &[u8]) {
            ReturnNoData::Success(s) |
            ReturnNoData::Info(s) => {
                panic_with_diagnostic(&s);
                assert_eq!(0, s.num_result_cols().unwrap());
            }
            ReturnNoData::NoData(_) => panic!("No Data"),
            ReturnNoData::Error(s) => {
                panic_with_diagnostic(&s);
            }
        }
    }
    dbc.disconnect().unwrap();
}

/// Checks for a diagnstic record. Should one be present this function panics printing the contents
/// of said record.
fn panic_with_diagnostic(diag: &Diagnostics) {
    use std::str;
    let mut buffer = [0; 512];
    match diag.diagnostics(1, &mut buffer) {
        DiagReturn::Success(dr) |
        DiagReturn::Info(dr) => {
            panic!(
                "{}",
                str::from_utf8(&buffer[0..(dr.text_length as usize)]).unwrap()
            )
        }
        DiagReturn::Error => panic!("Error during fetching diagnostic record"),
        DiagReturn::NoData => (),
    }
}
<|endoftext|>


<commit_before>extern crate capstone_sys;
extern crate libc;

use libc::{c_char, size_t};
use capstone_sys::*;

const X86_CODE16: &'static [u8] = b"\x8d\x4c\x32\x08\x01\xd8\x81\xc6\x34\x12\x00\x00\x05\x23\x01\x00\x00\x36\x8b\x84\x91\x23\x01\x00\x00\x41\x8d\x84\x39\x89\x67\x00\x00\x8d\x87\x89\x67\x00\x00\xb4\xc6";
const X86_CODE32: &'static [u8] = b"\x8d\x4c\x32\x08\x01\xd8\x81\xc6\x34\x12\x00\x00\x05\x23\x01\x00\x00\x36\x8b\x84\x91\x23\x01\x00\x00\x41\x8d\x84\x39\x89\x67\x00\x00\x8d\x87\x89\x67\x00\x00\xb4\xc6";
const X86_CODE64: &'static [u8] = b"\x55\x48\x8b\x05\xb8\x13\x00\x00";

fn to_str(raw: &[c_char]) -> &str {
    unsafe {
        ::std::ffi::CStr::from_ptr(raw.as_ptr()).to_str().expect("invalid UTF-8")
    }
}

fn generic(arch: cs_arch, mode: cs_mode, code: &[u8], expected_size: size_t, expected_first: (&str, &str)) {
    let mut handle: csh = 0;
    let err = unsafe { cs_open(arch, mode, &mut handle) };
    assert_eq!(err, CS_ERR_OK);

    let mut instrs: *mut cs_insn = ::std::ptr::null_mut();
    let size = unsafe { cs_disasm(handle, code.as_ptr(), code.len(), 0, 0 /* read as much as possible */, &mut instrs) };
    assert_eq!(size, expected_size);
    assert!(!instrs.is_null());

    let instr = unsafe { &*instrs };
    let (mnemonic, op_str) = expected_first;
    assert_eq!(to_str(&instr.mnemonic), mnemonic);
    assert_eq!(to_str(&instr.op_str), op_str);

    unsafe {
        cs_close(&mut handle);
    }
}

#[test]
fn test_x86_16() {
    generic(CS_ARCH_X86, CS_MODE_16, X86_CODE16, 15, ("lea", "cx, word ptr [si + 0x32]"));
}

#[test]
fn test_x86_32() {
    generic(CS_ARCH_X86, CS_MODE_32, X86_CODE32, 9, ("lea", "ecx, dword ptr [edx + esi + 8]"));
}

#[test]
fn test_x86_64() {
    generic(CS_ARCH_X86, CS_MODE_64, X86_CODE64, 2, ("push", "rbp"));
}
<commit_msg>Add detail introspection in x86 test<commit_after>extern crate capstone_sys;
extern crate libc;

use libc::{c_char, size_t};
use capstone_sys::*;
use capstone_sys::x86::*;

const X86_CODE16: &'static [u8] = b"\x8d\x4c\x32\x08\x01\xd8\x81\xc6\x34\x12\x00\x00\x05\x23\x01\x00\x00\x36\x8b\x84\x91\x23\x01\x00\x00\x41\x8d\x84\x39\x89\x67\x00\x00\x8d\x87\x89\x67\x00\x00\xb4\xc6";
const X86_CODE32: &'static [u8] = b"\x8d\x4c\x32\x08\x01\xd8\x81\xc6\x34\x12\x00\x00\x05\x23\x01\x00\x00\x36\x8b\x84\x91\x23\x01\x00\x00\x41\x8d\x84\x39\x89\x67\x00\x00\x8d\x87\x89\x67\x00\x00\xb4\xc6";
const X86_CODE64: &'static [u8] = b"\x55\x48\x8b\x05\xb8\x13\x00\x00";

fn to_str(raw: &[c_char]) -> &str {
    unsafe {
        ::std::ffi::CStr::from_ptr(raw.as_ptr()).to_str().expect("invalid UTF-8")
    }
}

fn generic(arch: cs_arch, mode: cs_mode, code: &[u8], expected_size: size_t, expected_first: (&str, &str, &[x86_op_type])) {
    let mut handle: csh = 0;
    let err = unsafe { cs_open(arch, mode, &mut handle) };
    assert_eq!(err, CS_ERR_OK);

    // let err = unsafe { cs_option(handle, CS_OPT_SYNTAX, CS_OPT_SYNTAX_ATT as size_t) };
    // assert_eq!(err, CS_ERR_OK);

    let err = unsafe { cs_option(handle, CS_OPT_DETAIL, CS_OPT_ON as size_t) };
    assert_eq!(err, CS_ERR_OK);

    let mut instrs: *mut cs_insn = ::std::ptr::null_mut();
    let size = unsafe { cs_disasm(handle, code.as_ptr(), code.len(), 0, 0 /* read as much as possible */, &mut instrs) };
    assert_eq!(size, expected_size);
    assert!(!instrs.is_null());

    let instr = unsafe { &*instrs };
    let (mnemonic, op_str, ops) = expected_first;
    assert_eq!(to_str(&instr.mnemonic), mnemonic);
    assert_eq!(to_str(&instr.op_str), op_str);
    assert!(!instr.detail.is_null());
    let detail = unsafe { (&*instr.detail).x86() };
    assert_eq!(detail.op_count, ops.len() as u8);
    for i in 0..ops.len() {
        assert_eq!(detail.operands[i].typ, ops[i]);
    }

    unsafe {
        cs_close(&mut handle);
    }
}

#[test]
fn test_x86_16() {
    generic(CS_ARCH_X86, CS_MODE_16, X86_CODE16, 15, ("lea", "cx, word ptr [si + 0x32]", &[X86_OP_REG, X86_OP_MEM]));
}

#[test]
fn test_x86_32() {
    generic(CS_ARCH_X86, CS_MODE_32, X86_CODE32, 9, ("lea", "ecx, dword ptr [edx + esi + 8]", &[X86_OP_REG, X86_OP_MEM]));
}

#[test]
fn test_x86_64() {
    generic(CS_ARCH_X86, CS_MODE_64, X86_CODE64, 2, ("push", "rbp", &[X86_OP_REG]));
}
<|endoftext|>


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

//! A pass that simplifies branches when their condition is known.

use rustc::ty::TyCtxt;
use rustc::middle::const_val::ConstVal;
use rustc::mir::transform::{MirPass, MirSource, Pass};
use rustc::mir::*;

use std::fmt;

pub struct SimplifyBranches<'a> { label: &'a str }

impl<'a> SimplifyBranches<'a> {
    pub fn new(label: &'a str) -> Self {
        SimplifyBranches { label: label }
    }
}

impl<'l, 'tcx> MirPass<'tcx> for SimplifyBranches<'l> {
    fn run_pass<'a>(&mut self, _tcx: TyCtxt<'a, 'tcx, 'tcx>, _src: MirSource, mir: &mut Mir<'tcx>) {
        for block in mir.basic_blocks_mut() {
            let terminator = block.terminator_mut();
            terminator.kind = match terminator.kind {
                // TerminatorKind::If { ref targets, cond: Operand::Constant(Constant {
                //     literal: Literal::Value {
                //         value: ConstVal::Bool(cond)
                //     }, ..
                // }) } => {
                //     if cond {
                //         TerminatorKind::Goto { target: targets.0 }
                //     } else {
                //         TerminatorKind::Goto { target: targets.1 }
                //     }
                // }

                TerminatorKind::Assert { target, cond: Operand::Constant(Constant {
                    literal: Literal::Value {
                        value: ConstVal::Bool(cond)
                    }, ..
                }), expected, .. } if cond == expected => {
                    TerminatorKind::Goto { target: target }
                }

                _ => continue
            };
        }
    }
}

impl<'l> Pass for SimplifyBranches<'l> {
    fn disambiguator<'a>(&'a self) -> Option<Box<fmt::Display+'a>> {
        Some(Box::new(self.label))
    }

    // avoid calling `type_name` - it contains `<'static>`
    fn name(&self) -> ::std::borrow::Cow<'static, str> { "SimplifyBranches".into() }
}
<commit_msg>Reimplement simplify_cfg for SwitchInt<commit_after>// Copyright 2016 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

//! A pass that simplifies branches when their condition is known.

use rustc::ty::TyCtxt;
use rustc::middle::const_val::ConstVal;
use rustc::mir::transform::{MirPass, MirSource, Pass};
use rustc::mir::*;

use std::fmt;

pub struct SimplifyBranches<'a> { label: &'a str }

impl<'a> SimplifyBranches<'a> {
    pub fn new(label: &'a str) -> Self {
        SimplifyBranches { label: label }
    }
}

impl<'l, 'tcx> MirPass<'tcx> for SimplifyBranches<'l> {
    fn run_pass<'a>(&mut self, _tcx: TyCtxt<'a, 'tcx, 'tcx>, _src: MirSource, mir: &mut Mir<'tcx>) {
        for block in mir.basic_blocks_mut() {
            let terminator = block.terminator_mut();
            terminator.kind = match terminator.kind {
                TerminatorKind::SwitchInt { discr: Operand::Constant(Constant {
                    literal: Literal::Value { ref value }, ..
                }), ref values, ref targets, .. } => {
                    if let Some(ref constint) = value.to_const_int() {
                        let (otherwise, targets) = targets.split_last().unwrap();
                        let mut ret = TerminatorKind::Goto { target: *otherwise };
                        for (v, t) in values.iter().zip(targets.iter()) {
                            if v == constint {
                                ret = TerminatorKind::Goto { target: *t };
                                break;
                            }
                        }
                        ret
                    } else {
                        continue
                    }
                },
                TerminatorKind::Assert { target, cond: Operand::Constant(Constant {
                    literal: Literal::Value {
                        value: ConstVal::Bool(cond)
                    }, ..
                }), expected, .. } if cond == expected => {
                    TerminatorKind::Goto { target: target }
                },
                _ => continue
            };
        }
    }
}

impl<'l> Pass for SimplifyBranches<'l> {
    fn disambiguator<'a>(&'a self) -> Option<Box<fmt::Display+'a>> {
        Some(Box::new(self.label))
    }

    // avoid calling `type_name` - it contains `<'static>`
    fn name(&self) -> ::std::borrow::Cow<'static, str> { "SimplifyBranches".into() }
}
<|endoftext|>


<commit_before>use casile::*;

use assert_cmd::prelude::*;
use predicates::prelude::*;
use std::process::Command;

static BIN_NAME: &str = "casile";

#[test]
fn outputs_version() -> Result<()> {
    let mut cmd = Command::cargo_bin(BIN_NAME)?;
    cmd.arg("--version");
    cmd.assert().stdout(predicate::str::starts_with("casile v"));
    Ok(())
}

#[test]
fn ouput_is_localized() -> Result<()> {
    let mut cmd = Command::cargo_bin(BIN_NAME)?;
    cmd.arg("-l").arg("tr").arg("setup");
    cmd.assert().stderr(predicate::str::contains("kurun artık"));
    Ok(())
}

#[test]
fn setup_path_exists() -> Result<()> {
    let mut cmd = Command::cargo_bin(BIN_NAME)?;
    cmd.arg("setup").arg("not_a_file");
    cmd.assert()
        .failure()
        .stderr(predicate::str::contains("No such file or directory"));
    Ok(())
}
<commit_msg>test(cli): Update tests for new usage<commit_after>use casile::*;

use assert_cmd::prelude::*;
use predicates::prelude::*;
use std::process::Command;

static BIN_NAME: &str = "casile";

#[test]
fn outputs_version() -> Result<()> {
    let mut cmd = Command::cargo_bin(BIN_NAME)?;
    cmd.arg("--version");
    cmd.assert().stdout(predicate::str::starts_with("casile v"));
    Ok(())
}

#[test]
fn ouput_is_localized() -> Result<()> {
    let mut cmd = Command::cargo_bin(BIN_NAME)?;
    cmd.arg("-l").arg("tr").arg("setup");
    cmd.assert().stderr(predicate::str::contains("kurun artık"));
    Ok(())
}

#[test]
fn setup_path_exists() -> Result<()> {
    let mut cmd = Command::cargo_bin(BIN_NAME)?;
    cmd.arg("-p").arg("not_a_dir").arg("setup");
    cmd.assert()
        .failure()
        .stderr(predicate::str::contains("No such file or directory"));
    Ok(())
}

#[test]
fn fail_on_casile_sources() -> Result<()> {
    let mut cmd = Command::cargo_bin(BIN_NAME)?;
    cmd.arg("-p").arg("./").arg("setup");
    cmd.assert()
        .failure()
        .stderr(predicate::str::contains("Make failed to parse or execute"));
    Ok(())
}
<|endoftext|>


<commit_before>extern crate trustines;

mod memory {
    use trustines::memory::Memory;

    #[test]
    fn read8_basic() {
        let mut m = Memory::new();
        m.mem[0] = 5;
        m.mem[1] = 10;
        assert_eq!(5,m.read8(0).unwrap());
        assert_eq!(10,m.read8(1).unwrap());
    }
    #[test]
    fn write8_basic() {
        let mut m = Memory::new();
        m.write8(0,5);
        assert_eq!(5,m.mem[0]);

        m.write8(1,10);
        assert_eq!(5,m.mem[0]);
        assert_eq!(10,m.mem[1]);
    }

    #[test]
    fn read16_basic() {
        let mut m = Memory::new();
        m.mem[0] = 2;
        m.mem[1] = 1;
        assert_eq!(258,m.read16(0).unwrap());
        assert_eq!(1,m.read16(1).unwrap());
    }
    #[test]
    fn write16_basic() {
        let mut m = Memory::new();
        m.write16(0,258);
        assert_eq!(2,m.mem[0]);
        assert_eq!(1,m.mem[1]);
    }
    #[test]
    fn readwrite8() {
        let mut m = Memory::new();
        m.write8(0,5);
        m.write8(1,10);
        assert_eq!(5,m.read8(0).unwrap());
        assert_eq!(10,m.read8(1).unwrap());
    }
    #[test]
    fn readwrite16() {
        let mut m = Memory::new();
        m.write16(0,258);
        m.write16(2,300);
        assert_eq!(258,m.read16(0).unwrap());
        assert_eq!(300,m.read16(2).unwrap());
    }
}

mod address_mode {
    #[test]
    fn absolute() {
    }
    #[test]
    fn absolute_x() {
    }
    #[test]
    fn absolute_y() {
    }
    #[test]
    fn accumulator() {
    }
    #[test]
    fn immediate() {
    }
    #[test]
    fn implied() {
    }
    #[test]
    fn indirect() {
    }
    #[test]
    fn indexed_indirect() {
    }
    #[test]
    fn indirect_indexed() {
    }
    #[test]
    fn relative() {
    }
    #[test]
    fn zeropage() {
    }
    #[test]
    fn zeropage_x() {
    }
    #[test]
    fn zeropage_y() {
    }
}

<commit_msg>who tests the tests...<commit_after>extern crate trustines;

mod memory {
    use trustines::memory::Memory;

    #[test]
    fn read8_basic() {
        let mut m = Memory::new();
        m.mem[0] = 5;
        m.mem[1] = 10;
        assert_eq!(5,m.read8(0).unwrap());
        assert_eq!(10,m.read8(1).unwrap());
    }
    #[test]
    fn write8_basic() {
        let mut m = Memory::new();
        m.write8(0,5);
        assert_eq!(5,m.mem[0]);

        m.write8(1,10);
        assert_eq!(5,m.mem[0]);
        assert_eq!(10,m.mem[1]);
    }

    #[test]
    fn read16_basic() {
        let mut m = Memory::new();
        m.mem[0] = 2;
        m.mem[1] = 1;
        m.mem[2] = 0;
        assert_eq!(258,m.read16(0).unwrap());
        assert_eq!(1,m.read16(1).unwrap());
    }
    #[test]
    fn write16_basic() {
        let mut m = Memory::new();
        m.write16(0,258);
        assert_eq!(2,m.mem[0]);
        assert_eq!(1,m.mem[1]);
    }
    #[test]
    fn readwrite8() {
        let mut m = Memory::new();
        m.write8(0,5);
        m.write8(1,10);
        assert_eq!(5,m.read8(0).unwrap());
        assert_eq!(10,m.read8(1).unwrap());
    }
    #[test]
    fn readwrite16() {
        let mut m = Memory::new();
        m.write16(0,258);
        m.write16(2,300);
        assert_eq!(258,m.read16(0).unwrap());
        assert_eq!(300,m.read16(2).unwrap());
    }
}

mod address_mode {
    #[test]
    fn absolute() {
    }
    #[test]
    fn absolute_x() {
    }
    #[test]
    fn absolute_y() {
    }
    #[test]
    fn accumulator() {
    }
    #[test]
    fn immediate() {
    }
    #[test]
    fn implied() {
    }
    #[test]
    fn indirect() {
    }
    #[test]
    fn indexed_indirect() {
    }
    #[test]
    fn indirect_indexed() {
    }
    #[test]
    fn relative() {
    }
    #[test]
    fn zeropage() {
    }
    #[test]
    fn zeropage_x() {
    }
    #[test]
    fn zeropage_y() {
    }
}

<|endoftext|>


<commit_before>extern crate test_server;
extern crate modbus;

#[cfg(feature="modbus-server-tests")]
mod modbus_server_tests {
    use test_server::start_dummy_server;
    use modbus::tcp::Ctx;
    use modbus::{Client, BitValue};

    /// /////////////////////
    /// simple READ tests
    #[test]
    fn test_read_coils() {
        let (_s, port) = start_dummy_server();
        let mut ctx = Ctx::new_with_port("127.0.0.1", port).unwrap();
        assert_eq!(ctx.read_coils(0, 5).unwrap().len(), 5);
        assert!(ctx.read_coils(0, 5).unwrap().iter().all(|c| *c == BitValue::Off));
    }

    #[test]
    fn test_read_discrete_inputs() {
        let (_s, port) = start_dummy_server();
        let mut ctx = Ctx::new_with_port("127.0.0.1", port).unwrap();
        assert_eq!(ctx.read_discrete_inputs(0, 5).unwrap().len(), 5);
        assert!(ctx.read_discrete_inputs(0, 5).unwrap().iter().all(|c| *c == BitValue::Off));
    }

    #[test]
    fn test_read_holding_registers() {
        let (_s, port) = start_dummy_server();
        let mut ctx = Ctx::new_with_port("127.0.0.1", port).unwrap();
        assert_eq!(ctx.read_holding_registers(0, 5).unwrap().len(), 5);
        assert!(ctx.read_holding_registers(0, 5).unwrap().iter().all(|c| *c == 0));
    }

    #[test]
    fn test_read_input_registers() {
        let (_s, port) = start_dummy_server();
        let mut ctx = Ctx::new_with_port("127.0.0.1", port).unwrap();
        assert_eq!(ctx.read_input_registers(0, 5).unwrap().len(), 5);
        assert!(ctx.read_input_registers(0, 5).unwrap().iter().all(|c| *c == 0));
    }

    /// /////////////////////
    /// simple WRITE tests
    #[test]
    fn test_write_single_coil() {
        let (_s, port) = start_dummy_server();
        let mut ctx = Ctx::new_with_port("127.0.0.1", port).unwrap();
        assert!(ctx.write_single_coil(0, BitValue::On).is_ok());
    }

    #[test]
    fn test_write_single_register() {
        let (_s, port) = start_dummy_server();
        let mut ctx = Ctx::new_with_port("127.0.0.1", port).unwrap();
        assert!(ctx.write_single_register(0, 1).is_ok());
    }

    #[test]
    fn test_write_multiple_coils() {
        let (_s, port) = start_dummy_server();
        let mut ctx = Ctx::new_with_port("127.0.0.1", port).unwrap();
        assert!(ctx.write_multiple_coils(0, &[BitValue::On, BitValue::Off]).is_ok());
        // assert!(write_multiple_coils(&mut ctx, 0, &[]).is_err());
    }

    #[test]
    fn test_write_multiple_registers() {
        let (_s, port) = start_dummy_server();
        let mut ctx = Ctx::new_with_port("127.0.0.1", port).unwrap();
        assert!(ctx.write_multiple_registers(0, &[0, 1, 2, 3]).is_ok());
        // assert!(write_multiple_registers(&mut ctx, 0, &[]).is_err());
    }

    /// /////////////////////
    /// coil WRITE-READ tests
    #[test]
    fn test_write_read_single_coils() {
        let (_s, port) = start_dummy_server();
        let mut ctx = Ctx::new_with_port("127.0.0.1", port).unwrap();

        assert!(ctx.write_single_coil(1, BitValue::On).is_ok());
        assert!(ctx.write_single_coil(3, BitValue::On).is_ok());
        assert_eq!(ctx.read_coils(0, 5).unwrap(),
                   vec![BitValue::Off, BitValue::On, BitValue::Off, BitValue::On, BitValue::Off]);
        assert_eq!(ctx.read_coils(1, 5).unwrap(),
                   vec![BitValue::On, BitValue::Off, BitValue::On, BitValue::Off, BitValue::Off]);
        assert!(ctx.write_single_coil(10, BitValue::On).is_ok());
        assert!(ctx.write_single_coil(11, BitValue::On).is_ok());
        assert_eq!(ctx.read_coils(9, 4).unwrap(),
                   vec![BitValue::Off, BitValue::On, BitValue::On, BitValue::Off]);
        assert!(ctx.write_single_coil(10, BitValue::Off).is_ok());
        assert!(ctx.write_single_coil(11, BitValue::Off).is_ok());
        assert_eq!(ctx.read_coils(9, 4).unwrap(),
                   vec![BitValue::Off, BitValue::Off, BitValue::Off, BitValue::Off]);
    }

    #[test]
    fn test_write_read_single_register() {
        let (_s, port) = start_dummy_server();
        let mut ctx = Ctx::new_with_port("127.0.0.1", port).unwrap();
        assert!(ctx.write_single_register(0, 23).is_ok());
        assert_eq!(ctx.read_holding_registers(0, 1).unwrap(), vec![23]);
        assert!(ctx.write_single_register(0, 0).is_ok());
        assert_eq!(ctx.read_holding_registers(0, 1).unwrap(), vec![0]);
        assert_eq!(ctx.read_input_registers(0, 1).unwrap(), vec![0]);
        assert!(ctx.write_single_register(0, 23).is_ok());
        assert!(ctx.write_single_register(1, 24).is_ok());
        assert_eq!(ctx.read_holding_registers(0, 2).unwrap(), vec![23, 24]);
    }

    #[test]
    fn test_write_read_multiple_coils() {
        let (_s, port) = start_dummy_server();
        let mut ctx = Ctx::new_with_port("127.0.0.1", port).unwrap();
        assert!(ctx.write_multiple_coils(0, &[BitValue::Off, BitValue::On]).is_ok());
        assert_eq!(ctx.read_coils(0, 3).unwrap(),
                   &[BitValue::Off, BitValue::On, BitValue::Off]);
        assert!(ctx.write_multiple_coils(0, &[BitValue::On; 9]).is_ok());
        assert_eq!(ctx.read_coils(0, 9).unwrap(), &[BitValue::On; 9]);
    }

    #[test]
    fn test_write_read_multiple_registers() {
        let (_s, port) = start_dummy_server();
        let mut ctx = Ctx::new_with_port("127.0.0.1", port).unwrap();
        // assert!(write_multiple_registers(&mut ctx, 0, &[]).is_err());
        assert!(ctx.write_multiple_registers(0, &[23]).is_ok());
        assert_eq!(ctx.read_holding_registers(0, 1).unwrap(), &[23]);
        assert!(ctx.write_multiple_registers(0, &[1, 2, 3]).is_ok());
        assert_eq!(ctx.read_holding_registers(0, 1).unwrap(), &[1]);
        assert_eq!(ctx.read_holding_registers(1, 1).unwrap(), &[2]);
        assert_eq!(ctx.read_holding_registers(2, 1).unwrap(), &[3]);
        assert_eq!(ctx.read_holding_registers(0, 3).unwrap(), &[1, 2, 3]);
    }

    #[test]
    fn test_write_too_big() {
        let (_s, port) = start_dummy_server();
        let mut ctx = Ctx::new_with_port("127.0.0.1", port).unwrap();
        // (MODBUS_MAX_WRITE_COUNT - HEADER) / u16-bytes
        assert!(write_multiple_registers(&mut ctx, 0, &[0xdead; (0x79 - 12) / 2]).is_ok());
        assert!(write_multiple_registers(&mut ctx, 0, &[0xdead; (0x79 - 11) / 2]).is_err());
    }
}
<commit_msg>Fix unit tests.<commit_after>extern crate test_server;
extern crate modbus;

#[cfg(feature="modbus-server-tests")]
mod modbus_server_tests {
    use test_server::start_dummy_server;
    use modbus::tcp::Ctx;
    use modbus::{Client, BitValue};

    /// /////////////////////
    /// simple READ tests
    #[test]
    fn test_read_coils() {
        let (_s, port) = start_dummy_server();
        let mut ctx = Ctx::new_with_port("127.0.0.1", port).unwrap();
        assert_eq!(ctx.read_coils(0, 5).unwrap().len(), 5);
        assert!(ctx.read_coils(0, 5).unwrap().iter().all(|c| *c == BitValue::Off));
    }

    #[test]
    fn test_read_discrete_inputs() {
        let (_s, port) = start_dummy_server();
        let mut ctx = Ctx::new_with_port("127.0.0.1", port).unwrap();
        assert_eq!(ctx.read_discrete_inputs(0, 5).unwrap().len(), 5);
        assert!(ctx.read_discrete_inputs(0, 5).unwrap().iter().all(|c| *c == BitValue::Off));
    }

    #[test]
    fn test_read_holding_registers() {
        let (_s, port) = start_dummy_server();
        let mut ctx = Ctx::new_with_port("127.0.0.1", port).unwrap();
        assert_eq!(ctx.read_holding_registers(0, 5).unwrap().len(), 5);
        assert!(ctx.read_holding_registers(0, 5).unwrap().iter().all(|c| *c == 0));
    }

    #[test]
    fn test_read_input_registers() {
        let (_s, port) = start_dummy_server();
        let mut ctx = Ctx::new_with_port("127.0.0.1", port).unwrap();
        assert_eq!(ctx.read_input_registers(0, 5).unwrap().len(), 5);
        assert!(ctx.read_input_registers(0, 5).unwrap().iter().all(|c| *c == 0));
    }

    /// /////////////////////
    /// simple WRITE tests
    #[test]
    fn test_write_single_coil() {
        let (_s, port) = start_dummy_server();
        let mut ctx = Ctx::new_with_port("127.0.0.1", port).unwrap();
        assert!(ctx.write_single_coil(0, BitValue::On).is_ok());
    }

    #[test]
    fn test_write_single_register() {
        let (_s, port) = start_dummy_server();
        let mut ctx = Ctx::new_with_port("127.0.0.1", port).unwrap();
        assert!(ctx.write_single_register(0, 1).is_ok());
    }

    #[test]
    fn test_write_multiple_coils() {
        let (_s, port) = start_dummy_server();
        let mut ctx = Ctx::new_with_port("127.0.0.1", port).unwrap();
        assert!(ctx.write_multiple_coils(0, &[BitValue::On, BitValue::Off]).is_ok());
        // assert!(write_multiple_coils(&mut ctx, 0, &[]).is_err());
    }

    #[test]
    fn test_write_multiple_registers() {
        let (_s, port) = start_dummy_server();
        let mut ctx = Ctx::new_with_port("127.0.0.1", port).unwrap();
        assert!(ctx.write_multiple_registers(0, &[0, 1, 2, 3]).is_ok());
        // assert!(write_multiple_registers(&mut ctx, 0, &[]).is_err());
    }

    /// /////////////////////
    /// coil WRITE-READ tests
    #[test]
    fn test_write_read_single_coils() {
        let (_s, port) = start_dummy_server();
        let mut ctx = Ctx::new_with_port("127.0.0.1", port).unwrap();

        assert!(ctx.write_single_coil(1, BitValue::On).is_ok());
        assert!(ctx.write_single_coil(3, BitValue::On).is_ok());
        assert_eq!(ctx.read_coils(0, 5).unwrap(),
                   vec![BitValue::Off, BitValue::On, BitValue::Off, BitValue::On, BitValue::Off]);
        assert_eq!(ctx.read_coils(1, 5).unwrap(),
                   vec![BitValue::On, BitValue::Off, BitValue::On, BitValue::Off, BitValue::Off]);
        assert!(ctx.write_single_coil(10, BitValue::On).is_ok());
        assert!(ctx.write_single_coil(11, BitValue::On).is_ok());
        assert_eq!(ctx.read_coils(9, 4).unwrap(),
                   vec![BitValue::Off, BitValue::On, BitValue::On, BitValue::Off]);
        assert!(ctx.write_single_coil(10, BitValue::Off).is_ok());
        assert!(ctx.write_single_coil(11, BitValue::Off).is_ok());
        assert_eq!(ctx.read_coils(9, 4).unwrap(),
                   vec![BitValue::Off, BitValue::Off, BitValue::Off, BitValue::Off]);
    }

    #[test]
    fn test_write_read_single_register() {
        let (_s, port) = start_dummy_server();
        let mut ctx = Ctx::new_with_port("127.0.0.1", port).unwrap();
        assert!(ctx.write_single_register(0, 23).is_ok());
        assert_eq!(ctx.read_holding_registers(0, 1).unwrap(), vec![23]);
        assert!(ctx.write_single_register(0, 0).is_ok());
        assert_eq!(ctx.read_holding_registers(0, 1).unwrap(), vec![0]);
        assert_eq!(ctx.read_input_registers(0, 1).unwrap(), vec![0]);
        assert!(ctx.write_single_register(0, 23).is_ok());
        assert!(ctx.write_single_register(1, 24).is_ok());
        assert_eq!(ctx.read_holding_registers(0, 2).unwrap(), vec![23, 24]);
    }

    #[test]
    fn test_write_read_multiple_coils() {
        let (_s, port) = start_dummy_server();
        let mut ctx = Ctx::new_with_port("127.0.0.1", port).unwrap();
        assert!(ctx.write_multiple_coils(0, &[BitValue::Off, BitValue::On]).is_ok());
        assert_eq!(ctx.read_coils(0, 3).unwrap(),
                   &[BitValue::Off, BitValue::On, BitValue::Off]);
        assert!(ctx.write_multiple_coils(0, &[BitValue::On; 9]).is_ok());
        assert_eq!(ctx.read_coils(0, 9).unwrap(), &[BitValue::On; 9]);
    }

    #[test]
    fn test_write_read_multiple_registers() {
        let (_s, port) = start_dummy_server();
        let mut ctx = Ctx::new_with_port("127.0.0.1", port).unwrap();
        // assert!(write_multiple_registers(&mut ctx, 0, &[]).is_err());
        assert!(ctx.write_multiple_registers(0, &[23]).is_ok());
        assert_eq!(ctx.read_holding_registers(0, 1).unwrap(), &[23]);
        assert!(ctx.write_multiple_registers(0, &[1, 2, 3]).is_ok());
        assert_eq!(ctx.read_holding_registers(0, 1).unwrap(), &[1]);
        assert_eq!(ctx.read_holding_registers(1, 1).unwrap(), &[2]);
        assert_eq!(ctx.read_holding_registers(2, 1).unwrap(), &[3]);
        assert_eq!(ctx.read_holding_registers(0, 3).unwrap(), &[1, 2, 3]);
    }

    #[test]
    fn test_write_too_big() {
        let (_s, port) = start_dummy_server();
        let mut ctx = Ctx::new_with_port("127.0.0.1", port).unwrap();
        // (MODBUS_MAX_WRITE_COUNT - HEADER) / u16-bytes
        assert!(ctx.write_multiple_registers(0, &[0xdead; (0x79 - 12) / 2]).is_ok());
        assert!(ctx.write_multiple_registers(0, &[0xdead; (0x79 - 11) / 2]).is_err());
    }
}
<|endoftext|>


<commit_before>extern crate codespawn;

#[test]
fn check_from_xml() {
    let raw_code = codespawn::from_xml("examples/sample.xml").unwrap();

    for c in raw_code.configs.iter() {
        println!("{}", c.1);
    }

    println!("{}", raw_code);
    println!("{}", raw_code.to_cpp());
    println!("{}", raw_code.tp_rust());

    // save to .rst file instead of .rs so that subsequent test don't get confused
    raw_code.to_rust().to_file("tests/sample.rst");
    raw_code.to_cpp().to_file("tests/sample.cpp");
}

#[test]
fn check_from_json() {
    let raw_code = codespawn::from_json("examples/sample.json").unwrap();

    for c in raw_code.configs.iter() {
        println!("{}", c.1);
    }

    println!("{}", raw_code);
    println!("{}", raw_code.to_cpp());
    println!("{}", raw_code.tp_rust());

    // save to .rst file instead of .rs so that subsequent test don't get confused
    raw_code.to_rust().to_file("tests/sample.rst");
    raw_code.to_cpp().to_file("tests/sample.cpp");
}

#[test]
#[should_panic]
fn check_from_xml_fail() {
    let _ = codespawn::from_xml("foobar").unwrap();
}

#[test]
#[should_panic]
fn check_from_json_fail() {
    let _ = codespawn::from_json("foobar").unwrap();
}

#[test]
#[should_panic]
fn check_from_xml_fail_cfg() {
    let _ = codespawn::from_xml_str("<config file=\"foobar\"/><var name=\"x\" type=\"int\"/>").unwrap();
}

#[test]
#[should_panic]
fn check_from_json_fail_cfg() {
    let _ = codespawn::from_json_str("{\"config\": { \"file\": \"foobar\" }, \"var\": {\"name\": \"x\", \"type\":\"int\" }}").unwrap();
}

#[test]
#[should_panic]
fn check_from_xml_fail_malformed() {
    let _ = codespawn::from_xml_str("<config file=\"foobar\"/>var name=\"x\" type=\"int\"/>").unwrap();
}

#[test]
#[should_panic]
fn check_from_xml_fail_malformed_cfg() {
    let _ = codespawn::from_xml_str("<config file=\"tests/malformed_cfg.xml\"/>var name=\"x\" type=\"int\"/>").unwrap();
}

#[test]
#[should_panic]
fn check_from_json_fail_malformed() {
    let _ = codespawn::from_json_str("{\"config\": { \"file\": \"examples/rust.json\" } \"var\": {\"name\": \"x\", \"type\":\"int\" }}").unwrap();
}
<commit_msg>fixed typo<commit_after>extern crate codespawn;

#[test]
fn check_from_xml() {
    let raw_code = codespawn::from_xml("examples/sample.xml").unwrap();

    for c in raw_code.configs.iter() {
        println!("{}", c.1);
    }

    println!("{}", raw_code);
    println!("{}", raw_code.to_cpp());
    println!("{}", raw_code.to_rust());

    // save to .rst file instead of .rs so that subsequent test don't get confused
    let _ = raw_code.to_rust().to_file("tests/sample.rst");
    let _ = raw_code.to_cpp().to_file("tests/sample.cpp");
}

#[test]
fn check_from_json() {
    let raw_code = codespawn::from_json("examples/sample.json").unwrap();

    for c in raw_code.configs.iter() {
        println!("{}", c.1);
    }

    println!("{}", raw_code);
    println!("{}", raw_code.to_cpp());
    println!("{}", raw_code.to_rust());

    // save to .rst file instead of .rs so that subsequent test don't get confused
    let _ = raw_code.to_rust().to_file("tests/sample.rst");
    let _ = raw_code.to_cpp().to_file("tests/sample.cpp");
}

#[test]
#[should_panic]
fn check_from_xml_fail() {
    let _ = codespawn::from_xml("foobar").unwrap();
}

#[test]
#[should_panic]
fn check_from_json_fail() {
    let _ = codespawn::from_json("foobar").unwrap();
}

#[test]
#[should_panic]
fn check_from_xml_fail_cfg() {
    let _ = codespawn::from_xml_str("<config file=\"foobar\"/><var name=\"x\" type=\"int\"/>").unwrap();
}

#[test]
#[should_panic]
fn check_from_json_fail_cfg() {
    let _ = codespawn::from_json_str("{\"config\": { \"file\": \"foobar\" }, \"var\": {\"name\": \"x\", \"type\":\"int\" }}").unwrap();
}

#[test]
#[should_panic]
fn check_from_xml_fail_malformed() {
    let _ = codespawn::from_xml_str("<config file=\"foobar\"/>var name=\"x\" type=\"int\"/>").unwrap();
}

#[test]
#[should_panic]
fn check_from_xml_fail_malformed_cfg() {
    let _ = codespawn::from_xml_str("<config file=\"tests/malformed_cfg.xml\"/>var name=\"x\" type=\"int\"/>").unwrap();
}

#[test]
#[should_panic]
fn check_from_json_fail_malformed() {
    let _ = codespawn::from_json_str("{\"config\": { \"file\": \"examples/rust.json\" } \"var\": {\"name\": \"x\", \"type\":\"int\" }}").unwrap();
}
<|endoftext|>