<commit_before>use env_logger;
use std::env;
use std::sync::mpsc::{channel, Receiver, TryRecvError};
use std::sync::Mutex;
use std::thread;
use std::time::Duration;

use common::communicate::{ClientToServer, ServerToClient};
use common::serialize;
use common::serialize::Copyable;
use common::socket::{SendSocket, ReceiveSocket};

use client::Client;
use update_thread::update_thread;
use view_thread::view_thread;

// TODO: This is duplicated in the server. Fix that.
#[inline(always)]
fn try_recv<T>(recv: &Receiver<T>) -> Option<T>
  where T: Send,
{
  match recv.try_recv() {
    Ok(msg) => Some(msg),
    Err(TryRecvError::Empty) => None,
    e => Some(e.unwrap()),
  }
}

#[main]
fn main() {
  env_logger::init().unwrap();

  let mut args = env::args();
  args.next().unwrap();
  let listen_url = args.next().unwrap_or(String::from("ipc:///tmp/client.ipc"));
  let server_url = args.next().unwrap_or(String::from("ipc:///tmp/server.ipc"));
  assert!(args.next().is_none());

  info!("Sending to {}.", server_url);
  info!("Listening on {}.", listen_url);

  let (server_send_thread_send, server_send_thread_recv) = channel();
  let (server_recv_thread_send, mut server_recv_thread_recv) = channel();
  let (terrain_blocks_send, mut terrain_blocks_recv) = channel();
  let (view_thread_send, mut view_thread_recv) = channel();

  let server_recv_thread_send = &server_recv_thread_send;
  let server_recv_thread_recv = &mut server_recv_thread_recv;
  let terrain_blocks_send = &terrain_blocks_send;
  let terrain_blocks_recv = &mut terrain_blocks_recv;
  let view_thread_send = &view_thread_send;
  let view_thread_recv = &mut view_thread_recv;

  let quit = Mutex::new(false);
  let quit = &quit;

  let _server_recv_thread = {
    let listen_url = listen_url.clone();
    let server_recv_thread_send = server_recv_thread_send.clone();
    thread::spawn(move || {
      let mut listen_socket =
        ReceiveSocket::new(listen_url.clone().as_ref(), Some(Duration::from_secs(30)));
      loop {
        let msg = listen_socket.read();
        server_recv_thread_send.send(msg).unwrap();
      }
    })
  };

  let _server_send_thread = {
    thread::spawn(move || {
      let mut talk_socket =
        SendSocket::new(server_url.clone().as_ref(), Some(Duration::from_secs(30)));
      loop {
        let msg: Option<ClientToServer> = server_send_thread_recv.recv().unwrap();
        let msg = serialize::encode(&msg.unwrap()).unwrap();
        talk_socket.write(msg.as_ref());
      }
    })
  };

  // TODO: Consider using RPCs to solidify the request-response patterns.
  server_send_thread_send.send(Some(ClientToServer::Init(listen_url.clone()))).unwrap();
  let client;
  'init_loop:loop {
    match server_recv_thread_recv.recv().map(|s| serialize::decode(s.as_ref()).unwrap()) {
      Ok(ServerToClient::LeaseId(client_id)) => {
        server_send_thread_send.send(Some(ClientToServer::AddPlayer(client_id))).unwrap();
        let client_id = client_id.0;
        loop {
          match server_recv_thread_recv.recv().map(|s| serialize::decode(s.as_ref()).unwrap()) {
            Ok(ServerToClient::PlayerAdded(Copyable(player_id), Copyable(position))) => {
              client = Client::new(client_id, player_id, position);
              break 'init_loop;
            },
            Ok(msg) => {
              // Ignore other messages in the meantime.
              info!("Ignoring: {:?}", msg);
            },
            Err(e) => {
              panic!("Received error: {:?}", e);
            },
          }
        }
      },
      Ok(msg) => {
        // Ignore other messages in the meantime.
        info!("Ignoring: {:?}", msg);
      },
      Err(e) => {
        panic!("Received error: {:?}", e);
      },
    }
  }
  let client = &client;

  {
    let _update_thread = {
      let client = &client;
      let view_thread_send = view_thread_send.clone();
      let server_send_thread_send = server_send_thread_send.clone();
      let terrain_blocks_send = terrain_blocks_send.clone();
      thread::scoped(move || {
        update_thread(
          quit,
          client,
          &mut || {
            try_recv(server_recv_thread_recv)
              .map(|msg| serialize::decode(msg.as_ref()).unwrap())
          },
          &mut || { try_recv(terrain_blocks_recv) },
          &mut |up| { view_thread_send.send(up).unwrap() },
	        &mut |up| { server_send_thread_send.send(Some(up)).unwrap() },
          &mut |block| { terrain_blocks_send.send(block).unwrap() },
        )
      })
    };

    let view_thread = {
      let server_send_thread_send = server_send_thread_send.clone();
      thread::scoped(move || {
        view_thread(
          client.player_id,
          &mut || {
            match view_thread_recv.try_recv() {
              Ok(msg) => Some(msg),
              Err(TryRecvError::Empty) => None,
              Err(TryRecvError::Disconnected) =>
                panic!("view_thread_send should not be closed."),
            }
          },
          &mut |server_update| {
            server_send_thread_send.send(Some(server_update)).unwrap();
          },
        )
      })
    };

    view_thread.join();

    // View thread returned, so we got a quit event.
    *quit.lock().unwrap() = true;
  }
}

#[test]
fn keep_bin_code_live() {
  let i = 0;
  if i == 1 {
    main();
  }
}
<commit_msg>Move SDL to main thread for platform-dependent reasons.<commit_after>use env_logger;
use std::env;
use std::sync::mpsc::{channel, Receiver, TryRecvError};
use std::sync::Mutex;
use std::thread;
use std::time::Duration;

use common::communicate::{ClientToServer, ServerToClient};
use common::serialize;
use common::serialize::Copyable;
use common::socket::{SendSocket, ReceiveSocket};

use client::Client;
use update_thread::update_thread;
use view_thread::view_thread;

// TODO: This is duplicated in the server. Fix that.
#[inline(always)]
fn try_recv<T>(recv: &Receiver<T>) -> Option<T>
  where T: Send,
{
  match recv.try_recv() {
    Ok(msg) => Some(msg),
    Err(TryRecvError::Empty) => None,
    e => Some(e.unwrap()),
  }
}

#[main]
fn main() {
  env_logger::init().unwrap();

  let mut args = env::args();
  args.next().unwrap();
  let listen_url = args.next().unwrap_or(String::from("ipc:///tmp/client.ipc"));
  let server_url = args.next().unwrap_or(String::from("ipc:///tmp/server.ipc"));
  assert!(args.next().is_none());

  info!("Sending to {}.", server_url);
  info!("Listening on {}.", listen_url);

  let (server_send_thread_send, server_send_thread_recv) = channel();
  let (server_recv_thread_send, mut server_recv_thread_recv) = channel();
  let (terrain_blocks_send, mut terrain_blocks_recv) = channel();
  let (view_thread_send, mut view_thread_recv) = channel();

  let server_recv_thread_send = &server_recv_thread_send;
  let server_recv_thread_recv = &mut server_recv_thread_recv;
  let terrain_blocks_send = &terrain_blocks_send;
  let terrain_blocks_recv = &mut terrain_blocks_recv;
  let view_thread_send = &view_thread_send;
  let view_thread_recv = &mut view_thread_recv;

  let quit = Mutex::new(false);
  let quit = &quit;

  let _server_recv_thread = {
    let listen_url = listen_url.clone();
    let server_recv_thread_send = server_recv_thread_send.clone();
    thread::spawn(move || {
      let mut listen_socket =
        ReceiveSocket::new(listen_url.clone().as_ref(), Some(Duration::from_secs(30)));
      loop {
        let msg = listen_socket.read();
        server_recv_thread_send.send(msg).unwrap();
      }
    })
  };

  let _server_send_thread = {
    thread::spawn(move || {
      let mut talk_socket =
        SendSocket::new(server_url.clone().as_ref(), Some(Duration::from_secs(30)));
      loop {
        let msg: Option<ClientToServer> = server_send_thread_recv.recv().unwrap();
        let msg = serialize::encode(&msg.unwrap()).unwrap();
        talk_socket.write(msg.as_ref());
      }
    })
  };

  // TODO: Consider using RPCs to solidify the request-response patterns.
  server_send_thread_send.send(Some(ClientToServer::Init(listen_url.clone()))).unwrap();
  let client;
  'init_loop:loop {
    match server_recv_thread_recv.recv().map(|s| serialize::decode(s.as_ref()).unwrap()) {
      Ok(ServerToClient::LeaseId(client_id)) => {
        server_send_thread_send.send(Some(ClientToServer::AddPlayer(client_id))).unwrap();
        let client_id = client_id.0;
        loop {
          match server_recv_thread_recv.recv().map(|s| serialize::decode(s.as_ref()).unwrap()) {
            Ok(ServerToClient::PlayerAdded(Copyable(player_id), Copyable(position))) => {
              client = Client::new(client_id, player_id, position);
              break 'init_loop;
            },
            Ok(msg) => {
              // Ignore other messages in the meantime.
              info!("Ignoring: {:?}", msg);
            },
            Err(e) => {
              panic!("Received error: {:?}", e);
            },
          }
        }
      },
      Ok(msg) => {
        // Ignore other messages in the meantime.
        info!("Ignoring: {:?}", msg);
      },
      Err(e) => {
        panic!("Received error: {:?}", e);
      },
    }
  }
  let client = &client;

  {
    let _update_thread = {
      let client = &client;
      let view_thread_send = view_thread_send.clone();
      let server_send_thread_send = server_send_thread_send.clone();
      let terrain_blocks_send = terrain_blocks_send.clone();
      thread::scoped(move || {
        update_thread(
          quit,
          client,
          &mut || {
            try_recv(server_recv_thread_recv)
              .map(|msg| serialize::decode(msg.as_ref()).unwrap())
          },
          &mut || { try_recv(terrain_blocks_recv) },
          &mut |up| { view_thread_send.send(up).unwrap() },
	        &mut |up| { server_send_thread_send.send(Some(up)).unwrap() },
          &mut |block| { terrain_blocks_send.send(block).unwrap() },
        )
      })
    };

    {
      let server_send_thread_send = server_send_thread_send.clone();
      view_thread(
        client.player_id,
        &mut || {
          match view_thread_recv.try_recv() {
            Ok(msg) => Some(msg),
            Err(TryRecvError::Empty) => None,
            Err(TryRecvError::Disconnected) =>
              panic!("view_thread_send should not be closed."),
          }
        },
        &mut |server_update| {
          server_send_thread_send.send(Some(server_update)).unwrap();
        },
      )
    }

    // View thread returned, so we got a quit event.
    *quit.lock().unwrap() = true;
  }
}

#[test]
fn keep_bin_code_live() {
  let i = 0;
  if i == 1 {
    main();
  }
}
<|endoftext|>


<commit_before>extern crate rfc6238;

extern crate chrono;
use chrono::*;

extern crate rustc_serialize;
extern crate docopt;
use docopt::Docopt;

use std::process;
use std::str::FromStr;

const VERSION: &'static str = "0.1";
const USAGE: &'static str = "
totp-client

Usage:
  totp-client <key> [--code-length=<cl>] [--time=<timestamp>]
  totp-client --version
  totp-client (-h | --help)

Options:
  -h --help             Show this screen.
  --version             Show version.
  --code-length=<l>     Specifies the desired length of the output code, defaults to 6
  --time=<timestamp>    Specifies the unix timestamp to be used, defaults to current time
";

#[derive(Debug, RustcDecodable)]
struct Args {
    arg_key: String,
    flag_version: bool,
    flag_help: bool,
    flag_code_length: Option<String>,
    flag_time: Option<u64>
}

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

    if args.flag_help {
        println!("{}", USAGE);
        process::exit(0);
    }

    let raw_code_length = args.flag_code_length.unwrap_or(String::from_str("6").unwrap());
    let code_length: u8 = raw_code_length.parse().unwrap();
    let timestamp = args.flag_time.unwrap_or(UTC::now().timestamp() as u64);

    println!("{}", args.arg_key);
    println!("{}", code_length);
    println!("{}", timestamp);
}
<commit_msg>Implements a command line interface for TOTP<commit_after>extern crate rfc6238;

extern crate chrono;
use chrono::*;

extern crate rustc_serialize;
extern crate docopt;
use docopt::Docopt;

use std::process;
use std::str::FromStr;

const VERSION: &'static str = "0.1";
const USAGE: &'static str = "
totp-client

Usage:
  totp-client <key> [--code-length=<cl>] [--time=<timestamp>]
  totp-client --version
  totp-client (-h | --help)

Options:
  -h --help             Show this screen.
  --version             Show version.
  --code-length=<l>     Specifies the desired length of the output code, defaults to 6
  --time=<timestamp>    Specifies the unix timestamp to be used, defaults to current time
";

#[derive(Debug, RustcDecodable)]
struct Args {
    arg_key: String,
    flag_version: bool,
    flag_help: bool,
    flag_code_length: Option<String>,
    flag_time: Option<u64>
}

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

    if args.flag_help {
        println!("{}", USAGE);
        process::exit(0);
    }

    let raw_code_length = args.flag_code_length.unwrap_or(String::from_str("6").unwrap());
    let code_length: u8 = raw_code_length.parse().unwrap();
    let timestamp = args.flag_time.unwrap_or(UTC::now().timestamp() as u64);

    let code = rfc6238::totp(code_length, args.arg_key.as_bytes(), timestamp);
    println!("{}", code);
}
<|endoftext|>


<commit_before>/* CONFIGURATION */

// add other android system headers to this list as necessary
static INCLUDE_SYS_H: [&str; 1] = ["jni.h"];

static RUST_SRC_DIR: &str = "src";
static ANDROID_BASE_DIR: &str = "app";

// =========================================================
// This script is portable; copy and paste it into your own
// build files at will.

extern crate bindgen;
extern crate rust_swig;
extern crate syntex;
extern crate walkdir;

use std::process::{Command, Stdio};
use std::{env, fmt};
use std::io::prelude::*;
use std::fs::File;
use std::path::{Path, PathBuf};

use bindgen::RustTarget;
use rust_swig::{JavaConfig, LanguageConfig};
use walkdir::WalkDir;

fn main() {
    let target = env::var("TARGET").unwrap();
    assert!(["aarch64-linux-android", "arm-linux-androideabi",
             "i686-linux-android", "x86_64-linux-android"].contains(&target.as_str()));

    let include_dirs =
        get_gcc_system_include_dirs().expect("Can't get gcc's system include dirs");

    let include_headers: Vec<_> = INCLUDE_SYS_H.into_iter()
        .map(|h| search_file_in_directory(&include_dirs, h)
             .expect(format!("Could not find header {}", h).as_ref()))
        .collect();

    let src_dir = Path::new(RUST_SRC_DIR);
    let out_dir = env::var("OUT_DIR").unwrap();

    gen_binding(
        &target,
        &include_dirs,
        &include_headers,
        &Path::new(&out_dir).join("android_c_headers.rs"),
    ).unwrap();

    // Find files ending in .rs.in and expand them with SWIG
    for _entry in WalkDir::new(RUST_SRC_DIR) {
        let entry = _entry.expect("Error walking sources.");
        if entry.path().is_dir() || !entry.path().to_string_lossy().ends_with(".rs.in") {
            continue;
        }

        println!("Found SWIG specification: {}", entry.path().display());
        let swigf = entry.path().strip_prefix("src").unwrap();

        rust_swig_expand(
            &src_dir,
            &swigf,
            Path::new(&out_dir),
        ).unwrap();

        write_include_file(&src_dir, swigf).expect("Failed to write include file.");
    }

    // Hook up cargo reruns
    println!("cargo:rerun-if-changed={}", RUST_SRC_DIR);
    for dir in &include_dirs {println!("cargo:rerun-if-changed={}", dir.display());}
    //if the generated files were deleted (e.g by gradle -q clean), regenerate them
    println!("cargo:rerun-if-changed={}", out_dir);
}

fn get_gcc_system_include_dirs() -> Result<Vec<PathBuf>, String> {
    let gcc_cmd = env::var("RUSTC_LINKER").expect("RUSTC_LINKER not set --
Update your version of Cargo or merge PR#5394 from github.com/rust-lang/cargo.");
    println!("Using Android gcc from '{}'", gcc_cmd);

    let gcc_process = Command::new(&gcc_cmd)
        .args(&["-v", "-x", "c", "-E", "-" /*, &("--sysroot=".to_owned() + &sysroot)*/])
        .stderr(Stdio::piped())
        .stdin(Stdio::piped())
        .stdout(Stdio::inherit())
        .spawn()
        .map_err(|err| err.to_string())?;

    gcc_process
        .stdin
        .ok_or(format!("Cannot get stdin of {}", gcc_cmd).as_str())?
        .write_all("\n".as_bytes())
        .map_err(|err| err.to_string())?;

    let mut gcc_output = String::new();
    gcc_process
        .stderr
        .ok_or(format!("Cannot get stderr of {}", gcc_cmd).as_str())?
        .read_to_string(&mut gcc_output)
        .map_err(|err| err.to_string())?;

    const BEGIN_PAT: &'static str = "\n#include <...> search starts here:\n";
    const END_PAT: &'static str = "\nEnd of search list.\n";
    let start_includes = gcc_output
        .find(BEGIN_PAT)
        .ok_or(format!("No '{}' in output from {}", BEGIN_PAT, gcc_cmd).as_str())?
        + BEGIN_PAT.len();
    let end_includes = (&gcc_output[start_includes..])
        .find(END_PAT)
        .ok_or(format!("No '{}' in output from {}", END_PAT, gcc_cmd).as_str())?
        + start_includes;

    Ok((&gcc_output[start_includes..end_includes])
       .split('\n')
       .map(|s| PathBuf::from(s.trim().to_string()))
       .collect())
}

fn search_file_in_directory<P>(dirs: &[P], file: &str) -> Result<PathBuf, ()>
where
    P: AsRef<Path>,
{
    for dir in dirs {
        let file_path = dir.as_ref().join(file);
        if file_path.exists() && file_path.is_file() {
            return Ok(file_path);
        }
    }
    Err(())
}

fn gen_binding<P1, P2>(
    target: &str,
    include_dirs: &[P1],
    c_headers: &[P2],
    output_rust: &Path,
) -> Result<(), String>
where
    P1: AsRef<Path> + fmt::Debug,
    P2: AsRef<Path> + fmt::Debug,
{
    assert!(!c_headers.is_empty());
    let c_file_path = &c_headers[0];

    let mut bindings: bindgen::Builder =
        bindgen::builder().header(c_file_path.as_ref().to_str().unwrap());
    bindings = include_dirs.iter().fold(bindings, |acc, x| {
        acc.clang_arg("-I".to_string() + x.as_ref().to_str().unwrap())
    });
    println!("Generate binding for {:?}", c_headers);
    bindings = bindings
        .rust_target(RustTarget::Stable_1_19)
    //long double not supported yet, see https://github.com/servo/rust-bindgen/issues/550
        .blacklist_type("max_align_t");
    bindings = if target.contains("windows") {
        //see https://github.com/servo/rust-bindgen/issues/578
        bindings.trust_clang_mangling(false)
    } else {
        bindings
    };
    bindings = c_headers[1..].iter().fold(
        Ok(bindings),
        |acc: Result<bindgen::Builder, String>, header| {
            let c_file_path = header;
            let c_file_str = c_file_path
                .as_ref()
                .to_str()
                .ok_or_else(|| format!("Invalid unicode in path to {:?}", c_file_path.as_ref()))?;
            Ok(acc.unwrap().clang_arg("-include").clang_arg(c_file_str))
        },
    )?;

    let generated_bindings = bindings
    //        .clang_arg(format!("-target {}", target))
        .generate()
        .map_err(|_| "Failed to generate bindings".to_string())?;
    generated_bindings
        .write_to_file(output_rust)
        .map_err(|err| err.to_string())?;

    Ok(())
}

fn rust_swig_expand(source_dir: &Path, file: &Path, out_dir: &Path) -> Result<(), String> {
    let app_id = env::var("ANDROID_APPLICATION_ID")
        .expect("You must set ANDROID_APPLICATION_ID to the package name of your android application.");

    let mut registry = syntex::Registry::new();
    let swig_gen = rust_swig::Generator::new(LanguageConfig::JavaConfig(
        JavaConfig::new(
            Path::new(ANDROID_BASE_DIR)
                .join("src")
                .join("main")
                .join("java")
                .join(app_id.replace(".", "/")),
            app_id.to_owned() // not sure why it requires ownership...
        ).use_null_annotation("android.support.annotation.NonNull".into()),
    ));
    swig_gen.register(&mut registry);

    let out_file = out_dir.join(Path::new(file.parent().unwrap_or(Path::new(".")))
                                .join(file.file_stem().expect("Got invalid file (no filename)")));

    registry
        .expand(app_id.as_ref(), source_dir.join(file), out_file)
        .map_err(|err| format!("Rust-SWIG expansion failed: {}", err))
}

fn write_include_file(source_dir: &Path, swig_file: &Path) -> std::io::Result<()> {
    let rs_rel_file = Path::new(swig_file.parent().unwrap_or(Path::new(".")))
        .join(swig_file.file_stem().expect("Got invalid file (no filename)"));
    let rs_path = source_dir.join(&rs_rel_file);

    if rs_path.exists() {
        println!("Not writing {} because it exists", rs_path.display());
        return Ok(());
    }

    let mut rs_file = File::create(rs_path)?;
    rs_file.write_all(format!("include!(concat!(env!(\"OUT_DIR\"), \"/{}\"",
                              rs_rel_file.to_string_lossy()).as_bytes())?;

    return Ok(());
}
<commit_msg>Added fallback for RUSTC_LINKER<commit_after>/* CONFIGURATION */

// add other android system headers to this list as necessary
static INCLUDE_SYS_H: [&str; 1] = ["jni.h"];

static RUST_SRC_DIR: &str = "src";
static ANDROID_BASE_DIR: &str = "app";

// =========================================================
// This script is portable; copy and paste it into your own
// build files at will.

extern crate bindgen;
extern crate rust_swig;
extern crate syntex;
extern crate walkdir;

use std::process::{Command, Stdio};
use std::{env, fmt};
use std::io::prelude::*;
use std::fs::File;
use std::path::{Path, PathBuf};

use bindgen::RustTarget;
use rust_swig::{JavaConfig, LanguageConfig};
use walkdir::WalkDir;

fn main() {
    // don't simplify this to if the target contains the substring "android" --
    // these lines also serve as a guard so only true android triples receive
    // JNI generation.
    let target = env::var("TARGET").unwrap();
    if ["aarch64-linux-android",
        "arm-linux-androideabi",
        "i686-linux-android",
        "x86_64-linux-android"]
        .contains(&target.as_str()) {
            gen_for_android();
        }
}

fn gen_for_android() {
    let target = env::var("TARGET").unwrap();

    let include_dirs =
        get_gcc_system_include_dirs(&target).expect("Can't get NDK's system include dirs");

    let include_headers: Vec<_> = INCLUDE_SYS_H.into_iter()
        .map(|h| search_file_in_directory(&include_dirs, h)
             .expect(format!("Could not find header {}", h).as_ref()))
        .collect();

    let src_dir = Path::new(RUST_SRC_DIR);
    let out_dir = env::var("OUT_DIR").unwrap();

    gen_binding(
        &target,
        &include_dirs,
        &include_headers,
        &Path::new(&out_dir).join("android_c_headers.rs"),
    ).unwrap();

    // Find files ending in .rs.in and expand them with SWIG
    for _entry in WalkDir::new(RUST_SRC_DIR) {
        let entry = _entry.expect("Error walking sources.");
        if entry.path().is_dir() || !entry.path().to_string_lossy().ends_with(".rs.in") {
            continue;
        }

        println!("Found SWIG specification: {}", entry.path().display());
        let swigf = entry.path().strip_prefix("src").unwrap();

        rust_swig_expand(
            &src_dir,
            &swigf,
            Path::new(&out_dir),
        ).unwrap();

        write_include_file(&src_dir, swigf).expect("Failed to write include file.");
    }

    // Hook up cargo reruns
    println!("cargo:rerun-if-changed={}", RUST_SRC_DIR);
    for dir in &include_dirs {println!("cargo:rerun-if-changed={}", dir.display());}
    //if the generated files were deleted (e.g by gradle -q clean), regenerate them
    println!("cargo:rerun-if-changed={}", out_dir);
}

fn get_gcc_system_include_dirs(target: &str) -> Result<Vec<PathBuf>, String> {
    let gcc_cmd = match env::var("RUSTC_LINKER") {
        Ok(path) => path,
        Err(_) => target.to_owned() + "-gcc"
    };

    assert!(Path::new(&gcc_cmd).exists(),
            "RUSTC_LINKER not set -- Update your version of Cargo
or merge PR#5394 from github.com/rust-lang/cargo.");

    println!("Using Android gcc from '{}'", gcc_cmd);

    let gcc_process = Command::new(&gcc_cmd)
        .args(&["-v", "-x", "c", "-E", "-" /*, &("--sysroot=".to_owned() + &sysroot)*/])
        .stderr(Stdio::piped())
        .stdin(Stdio::piped())
        .stdout(Stdio::inherit())
        .spawn()
        .map_err(|err| err.to_string())?;

    gcc_process
        .stdin
        .ok_or(format!("Cannot get stdin of {}", gcc_cmd).as_str())?
        .write_all("\n".as_bytes())
        .map_err(|err| err.to_string())?;

    let mut gcc_output = String::new();
    gcc_process
        .stderr
        .ok_or(format!("Cannot get stderr of {}", gcc_cmd).as_str())?
        .read_to_string(&mut gcc_output)
        .map_err(|err| err.to_string())?;

    const BEGIN_PAT: &'static str = "\n#include <...> search starts here:\n";
    const END_PAT: &'static str = "\nEnd of search list.\n";
    let start_includes = gcc_output
        .find(BEGIN_PAT)
        .ok_or(format!("No '{}' in output from {}", BEGIN_PAT, gcc_cmd).as_str())?
        + BEGIN_PAT.len();
    let end_includes = (&gcc_output[start_includes..])
        .find(END_PAT)
        .ok_or(format!("No '{}' in output from {}", END_PAT, gcc_cmd).as_str())?
        + start_includes;

    Ok((&gcc_output[start_includes..end_includes])
       .split('\n')
       .map(|s| PathBuf::from(s.trim().to_string()))
       .collect())
}

fn search_file_in_directory<P>(dirs: &[P], file: &str) -> Result<PathBuf, ()>
where
    P: AsRef<Path>,
{
    for dir in dirs {
        let file_path = dir.as_ref().join(file);
        if file_path.exists() && file_path.is_file() {
            return Ok(file_path);
        }
    }
    Err(())
}

fn gen_binding<P1, P2>(
    target: &str,
    include_dirs: &[P1],
    c_headers: &[P2],
    output_rust: &Path,
) -> Result<(), String>
where
    P1: AsRef<Path> + fmt::Debug,
    P2: AsRef<Path> + fmt::Debug,
{
    assert!(!c_headers.is_empty());
    let c_file_path = &c_headers[0];

    let mut bindings: bindgen::Builder =
        bindgen::builder().header(c_file_path.as_ref().to_str().unwrap());
    bindings = include_dirs.iter().fold(bindings, |acc, x| {
        acc.clang_arg("-I".to_string() + x.as_ref().to_str().unwrap())
    });
    println!("Generate binding for {:?}", c_headers);
    bindings = bindings
        .rust_target(RustTarget::Stable_1_19)
    //long double not supported yet, see https://github.com/servo/rust-bindgen/issues/550
        .blacklist_type("max_align_t");
    bindings = if target.contains("windows") {
        //see https://github.com/servo/rust-bindgen/issues/578
        bindings.trust_clang_mangling(false)
    } else {
        bindings
    };
    bindings = c_headers[1..].iter().fold(
        Ok(bindings),
        |acc: Result<bindgen::Builder, String>, header| {
            let c_file_path = header;
            let c_file_str = c_file_path
                .as_ref()
                .to_str()
                .ok_or_else(|| format!("Invalid unicode in path to {:?}", c_file_path.as_ref()))?;
            Ok(acc.unwrap().clang_arg("-include").clang_arg(c_file_str))
        },
    )?;

    let generated_bindings = bindings
    //        .clang_arg(format!("-target {}", target))
        .generate()
        .map_err(|_| "Failed to generate bindings".to_string())?;
    generated_bindings
        .write_to_file(output_rust)
        .map_err(|err| err.to_string())?;

    Ok(())
}

fn rust_swig_expand(source_dir: &Path, file: &Path, out_dir: &Path) -> Result<(), String> {
    let app_id = env::var("ANDROID_APPLICATION_ID")
        .expect("You must set ANDROID_APPLICATION_ID to the package name of your android application.");

    let mut registry = syntex::Registry::new();
    let swig_gen = rust_swig::Generator::new(LanguageConfig::JavaConfig(
        JavaConfig::new(
            Path::new(ANDROID_BASE_DIR)
                .join("src")
                .join("main")
                .join("java")
                .join(app_id.replace(".", "/")),
            app_id.to_owned() // not sure why it requires ownership...
        ).use_null_annotation("android.support.annotation.NonNull".into()),
    ));
    swig_gen.register(&mut registry);

    let out_file = out_dir.join(Path::new(file.parent().unwrap_or(Path::new(".")))
                                .join(file.file_stem().expect("Got invalid file (no filename)")));

    registry
        .expand(app_id.as_ref(), source_dir.join(file), out_file)
        .map_err(|err| format!("Rust-SWIG expansion failed: {}", err))
}

fn write_include_file(source_dir: &Path, swig_file: &Path) -> std::io::Result<()> {
    let rs_rel_file = Path::new(swig_file.parent().unwrap_or(Path::new(".")))
        .join(swig_file.file_stem().expect("Got invalid file (no filename)"));
    let rs_path = source_dir.join(&rs_rel_file);

    if rs_path.exists() {
        println!("Not writing {} because it exists", rs_path.display());
        return Ok(());
    }

    let mut rs_file = File::create(rs_path)?;
    rs_file.write_all(format!("include!(concat!(env!(\"OUT_DIR\"), \"/{}\"",
                              rs_rel_file.to_string_lossy()).as_bytes())?;

    return Ok(());
}
<|endoftext|>


<commit_before>use core::*;
use tables::*;

#[derive(Debug, PartialEq, Clone)]
pub struct Board {
    pieces: [Bitboard;12],
    occupied: [Bitboard;2],
    unoccupied: Bitboard,
}

impl Board {
    pub fn starting_position() -> Board {
        return Board {
            pieces: [ Bitboard::new(0x000000000000FF00), Bitboard::new(71776119061217280),
                      Bitboard::new(0x0000000000000042), Bitboard::new(0x4200000000000000),
                      Bitboard::new(0x0000000000000024), Bitboard::new(0x2400000000000000),
                      Bitboard::new(0x0000000000000081), Bitboard::new(0x8100000000000000),
                      Bitboard::new(0x0000000000000008), Bitboard::new(0x0800000000000000),
                      Bitboard::new(0x0000000000000010), Bitboard::new(0x1000000000000000)],
            occupied: [ Bitboard::new(0x000000000000FFFF), Bitboard::new(0xFFFF000000000000) ],
            unoccupied: Bitboard::new(0x0000FFFFFFFF0000)
        }
    }

    pub fn empty_position() -> Board {
        return Board {
            pieces: [ Bitboard::new(0), Bitboard::new(0),
                      Bitboard::new(0), Bitboard::new(0),
                      Bitboard::new(0), Bitboard::new(0),
                      Bitboard::new(0), Bitboard::new(0),
                      Bitboard::new(0), Bitboard::new(0),
                      Bitboard::new(0), Bitboard::new(0)],
            occupied: [ Bitboard::new(0), Bitboard::new(0) ],
            unoccupied: Bitboard::new(0xFFFFFFFFFFFFFFFF)
        }
    }

    pub fn get_pieces(&self, color: Color, ptype: PieceType) -> Bitboard {
        let idx = 2 * ptype as usize + color as usize;
        return self.pieces[idx];
    }

    pub fn occupied_by(&self, color: Color) -> Bitboard {
        return self.occupied[color as usize];
    }

    pub fn occupied(&self) -> Bitboard {
        return self.occupied[0] | self.occupied[1];
    }

    pub fn unoccupied(&self) -> Bitboard {
        return self.unoccupied;
    }

    // pub fn update(&mut self, color: Color, ptype: PieceType, newBB: Bitboard) {
    //     let idx = 2 * (ptype as usize) + (color as usize);
    //     self.0[idx] = newBB;
    // }

    pub fn color_at(&self, sq: Square) -> Option<Color> {
        let bit = sq.bitrep();

        if (bit & self.occupied()).empty() { return None }

        if (bit & self.occupied_by(Color::White)).nonempty() {
            return Some(Color::White);
        } else {
            return Some(Color::Black);
        };
    }

    pub fn piece_at(&self, sq: Square) -> Option<Piece> {

        match self.color_at(sq) {
            None => return None,
            Some(col) => {
                let bit = sq.bitrep();
                for pt in PieceType::all() {
                    if (bit & self.get_pieces(col, *pt)).nonempty() {
                        return Some(Piece { ptype: *pt, color: col });
                    }
                }
            }
        }

        //TODO: log warning
        return None;
    }

    pub fn get_king_square(&self, color: Color) -> Square {
        self.get_pieces(color, PieceType::King).bitscan_forward()
    }

    pub fn is_square_attacked_by(&self, square: Square, color: Color) -> bool {
        use PieceType::*;

        if (PAWN_ATTACKS[!color as usize][square.idx()] & self.get_pieces(color, Pawn)).nonempty() {
            return true;
        } else if (KNIGHT_TABLE[square.idx()] & self.get_pieces(color, Knight)).nonempty() {
            return true;
        } else if (KING_TABLE[square.idx()] & self.get_pieces(color, King)).nonempty() {
            return true;
        }

        let occupied = self.occupied();

        let bishops_queens = self.get_pieces(color, Queen) | self.get_pieces(color, Bishop);
        if (get_bishop_rays(square, occupied) & bishops_queens).nonempty() {
            return true;
        }

        let rooks_queens = self.get_pieces(color, Queen) | self.get_pieces(color, Rook);
        if (get_rook_rays(square, occupied) & rooks_queens).nonempty() {
            return true;
        }

        return false;
    }
}
<commit_msg>added get_pieces_mut to grab mutable bitboards from a Board<commit_after>use core::*;
use tables::*;

#[derive(Debug, PartialEq, Clone)]
pub struct Board {
    pieces: [Bitboard;12],
    occupied: [Bitboard;2],
    unoccupied: Bitboard,
}

impl Board {
    pub fn starting_position() -> Board {
        return Board {
            pieces: [ Bitboard::new(0x000000000000FF00), Bitboard::new(71776119061217280),
                      Bitboard::new(0x0000000000000042), Bitboard::new(0x4200000000000000),
                      Bitboard::new(0x0000000000000024), Bitboard::new(0x2400000000000000),
                      Bitboard::new(0x0000000000000081), Bitboard::new(0x8100000000000000),
                      Bitboard::new(0x0000000000000008), Bitboard::new(0x0800000000000000),
                      Bitboard::new(0x0000000000000010), Bitboard::new(0x1000000000000000)],
            occupied: [ Bitboard::new(0x000000000000FFFF), Bitboard::new(0xFFFF000000000000) ],
            unoccupied: Bitboard::new(0x0000FFFFFFFF0000)
        }
    }

    pub fn empty_position() -> Board {
        return Board {
            pieces: [ Bitboard::new(0), Bitboard::new(0),
                      Bitboard::new(0), Bitboard::new(0),
                      Bitboard::new(0), Bitboard::new(0),
                      Bitboard::new(0), Bitboard::new(0),
                      Bitboard::new(0), Bitboard::new(0),
                      Bitboard::new(0), Bitboard::new(0)],
            occupied: [ Bitboard::new(0), Bitboard::new(0) ],
            unoccupied: Bitboard::new(0xFFFFFFFFFFFFFFFF)
        }
    }

    pub fn get_pieces(&self, color: Color, ptype: PieceType) -> Bitboard {
        let idx = 2 * ptype as usize + color as usize;
        return self.pieces[idx];
    }

    pub fn get_pieces_mut(&mut self, color: Color, ptype: PieceType) -> &mut Bitboard {
        let idx = 2 * ptype as usize + color as usize;
        return &mut self.pieces[idx];
    }

    pub fn occupied_by(&self, color: Color) -> Bitboard {
        return self.occupied[color as usize];
    }

    pub fn occupied(&self) -> Bitboard {
        return self.occupied[0] | self.occupied[1];
    }

    pub fn unoccupied(&self) -> Bitboard {
        return self.unoccupied;
    }

    // pub fn update(&mut self, color: Color, ptype: PieceType, newBB: Bitboard) {
    //     let idx = 2 * (ptype as usize) + (color as usize);
    //     self.0[idx] = newBB;
    // }

    pub fn color_at(&self, sq: Square) -> Option<Color> {
        let bit = sq.bitrep();

        if (bit & self.occupied()).empty() { return None }

        if (bit & self.occupied_by(Color::White)).nonempty() {
            return Some(Color::White);
        } else {
            return Some(Color::Black);
        };
    }

    pub fn piece_at(&self, sq: Square) -> Option<Piece> {

        match self.color_at(sq) {
            None => return None,
            Some(col) => {
                let bit = sq.bitrep();
                for pt in PieceType::all() {
                    if (bit & self.get_pieces(col, *pt)).nonempty() {
                        return Some(Piece { ptype: *pt, color: col });
                    }
                }
            }
        }

        //TODO: log warning
        return None;
    }

    pub fn get_king_square(&self, color: Color) -> Square {
        self.get_pieces(color, PieceType::King).bitscan_forward()
    }

    pub fn is_square_attacked_by(&self, square: Square, color: Color) -> bool {
        use PieceType::*;

        if (PAWN_ATTACKS[!color as usize][square.idx()] & self.get_pieces(color, Pawn)).nonempty() {
            return true;
        } else if (KNIGHT_TABLE[square.idx()] & self.get_pieces(color, Knight)).nonempty() {
            return true;
        } else if (KING_TABLE[square.idx()] & self.get_pieces(color, King)).nonempty() {
            return true;
        }

        let occupied = self.occupied();

        let bishops_queens = self.get_pieces(color, Queen) | self.get_pieces(color, Bishop);
        if (get_bishop_rays(square, occupied) & bishops_queens).nonempty() {
            return true;
        }

        let rooks_queens = self.get_pieces(color, Queen) | self.get_pieces(color, Rook);
        if (get_rook_rays(square, occupied) & rooks_queens).nonempty() {
            return true;
        }

        return false;
    }
}
<|endoftext|>


<commit_before>// Copyright 2018 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#![feature(uniform_paths)]
//! Simple efficient composable primitives for pretty printing.
//!
//! The implementation is derived from the paper ["A New Approach to Optimal
//! Code Formatting"][pp-paper] by Phillip M. Yelland.
//!
//! [pp-paper]: https://static.googleusercontent.com/media/research.google.com/en//pubs/archive/44667.pdf

extern crate unicode_width;

mod knot_column;
mod knot_set;
mod linear_value;
mod resolved_layout;
mod shared_string;

use std::borrow::Borrow;
use std::collections as col;
use std::fmt;
use std::rc;

use shared_string::SharedString;

const OVERFLOW_COST: f32 = 100.0;
const NEWLINE_COST: f32 = 1.0;

/// The primary representation of pretty-printed text. Logically, it represents
/// a set of possible permissible layouts of text.
///
/// Layouts are constructed with four different primitives:
///
/// 1. Text
///
///    A literal string which is laid out as written. Its length is obtained
/// using the    `unicode-width` package.
///
/// 2. Stack
///
///    Vertically stacks two layouts. The left margins of the two layouts will
/// be    aligned.
///
/// 3. Juxtapose
///
///    Horizontally juxtapose two layouts. The left margin of the second layout
///    will be aligned with the end of the first layout's last line.
///
/// 4. Choice
///
///    Creates a choice between two or more layouts. The choice is made at
/// layout    time based on the cost of each possible layout. See the `layout`
/// method.
#[derive(Clone)]
pub struct Layout(rc::Rc<LayoutContents>);

impl Layout {
  fn with_contents(contents: LayoutContents) -> Layout {
    Layout(rc::Rc::new(contents))
  }

  fn contents(&self) -> &LayoutContents {
    &*self.0
  }

  /// Create a text layout value. This is a literal string with no layout
  /// variance.
  pub fn text(lit_text: impl Into<String>) -> Layout {
    Layout::with_contents(LayoutContents::Text(lit_text.into().into()))
  }

  fn choice_pair(first: &Layout, second: &Layout) -> Layout {
    // We should canonicalize this so that the choices are always in the same
    // order.
    Layout::with_contents(LayoutContents::Choice(first.clone(), second.clone()))
  }

  fn stack_pair(top: &Layout, bottom: &Layout) -> Layout {
    Layout::with_contents(LayoutContents::Stack(top.clone(), bottom.clone()))
  }

  /// Create a layout that is the juxtaposition of two other layouts.
  ///
  /// This lays out the latter layout immediately to the right of the last line
  /// of the left layout.
  pub fn juxtapose_pair(left: &Layout, right: &Layout) -> Layout {
    let mut builder = JuxtaposeBuilder::new(right);
    builder.juxtapose(left)
  }

  /// Creates a layout that is the lowest-cost choice of layouts provided.
  pub fn choices<S, T>(items: S) -> Layout
  where
    S: AsRef<[T]>,
    T: Borrow<Layout>,
  {
    let items = items.as_ref();
    assert!(items.len() > 0);
    let mut curr_layout = items[0].borrow().clone();
    for item in &items[1..] {
      curr_layout = Layout::choice_pair(&curr_layout, item.borrow());
    }

    curr_layout
  }

  /// Create a stack of the layouts, where each of the layouts are
  /// vertically stacked on top of each other in the order provided.
  pub fn stack<'a, S, T>(items: S) -> Layout
  where
    S: AsRef<[T]>,
    T: Borrow<Layout>,
  {
    let items = items.as_ref();
    if items.len() == 0 {
      return Layout::text("");
    }
    assert!(items.len() > 0);
    let mut curr_layout = items[0].borrow().clone();
    for item in &items[1..] {
      curr_layout = Layout::stack_pair(&curr_layout, item.borrow());
    }
    curr_layout
  }

  /// Creates a juxtoposition of layouts, with each layout immediately
  /// following the last line of the previous layout.
  pub fn juxtapose<S, T>(items: S) -> Layout
  where
    S: AsRef<[T]>,
    T: Borrow<Layout>,
  {
    let items = items.as_ref();
    assert!(items.len() > 0);
    let mut curr_layout = items[0].borrow().clone();
    for item in &items[1..] {
      curr_layout = Layout::juxtapose_pair(&curr_layout, item.borrow());
    }
    curr_layout
  }

  /// Lays out the contents of this layout for a text buffer of width margin.
  pub fn layout(&self, margin: u16) -> String {
    self.layout_with_costs(margin, OVERFLOW_COST, NEWLINE_COST)
  }

  /// Lays out the contents of this layout for a text buffer of width margin,
  /// and with newline costs and overflow costs as provided.
  ///
  /// For each character over the margin width, the overflow cost is incurred.
  /// For each newline in the result, the newline cost is incurred. The layout
  /// chosen is that with the smallest overall cost.
  pub fn layout_with_costs(
    &self,
    margin: u16,
    overflow_cost: f32,
    newline_cost: f32,
  ) -> String {
    let final_layout =
      knot_set::do_layout(self, overflow_cost, newline_cost, margin);
    return final_layout.to_text(0);
  }

  #[doc(hidden)]
  pub fn debug_num_nodes(&self) -> usize {
    let mut counter = NodeCounter::new();
    counter.visit_node(self);
    counter.get_count()
  }

  fn wrap_inner<T: Borrow<Layout>>(
    layouts: &[T],
  ) -> (Layout, Vec<(Layout, Option<Layout>)>) {
    if layouts.len() == 0 {
      (Layout::text(""), vec![])
    } else if layouts.len() == 1 {
      let singleton = layouts[0].borrow();
      (
        singleton.borrow().clone(),
        vec![(singleton.borrow().clone(), None)],
      )
    } else {
      let first = layouts[0].borrow();
      let rest = &layouts[1..];
      let (block, line_blocks) = Layout::wrap_inner(rest);

      let mut new_line_pairs: Vec<_> = line_blocks
        .into_iter()
        .map(|(l, b)| {
          (
            Layout::juxtapose(&[first.borrow(), &Layout::text(" "), &l]),
            b,
          )
        })
        .collect();
      new_line_pairs.push((first.borrow().clone(), Some(block)));

      let new_choices: Vec<_> = new_line_pairs
        .iter()
        .map(|(k, v)| match v {
          Some(b) => Layout::stack_pair(k, b),
          None => k.clone(),
        })
        .collect();

      (Layout::choices(&new_choices), new_line_pairs)
    }
  }

  pub fn wrap<S, T>(layouts: S) -> Layout
  where
    S: AsRef<[T]>,
    T: Borrow<Layout>,
  {
    let slice = layouts.as_ref();
    let (result, _) = Layout::wrap_inner(slice);
    result
  }
}

impl fmt::Debug for Layout {
  fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
    <LayoutContents as fmt::Debug>::fmt(&*self.0, f)
  }
}

#[derive(Debug)]
enum LayoutContents {
  Text(SharedString),
  Choice(Layout, Layout),
  Stack(Layout, Layout),
  Juxtapose(SharedString, Layout),
}

struct JuxtaposeBuilder {
  right: Layout,
  memo: col::BTreeMap<*const LayoutContents, Layout>,
}

impl JuxtaposeBuilder {
  fn new(right: &Layout) -> Self {
    JuxtaposeBuilder {
      right: right.clone(),
      memo: col::BTreeMap::new(),
    }
  }

  fn juxtapose(&mut self, left: &Layout) -> Layout {
    if let Some(v) = self.memo.get(&(left.contents() as *const LayoutContents))
    {
      return v.clone();
    }

    let new_layout = match left.contents() {
      LayoutContents::Text(t) => Layout::with_contents(
        LayoutContents::Juxtapose(t.clone(), self.right.clone()),
      ),
      LayoutContents::Choice(first, second) => Layout::with_contents(
        LayoutContents::Choice(self.juxtapose(first), self.juxtapose(second)),
      ),
      LayoutContents::Stack(top, bottom) => Layout::with_contents(
        LayoutContents::Stack(top.clone(), self.juxtapose(bottom)),
      ),
      LayoutContents::Juxtapose(text, jux_right) => Layout::with_contents(
        LayoutContents::Juxtapose(text.clone(), self.juxtapose(jux_right)),
      ),
    };

    self
      .memo
      .insert(left.contents() as *const LayoutContents, new_layout.clone());
    new_layout
  }
}

struct NodeCounter {
  seen: col::BTreeSet<*const LayoutContents>,
}

impl NodeCounter {
  fn new() -> Self {
    NodeCounter {
      seen: col::BTreeSet::new(),
    }
  }
  fn visit_node(&mut self, layout: &Layout) {
    if self.seen.insert(layout.contents() as *const LayoutContents) {
      use LayoutContents::*;
      match layout.contents() {
        Text(_) => {}
        Choice(first, second) => {
          self.visit_node(first);
          self.visit_node(second);
        }
        Stack(top, bottom) => {
          self.visit_node(top);
          self.visit_node(bottom);
        }
        Juxtapose(_left, right) => {
          self.visit_node(right);
        }
      }
    }
  }

  fn get_count(&self) -> usize {
    self.seen.len()
  }
}

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

  #[test]
  fn test_simple_set() {
    let foo = Layout::text("foo");
    let pair = Layout::juxtapose(&[&foo, &foo]);
    assert_eq!(pair.layout(10), "foofoo");
  }

  #[test]
  fn test_simple_stack() {
    let foo = Layout::text("foo");
    let pair = Layout::stack(&[&foo, &foo]);
    assert_eq!(pair.layout(10), "foo\nfoo");
  }

  #[test]
  fn test_simple_choice() {
    let foo = Layout::text("foo");
    let pair = Layout::choices(&[
      &Layout::juxtapose(&[&foo, &foo]),
      &Layout::stack(&[&foo, &foo]),
    ]);
    assert_eq!(pair.layout(10), "foofoo");
    assert_eq!(pair.layout(4), "foo\nfoo");
  }

  #[test]
  fn test_wrap() {
    let lorem = &"Lorem ipsum dolor sit amet, consectetur adipiscing elit.
    Nullam suscipit dolor sed dolor facilisis ultrices ut id nisl. Nam
    malesuada malesuada dolor, eget dapibus nibh euismod at. Vestibulum
    aliquam aliquam mi at tincidunt. Sed imperdiet eget purus in egestas.
    Suspendisse id odio in augue cursus tempor. Duis imperdiet imperdiet eros
    et lobortis. Vestibulum vestibulum condimentum dui, sit amet fringilla libero
    commodo at. Sed aliquam mauris vitae egestas convallis. Integer sed est vitae
    nibh pellentesque sodales. Suspendisse sit amet dignissim arcu. Quisque hendrerit
    pellentesque egestas. Nulla at elementum est. Maecenas lectus turpis, placerat
    vitae est sit amet, mattis pharetra orci. Praesent.";
    let words: Vec<_> =
      lorem.split_whitespace().map(|k| Layout::text(k)).collect();
    let layout = Layout::wrap(words);
    println!("{}", layout.debug_num_nodes());
    assert_eq!(layout.layout(80).chars().filter(|c| c == &'\n').count(), 9);
    assert_eq!(layout.layout(100).chars().filter(|c| c == &'\n').count(), 7);
  }

  #[test]
  fn test_large_stack() {
    let foo = Layout::text("foo");
    let bar = Layout::text("bar");
    let foo_stack = Layout::stack(&[&foo, &bar]);
    let foo_jux = Layout::juxtapose(&[&foo, &bar]);
    let foo_choice = Layout::choices(&[&foo_stack, &foo_jux]);

    let choice = Layout::juxtapose(&vec![&foo_choice; 1000]);

    println!("Done creating layout.");
    println!("Num nodes: {}", choice.debug_num_nodes());

    choice.layout(500);
  }
}
<commit_msg>Remove configuration flag to make the code compatible with Rust 1.31<commit_after>// Copyright 2018 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//! Simple efficient composable primitives for pretty printing.
//!
//! The implementation is derived from the paper ["A New Approach to Optimal
//! Code Formatting"][pp-paper] by Phillip M. Yelland.
//!
//! [pp-paper]: https://static.googleusercontent.com/media/research.google.com/en//pubs/archive/44667.pdf

extern crate unicode_width;

mod knot_column;
mod knot_set;
mod linear_value;
mod resolved_layout;
mod shared_string;

use std::borrow::Borrow;
use std::collections as col;
use std::fmt;
use std::rc;

use self::shared_string::SharedString;

const OVERFLOW_COST: f32 = 100.0;
const NEWLINE_COST: f32 = 1.0;

/// The primary representation of pretty-printed text. Logically, it represents
/// a set of possible permissible layouts of text.
///
/// Layouts are constructed with four different primitives:
///
/// 1. Text
///
///    A literal string which is laid out as written. Its length is obtained
/// using the    `unicode-width` package.
///
/// 2. Stack
///
///    Vertically stacks two layouts. The left margins of the two layouts will
///    be aligned.
///
/// 3. Juxtapose
///
///    Horizontally juxtapose two layouts. The left margin of the second layout
///    will be aligned with the end of the first layout's last line.
///
/// 4. Choice
///
///    Creates a choice between two or more layouts. The choice is made at
/// layout    time based on the cost of each possible layout. See the `layout`
/// method.
#[derive(Clone)]
pub struct Layout(rc::Rc<LayoutContents>);

impl Layout {
  fn with_contents(contents: LayoutContents) -> Layout {
    Layout(rc::Rc::new(contents))
  }

  fn contents(&self) -> &LayoutContents {
    &*self.0
  }

  /// Create a text layout value. This is a literal string with no layout
  /// variance.
  pub fn text(lit_text: impl Into<String>) -> Layout {
    Layout::with_contents(LayoutContents::Text(lit_text.into().into()))
  }

  fn choice_pair(first: &Layout, second: &Layout) -> Layout {
    // We should canonicalize this so that the choices are always in the same
    // order.
    Layout::with_contents(LayoutContents::Choice(first.clone(), second.clone()))
  }

  fn stack_pair(top: &Layout, bottom: &Layout) -> Layout {
    Layout::with_contents(LayoutContents::Stack(top.clone(), bottom.clone()))
  }

  /// Create a layout that is the juxtaposition of two other layouts.
  ///
  /// This lays out the latter layout immediately to the right of the last line
  /// of the left layout.
  pub fn juxtapose_pair(left: &Layout, right: &Layout) -> Layout {
    let mut builder = JuxtaposeBuilder::new(right);
    builder.juxtapose(left)
  }

  /// Creates a layout that is the lowest-cost choice of layouts provided.
  pub fn choices<S, T>(items: S) -> Layout
  where
    S: AsRef<[T]>,
    T: Borrow<Layout>,
  {
    let items = items.as_ref();
    assert!(items.len() > 0);
    let mut curr_layout = items[0].borrow().clone();
    for item in &items[1..] {
      curr_layout = Layout::choice_pair(&curr_layout, item.borrow());
    }

    curr_layout
  }

  /// Create a stack of the layouts, where each of the layouts are
  /// vertically stacked on top of each other in the order provided.
  pub fn stack<'a, S, T>(items: S) -> Layout
  where
    S: AsRef<[T]>,
    T: Borrow<Layout>,
  {
    let items = items.as_ref();
    if items.len() == 0 {
      return Layout::text("");
    }
    assert!(items.len() > 0);
    let mut curr_layout = items[0].borrow().clone();
    for item in &items[1..] {
      curr_layout = Layout::stack_pair(&curr_layout, item.borrow());
    }
    curr_layout
  }

  /// Creates a juxtoposition of layouts, with each layout immediately
  /// following the last line of the previous layout.
  pub fn juxtapose<S, T>(items: S) -> Layout
  where
    S: AsRef<[T]>,
    T: Borrow<Layout>,
  {
    let items = items.as_ref();
    assert!(items.len() > 0);
    let mut curr_layout = items[0].borrow().clone();
    for item in &items[1..] {
      curr_layout = Layout::juxtapose_pair(&curr_layout, item.borrow());
    }
    curr_layout
  }

  /// Lays out the contents of this layout for a text buffer of width margin.
  pub fn layout(&self, margin: u16) -> String {
    self.layout_with_costs(margin, OVERFLOW_COST, NEWLINE_COST)
  }

  /// Lays out the contents of this layout for a text buffer of width margin,
  /// and with newline costs and overflow costs as provided.
  ///
  /// For each character over the margin width, the overflow cost is incurred.
  /// For each newline in the result, the newline cost is incurred. The layout
  /// chosen is that with the smallest overall cost.
  pub fn layout_with_costs(
    &self,
    margin: u16,
    overflow_cost: f32,
    newline_cost: f32,
  ) -> String {
    let final_layout =
      knot_set::do_layout(self, overflow_cost, newline_cost, margin);
    return final_layout.to_text(0);
  }

  #[doc(hidden)]
  pub fn debug_num_nodes(&self) -> usize {
    let mut counter = NodeCounter::new();
    counter.visit_node(self);
    counter.get_count()
  }

  fn wrap_inner<T: Borrow<Layout>>(
    layouts: &[T],
  ) -> (Layout, Vec<(Layout, Option<Layout>)>) {
    if layouts.len() == 0 {
      (Layout::text(""), vec![])
    } else if layouts.len() == 1 {
      let singleton = layouts[0].borrow();
      (
        singleton.borrow().clone(),
        vec![(singleton.borrow().clone(), None)],
      )
    } else {
      let first = layouts[0].borrow();
      let rest = &layouts[1..];
      let (block, line_blocks) = Layout::wrap_inner(rest);

      let mut new_line_pairs: Vec<_> = line_blocks
        .into_iter()
        .map(|(l, b)| {
          (
            Layout::juxtapose(&[first.borrow(), &Layout::text(" "), &l]),
            b,
          )
        })
        .collect();
      new_line_pairs.push((first.borrow().clone(), Some(block)));

      let new_choices: Vec<_> = new_line_pairs
        .iter()
        .map(|(k, v)| match v {
          Some(b) => Layout::stack_pair(k, b),
          None => k.clone(),
        })
        .collect();

      (Layout::choices(&new_choices), new_line_pairs)
    }
  }

  pub fn wrap<S, T>(layouts: S) -> Layout
  where
    S: AsRef<[T]>,
    T: Borrow<Layout>,
  {
    let slice = layouts.as_ref();
    let (result, _) = Layout::wrap_inner(slice);
    result
  }
}

impl fmt::Debug for Layout {
  fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
    <LayoutContents as fmt::Debug>::fmt(&*self.0, f)
  }
}

#[derive(Debug)]
enum LayoutContents {
  Text(SharedString),
  Choice(Layout, Layout),
  Stack(Layout, Layout),
  Juxtapose(SharedString, Layout),
}

struct JuxtaposeBuilder {
  right: Layout,
  memo: col::BTreeMap<*const LayoutContents, Layout>,
}

impl JuxtaposeBuilder {
  fn new(right: &Layout) -> Self {
    JuxtaposeBuilder {
      right: right.clone(),
      memo: col::BTreeMap::new(),
    }
  }

  fn juxtapose(&mut self, left: &Layout) -> Layout {
    if let Some(v) = self.memo.get(&(left.contents() as *const LayoutContents))
    {
      return v.clone();
    }

    let new_layout = match left.contents() {
      LayoutContents::Text(t) => Layout::with_contents(
        LayoutContents::Juxtapose(t.clone(), self.right.clone()),
      ),
      LayoutContents::Choice(first, second) => Layout::with_contents(
        LayoutContents::Choice(self.juxtapose(first), self.juxtapose(second)),
      ),
      LayoutContents::Stack(top, bottom) => Layout::with_contents(
        LayoutContents::Stack(top.clone(), self.juxtapose(bottom)),
      ),
      LayoutContents::Juxtapose(text, jux_right) => Layout::with_contents(
        LayoutContents::Juxtapose(text.clone(), self.juxtapose(jux_right)),
      ),
    };

    self
      .memo
      .insert(left.contents() as *const LayoutContents, new_layout.clone());
    new_layout
  }
}

struct NodeCounter {
  seen: col::BTreeSet<*const LayoutContents>,
}

impl NodeCounter {
  fn new() -> Self {
    NodeCounter {
      seen: col::BTreeSet::new(),
    }
  }
  fn visit_node(&mut self, layout: &Layout) {
    if self.seen.insert(layout.contents() as *const LayoutContents) {
      use self::LayoutContents::*;
      match layout.contents() {
        Text(_) => {}
        Choice(first, second) => {
          self.visit_node(first);
          self.visit_node(second);
        }
        Stack(top, bottom) => {
          self.visit_node(top);
          self.visit_node(bottom);
        }
        Juxtapose(_left, right) => {
          self.visit_node(right);
        }
      }
    }
  }

  fn get_count(&self) -> usize {
    self.seen.len()
  }
}

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

  #[test]
  fn test_simple_set() {
    let foo = Layout::text("foo");
    let pair = Layout::juxtapose(&[&foo, &foo]);
    assert_eq!(pair.layout(10), "foofoo");
  }

  #[test]
  fn test_simple_stack() {
    let foo = Layout::text("foo");
    let pair = Layout::stack(&[&foo, &foo]);
    assert_eq!(pair.layout(10), "foo\nfoo");
  }

  #[test]
  fn test_simple_choice() {
    let foo = Layout::text("foo");
    let pair = Layout::choices(&[
      &Layout::juxtapose(&[&foo, &foo]),
      &Layout::stack(&[&foo, &foo]),
    ]);
    assert_eq!(pair.layout(10), "foofoo");
    assert_eq!(pair.layout(4), "foo\nfoo");
  }

  #[test]
  fn test_wrap() {
    let lorem = &"Lorem ipsum dolor sit amet, consectetur adipiscing elit.
    Nullam suscipit dolor sed dolor facilisis ultrices ut id nisl. Nam
    malesuada malesuada dolor, eget dapibus nibh euismod at. Vestibulum
    aliquam aliquam mi at tincidunt. Sed imperdiet eget purus in egestas.
    Suspendisse id odio in augue cursus tempor. Duis imperdiet imperdiet eros
    et lobortis. Vestibulum vestibulum condimentum dui, sit amet fringilla libero
    commodo at. Sed aliquam mauris vitae egestas convallis. Integer sed est vitae
    nibh pellentesque sodales. Suspendisse sit amet dignissim arcu. Quisque hendrerit
    pellentesque egestas. Nulla at elementum est. Maecenas lectus turpis, placerat
    vitae est sit amet, mattis pharetra orci. Praesent.";
    let words: Vec<_> =
      lorem.split_whitespace().map(|k| Layout::text(k)).collect();
    let layout = Layout::wrap(words);
    println!("{}", layout.debug_num_nodes());
    assert_eq!(layout.layout(80).chars().filter(|c| c == &'\n').count(), 9);
    assert_eq!(layout.layout(100).chars().filter(|c| c == &'\n').count(), 7);
  }

  #[test]
  fn test_large_stack() {
    let foo = Layout::text("foo");
    let bar = Layout::text("bar");
    let foo_stack = Layout::stack(&[&foo, &bar]);
    let foo_jux = Layout::juxtapose(&[&foo, &bar]);
    let foo_choice = Layout::choices(&[&foo_stack, &foo_jux]);

    let choice = Layout::juxtapose(&vec![&foo_choice; 1000]);

    println!("Done creating layout.");
    println!("Num nodes: {}", choice.debug_num_nodes());

    choice.layout(500);
  }
}
<|endoftext|>


<commit_before>// Module to represent World coordinates for Player, Bots, Camera, etc.
use camera::Range;
use level::Level;

/// Struct to represent the world coordinates
#[derive(Copy, Clone, Debug)]
pub struct Coordinate {
    x: u64,
    y: u64,
}

impl Coordinate {
    /// Creates a Coordinate wth the given x and y-value
    pub fn new(x: u64, y: u64) -> Self {
        Coordinate { x: x, y: y }
    }

    /// Creates a Coordinate in the origin (0,0)
    pub fn origin() -> Self {
        Coordinate::new(0, 0)
    }

    /// Getter for the x-value in the coordinates
    pub fn get_x(&self) -> u64 {
        self.x
    }

    /// Getter for the y-value in the coordinates
    pub fn get_y(&self) -> u64 {
        self.y
    }

    /// Move the coordinates and prevents leaving the camera, leaving the level,
    /// or collide with other coordinates, except of the camera. Also checks, if
    /// field on new coordinate is passable
    pub fn move_coord_with_cam(&mut self, dx: i64, dy: i64, level: &mut Level, range: Range) {
        self.move_coord_without_cam(dx, dy, 0, 0, level);
        self.cam_border(range);
    }

    /// Sets the coordinate to the given new position (No checking)
    pub fn set_coord(&mut self, x: u64, y: u64) {
        self.x = x;
        self.y = y;
    }

    /// Sets the positon of the camera and prevents leaving Level
    fn cam_border(&mut self, range: Range) {
        self.x = if self.x < range.x_min {
            range.x_min
        } else if self.x >= range.x_max {
            range.x_max - 1
        } else {
            self.x
        };
        self.y = if self.y < range.y_min {
            range.y_min
        } else if self.y >= range.y_max {
            range.y_max - 1
        } else {
            self.y
        };
    }

    /// Force the Coordinate to move without any checking
    pub fn force_move(&mut self, dx: i64, dy: i64) {
        self.x = (self.x as i64 + dx) as u64;
        self.y = (self.y as i64 + dy) as u64;
    }

    /// Move the coordinates and prevents leaving the level,
    /// or collide with other coordinates, except of the camera. Also checks, if
    /// field on new coordinate is passable
    pub fn move_coord_without_cam(&mut self,
                                  dx: i64,
                                  dy: i64,
                                  mut buf_x: u64,
                                  mut buf_y: u64,
                                  level: &mut Level) {
        // prevents leaving the the level if a buffer was given
        buf_x = if (level.get_width() as u64) < buf_x {
            level.get_width() as u64
        } else {
            buf_x
        };
        buf_y = if (level.get_height() as u64) < buf_y {
            level.get_height() as u64
        } else {
            buf_y
        };

        // checks leaving level
        let new_x = if (self.x as i64 + dx) < 0 {
            0
        } else {
            (self.x as i64 + dx) as u64
        };
        let new_y = if (self.y as i64 + dy) < 0 {
            0
        } else {
            (self.y as i64 + dy) as u64
        };

        /* player not at border */

        /* Check collision with unpassable fields, not with camera! (dx = dy = 0) */

        if dx != 0 || dy != 0 {
            let next_field =
                level.get_field_at((self.x as i64 + dx) as usize, (self.y as i64 + dy) as usize);
            if !next_field.check_passable() {
                return;
            }
        }
        /* Check end */

        if dx != 0 || dy != 0 {
            /* Update old position in field */
            level.get_data()[self.x as usize][self.y as usize].free_fieldstatus();
        }
        // sets coordinates after last checks
        self.x = if new_x < buf_x {
            buf_x
        } else if new_x > (level.get_width() as u64) - buf_x {
            level.get_width() as u64 - buf_x
        } else {
            new_x
        };
        self.y = if new_y < buf_y {
            buf_y
        } else if new_y > (level.get_height() as u64) - buf_y {
            level.get_height() as u64 - buf_y
        } else {
            new_y
        };
    }
}
<commit_msg>Repair Camera borders<commit_after>// Module to represent World coordinates for Player, Bots, Camera, etc.
use camera::Range;
use level::Level;

/// Struct to represent the world coordinates
#[derive(Copy, Clone, Debug)]
pub struct Coordinate {
    x: u64,
    y: u64,
}

impl Coordinate {
    /// Creates a Coordinate wth the given x and y-value
    pub fn new(x: u64, y: u64) -> Self {
        Coordinate { x: x, y: y }
    }

    /// Creates a Coordinate in the origin (0,0)
    pub fn origin() -> Self {
        Coordinate::new(0, 0)
    }

    /// Getter for the x-value in the coordinates
    pub fn get_x(&self) -> u64 {
        self.x
    }

    /// Getter for the y-value in the coordinates
    pub fn get_y(&self) -> u64 {
        self.y
    }

    /// Move the coordinates and prevents leaving the camera, leaving the level,
    /// or collide with other coordinates, except of the camera. Also checks, if
    /// field on new coordinate is passable
    pub fn move_coord_with_cam(&mut self, dx: i64, dy: i64, level: &mut Level, range: Range) {
        self.move_coord_without_cam(dx, dy, 0, 0, level);
        self.cam_border(range);
    }

    /// Sets the coordinate to the given new position (No checking)
    pub fn set_coord(&mut self, x: u64, y: u64) {
        self.x = x;
        self.y = y;
    }

    /// Sets the positon of the camera and prevents leaving Level
    fn cam_border(&mut self, range: Range) {
        self.x = if self.x < range.x_min {
            range.x_min
        } else if self.x >= range.x_max {
            range.x_max - 1
        } else {
            self.x
        };
        self.y = if self.y < range.y_min {
            range.y_min
        } else if self.y >= range.y_max {
            range.y_max - 1
        } else {
            self.y
        };
    }

    /// Force the Coordinate to move without any checking
    pub fn force_move(&mut self, dx: i64, dy: i64) {
        self.x = (self.x as i64 + dx) as u64;
        self.y = (self.y as i64 + dy) as u64;
    }

    /// Move the coordinates and prevents leaving the level,
    /// or collide with other coordinates, except of the camera. Also checks, if
    /// field on new coordinate is passable
    pub fn move_coord_without_cam(&mut self,
                                  dx: i64,
                                  dy: i64,
                                  mut buf_x: u64,
                                  mut buf_y: u64,
                                  level: &mut Level) {
        // prevents leaving the the level if a buffer was given
        buf_x = if (level.get_width() as u64) < buf_x {
            level.get_width() as u64
        } else {
            buf_x
        };
        buf_y = if (level.get_height() as u64) < buf_y {
            level.get_height() as u64
        } else {
            buf_y
        };

        // checks leaving level
        let new_x = if (self.x as i64 + dx) < 0 {
            0
        } else if (self.x as i64 + dx) as u64 >= level.get_width() as u64 {
            level.get_width() as u64
        } else {
            (self.x as i64 + dx) as u64
        };
        let new_y = if (self.y as i64 + dy) < 0 {
            0
        } else if (self.y as i64 + dy) as u64 >= level.get_height() as u64 {
            level.get_height() as u64
        } else {
            (self.y as i64 + dy) as u64
        };

        /* player not at border */

        /* Check collision with unpassable fields, not with camera! (dx = dy = 0) */

        if dx != 0 || dy != 0 {
            let next_field =
                level.get_field_at((self.x as i64 + dx) as usize, (self.y as i64 + dy) as usize);
            if !next_field.check_passable() {
                return;
            }
        }
        /* Check end */

        if dx != 0 || dy != 0 {
            /* Update old position in field */
            level.get_data()[self.x as usize][self.y as usize].free_fieldstatus();
        }
        // sets coordinates after last checks
        self.x = if new_x < buf_x {
            buf_x
        } else if new_x > (level.get_width() as u64) - buf_x - 1  {
            level.get_width() as u64 - buf_x - 1
        } else {
            new_x
        };
        self.y = if new_y < buf_y {
            buf_y
        } else if new_y > (level.get_height() as u64) - buf_y - 1 {
            level.get_height() as u64 - buf_y - 1
        } else {
            new_y
        };
    }
}
<|endoftext|>


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

use ::page;

/// modified from gkbrk's demo:
/// https://gist.github.com/gkbrk/bea6dee7c0478395b718

fn handle_client(mut stream: TcpStream) {
let mut reader = BufReader::new(stream.try_clone().unwrap());
    stream.write("220 urdict 0.1.0\r\n".as_bytes()).unwrap();
    loop {
        let mut line = String::new();
        let line_len = reader.read_line(&mut line).unwrap();
        if line_len > 0{
            println!("{}", line);
            let pieces: Vec<&str> = line.trim().split(" ").collect();
            match pieces[0] {
                "define" => {
                    let word = pieces[2].replace("\"", "");

                    if let Some(def) = page::find_on_urban_dict(&word) {
                        stream.write("250 ok\r\n".as_bytes()).unwrap();
                        stream.write(format!("150 {} definitions received\r\n", 1).as_bytes()).unwrap();

                        stream.write(format!("151 \"{}\"", def.word).as_bytes()).unwrap();
                        stream.write(format!(" \"Urban Dictionary {} {}\"\r\n", def.contributor, def.date).as_bytes()).unwrap();
                        stream.write(format!("{}\r\n.\r\n", def.def).as_bytes()).unwrap();

                        stream.write("250 ok\r\n".as_bytes()).unwrap();
                        println!("found {}", word);
                    } else {
                        //TODO
                    }
                },
                "quit" => {
                    stream.write("221 bye\r\n".as_bytes()).unwrap();
                    break;
                },
                _ => {
                    println!("{}", line.trim());
                }
            }
        }else{
            println!("Client disconnected");
            break;
        }
    }
}

pub fn start_server(host: &str, port: u16) {
    let listener = TcpListener::bind(&(host, port)).unwrap();
    for stream in listener.incoming() {
        match stream {
            Ok(stream) => {
                thread::spawn(move|| {
                    handle_client(stream);
                });
            },
            Err(e) => {
                println!("{}", e.description());
            }
        }
    }
}
<commit_msg>(fix) fixed 250 response<commit_after>use std::error::Error;
use std::io::{BufRead, Write};
use std::thread;
use std::net::{TcpListener, TcpStream};
use std::io::BufReader;

use ::page;

/// modified from gkbrk's demo:
/// https://gist.github.com/gkbrk/bea6dee7c0478395b718

fn handle_client(mut stream: TcpStream) {
let mut reader = BufReader::new(stream.try_clone().unwrap());
    stream.write("220 urdict 0.1.0\r\n".as_bytes()).unwrap();
    loop {
        let mut line = String::new();
        let line_len = reader.read_line(&mut line).unwrap();
        if line_len > 0{
            println!("{}", line);
            let pieces: Vec<&str> = line.trim().split(" ").collect();
            match pieces[0].to_lowercase().as_ref() {
                "define" => {
                    let word = pieces[2].replace("\"", "");
                    println!("{}", word);

                    if let Some(def) = page::find_on_urban_dict(&word) {
                        stream.write(format!("150 {} definitions retrieved\r\n", 1).as_bytes()).unwrap();

                        stream.write(format!("151 \"{}\" gcide", def.word).as_bytes()).unwrap();
                        stream.write(format!(" \"Urban Dictionary {} {}\"\r\n", def.contributor, def.date).as_bytes()).unwrap();
                        stream.write(format!("{}\r\n.\r\n", def.def).as_bytes()).unwrap();

                        stream.write("250 ok\r\n".as_bytes()).unwrap();
                        println!("found {}", word);
                    } else {
                        //TODO
                    }
                },
                "quit" => {
                    stream.write("221 bye\r\n".as_bytes()).unwrap();
                    break;
                },
                "client" => {
                    stream.write("250 ok\r\n".as_bytes()).unwrap();
                }
                _ => {
                    println!("{}", line.trim());
                }
            }
        }else{
            println!("Client disconnected");
            break;
        }
    }
}

pub fn start_server(host: &str, port: u16) {
    let listener = TcpListener::bind(&(host, port)).unwrap();
    for stream in listener.incoming() {
        match stream {
            Ok(stream) => {
                thread::spawn(move|| {
                    handle_client(stream);
                });
            },
            Err(e) => {
                println!("{}", e.description());
            }
        }
    }
}
<|endoftext|>


<commit_before>//! Methods for dumping serializable structs to a compressed binary format,
//! used to allow fast startup times
//!
//! Currently syntect serializes [`SyntaxSet`] structs with [`dump_to_file`]
//! into `.packdump` files and likewise [`ThemeSet`] structs to `.themedump` files.
//!
//! You can use these methods to manage your own caching of compiled syntaxes and
//! themes. And even your own `serde::Serialize` structures if you want to
//! be consistent with your format.
//!
//! [`SyntaxSet`]: ../parsing/struct.SyntaxSet.html
//! [`dump_to_file`]: fn.dump_to_file.html
//! [`ThemeSet`]: ../highlighting/struct.ThemeSet.html
use bincode::Result;
#[cfg(any(feature = "dump-load", feature = "dump-load-rs"))]
use bincode::deserialize_from;
#[cfg(any(feature = "dump-create", feature = "dump-create-rs"))]
use bincode::serialize_into;
use std::fs::File;
#[cfg(any(feature = "dump-load", feature = "dump-load-rs"))]
use std::io::{BufRead, BufReader};
#[cfg(any(feature = "dump-create", feature = "dump-create-rs"))]
use std::io::{BufWriter, Write};
#[cfg(all(feature = "parsing", feature = "assets", any(feature = "dump-load", feature = "dump-load-rs")))]
use crate::parsing::SyntaxSet;
#[cfg(all(feature = "assets", any(feature = "dump-load", feature = "dump-load-rs")))]
use crate::highlighting::ThemeSet;
use std::path::Path;
#[cfg(feature = "dump-create")]
use flate2::write::ZlibEncoder;
#[cfg(any(feature = "dump-load", feature = "dump-load-rs"))]
use flate2::bufread::ZlibDecoder;
#[cfg(any(feature = "dump-create", feature = "dump-create-rs"))]
use flate2::Compression;
#[cfg(any(feature = "dump-create", feature = "dump-create-rs"))]
use serde::Serialize;
#[cfg(any(feature = "dump-load", feature = "dump-load-rs"))]
use serde::de::DeserializeOwned;

/// Dumps an object to the given writer in a compressed binary format
///
/// The writer is encoded with the `bincode` crate and compressed with `flate2`.
#[cfg(any(feature = "dump-create", feature = "dump-create-rs"))]
pub fn dump_to_writer<T: Serialize, W: Write>(to_dump: &T, output: W) -> Result<()> {
    let mut encoder = ZlibEncoder::new(output, Compression::best());
    serialize_into(&mut encoder, to_dump)
}

/// Dumps an object to a binary array in the same format as [`dump_to_writer`]
///
/// [`dump_to_writer`]: fn.dump_to_writer.html
#[cfg(any(feature = "dump-create", feature = "dump-create-rs"))]
pub fn dump_binary<T: Serialize>(o: &T) -> Vec<u8> {
    let mut v = Vec::new();
    dump_to_writer(o, &mut v).unwrap();
    v
}

/// Dumps an encodable object to a file at a given path, in the same format as [`dump_to_writer`]
///
/// If a file already exists at that path it will be overwritten. The files created are encoded with
/// the `bincode` crate and then compressed with the `flate2` crate.
///
/// [`dump_to_writer`]: fn.dump_to_writer.html
#[cfg(any(feature = "dump-create", feature = "dump-create-rs"))]
pub fn dump_to_file<T: Serialize, P: AsRef<Path>>(o: &T, path: P) -> Result<()> {
    let out = BufWriter::new(File::create(path)?);
    dump_to_writer(o, out)
}

/// A helper function for decoding and decompressing data from a reader
#[cfg(any(feature = "dump-load", feature = "dump-load-rs"))]
pub fn from_reader<T: DeserializeOwned, R: BufRead>(input: R) -> Result<T> {
    let mut decoder = ZlibDecoder::new(input);
    deserialize_from(&mut decoder)
}

/// Returns a fully loaded syntax set from a binary dump.
///
/// This function panics if the dump is invalid.
#[cfg(any(feature = "dump-load", feature = "dump-load-rs"))]
pub fn from_binary<T: DeserializeOwned>(v: &[u8]) -> T {
    from_reader(v).unwrap()
}

/// Returns a fully loaded syntax set from a binary dump file.
#[cfg(any(feature = "dump-load", feature = "dump-load-rs"))]
pub fn from_dump_file<T: DeserializeOwned, P: AsRef<Path>>(path: P) -> Result<T> {
    let f = File::open(path)?;
    let reader = BufReader::new(f);
    from_reader(reader)
}

#[cfg(all(feature = "parsing", feature = "assets", any(feature = "dump-load", feature = "dump-load-rs")))]
impl SyntaxSet {
    /// Instantiates a new syntax set from a binary dump of Sublime Text's default open source
    /// syntax definitions.
    ///
    /// These dumps are included in this library's binary for convenience.
    ///
    /// This method loads the version for parsing line strings with no `\n` characters at the end.
    /// If you're able to efficiently include newlines at the end of strings, use
    /// [`load_defaults_newlines`] since it works better. See [`SyntaxSetBuilder::add_from_folder`]
    /// for more info on this issue.
    ///
    /// This is the recommended way of creating a syntax set for non-advanced use cases. It is also
    /// significantly faster than loading the YAML files.
    ///
    /// Note that you can load additional syntaxes after doing this. If you want you can even use
    /// the fact that SyntaxDefinitions are serializable with the bincode crate to cache dumps of
    /// additional syntaxes yourself.
    ///
    /// [`load_defaults_newlines`]: #method.load_defaults_nonewlines
    /// [`SyntaxSetBuilder::add_from_folder`]: struct.SyntaxSetBuilder.html#method.add_from_folder
    pub fn load_defaults_nonewlines() -> SyntaxSet {

        #[cfg(feature = "metadata")]
        {
            let mut ps: SyntaxSet = from_binary(include_bytes!("../assets/default_nonewlines.packdump"));
            let metadata = from_binary(include_bytes!("../assets/default_metadata.packdump"));
            ps.metadata = metadata;
            ps
        }
        #[cfg(not(feature = "metadata"))]
        {
            from_binary(include_bytes!("../assets/default_nonewlines.packdump"))
        }
    }

    /// Same as [`load_defaults_nonewlines`] but for parsing line strings with newlines at the end.
    ///
    /// These are separate methods because thanks to linker garbage collection, only the serialized
    /// dumps for the method(s) you call will be included in the binary (each is ~200kb for now).
    ///
    /// [`load_defaults_nonewlines`]: #method.load_defaults_nonewlines
    pub fn load_defaults_newlines() -> SyntaxSet {

        #[cfg(feature = "metadata")]
        {
            let mut ps: SyntaxSet = from_binary(include_bytes!("../assets/default_newlines.packdump"));
            let metadata = from_binary(include_bytes!("../assets/default_metadata.packdump"));
            ps.metadata = metadata;
            ps
        }
        #[cfg(not(feature = "metadata"))]
        {
            from_binary(include_bytes!("../assets/default_newlines.packdump"))
        }
    }
}

#[cfg(all(feature = "assets", any(feature = "dump-load", feature = "dump-load-rs")))]
impl ThemeSet {
    /// Loads the set of default themes
    /// Currently includes (these are the keys for the map):
    ///
    /// - `base16-ocean.dark`,`base16-eighties.dark`,`base16-mocha.dark`,`base16-ocean.light`
    /// - `InspiredGitHub` from [here](https://github.com/sethlopezme/InspiredGitHub.tmtheme)
    /// - `Solarized (dark)` and `Solarized (light)`
    pub fn load_defaults() -> ThemeSet {
        from_binary(include_bytes!("../assets/default.themedump"))
    }
}

#[cfg(test)]
mod tests {
    #[cfg(all(feature = "yaml-load", any(feature = "dump-create", feature = "dump-create-rs"), any(feature = "dump-load", feature = "dump-load-rs")))]
    #[test]
    fn can_dump_and_load() {
        use super::*;
        use crate::parsing::SyntaxSetBuilder;
        let mut builder = SyntaxSetBuilder::new();
        builder.add_from_folder("testdata/Packages", false).unwrap();
        let ss = builder.build();

        let bin = dump_binary(&ss);
        println!("{:?}", bin.len());
        let ss2: SyntaxSet = from_binary(&bin[..]);
        assert_eq!(ss.syntaxes().len(), ss2.syntaxes().len());
    }

    #[cfg(all(feature = "yaml-load", any(feature = "dump-create", feature = "dump-create-rs"), any(feature = "dump-load", feature = "dump-load-rs")))]
    #[test]
    fn dump_is_deterministic() {
        use super::*;
        use crate::parsing::SyntaxSetBuilder;

        let mut builder1 = SyntaxSetBuilder::new();
        builder1.add_from_folder("testdata/Packages", false).unwrap();
        let ss1 = builder1.build();
        let bin1 = dump_binary(&ss1);

        let mut builder2 = SyntaxSetBuilder::new();
        builder2.add_from_folder("testdata/Packages", false).unwrap();
        let ss2 = builder2.build();
        let bin2 = dump_binary(&ss2);
        // This is redundant, but assert_eq! can be really slow on a large
        // vector, so check the length first to fail faster.
        assert_eq!(bin1.len(), bin2.len());
        assert_eq!(bin1, bin2);
    }

    #[cfg(all(feature = "assets", any(feature = "dump-load", feature = "dump-load-rs")))]
    #[test]
    fn has_default_themes() {
        use crate::highlighting::ThemeSet;
        let themes = ThemeSet::load_defaults();
        assert!(themes.themes.len() > 4);
    }
}
<commit_msg>Make from_dump_file() ~15% faster<commit_after>//! Methods for dumping serializable structs to a compressed binary format,
//! used to allow fast startup times
//!
//! Currently syntect serializes [`SyntaxSet`] structs with [`dump_to_file`]
//! into `.packdump` files and likewise [`ThemeSet`] structs to `.themedump` files.
//!
//! You can use these methods to manage your own caching of compiled syntaxes and
//! themes. And even your own `serde::Serialize` structures if you want to
//! be consistent with your format.
//!
//! [`SyntaxSet`]: ../parsing/struct.SyntaxSet.html
//! [`dump_to_file`]: fn.dump_to_file.html
//! [`ThemeSet`]: ../highlighting/struct.ThemeSet.html
use bincode::Result;
#[cfg(any(feature = "dump-load", feature = "dump-load-rs"))]
use bincode::deserialize_from;
#[cfg(any(feature = "dump-create", feature = "dump-create-rs"))]
use bincode::serialize_into;
use std::fs::File;
#[cfg(any(feature = "dump-load", feature = "dump-load-rs"))]
use std::io::{BufRead};
#[cfg(any(feature = "dump-create", feature = "dump-create-rs"))]
use std::io::{BufWriter, Write};
#[cfg(all(feature = "parsing", feature = "assets", any(feature = "dump-load", feature = "dump-load-rs")))]
use crate::parsing::SyntaxSet;
#[cfg(all(feature = "assets", any(feature = "dump-load", feature = "dump-load-rs")))]
use crate::highlighting::ThemeSet;
use std::path::Path;
#[cfg(feature = "dump-create")]
use flate2::write::ZlibEncoder;
#[cfg(any(feature = "dump-load", feature = "dump-load-rs"))]
use flate2::bufread::ZlibDecoder;
#[cfg(any(feature = "dump-create", feature = "dump-create-rs"))]
use flate2::Compression;
#[cfg(any(feature = "dump-create", feature = "dump-create-rs"))]
use serde::Serialize;
#[cfg(any(feature = "dump-load", feature = "dump-load-rs"))]
use serde::de::DeserializeOwned;

/// Dumps an object to the given writer in a compressed binary format
///
/// The writer is encoded with the `bincode` crate and compressed with `flate2`.
#[cfg(any(feature = "dump-create", feature = "dump-create-rs"))]
pub fn dump_to_writer<T: Serialize, W: Write>(to_dump: &T, output: W) -> Result<()> {
    let mut encoder = ZlibEncoder::new(output, Compression::best());
    serialize_into(&mut encoder, to_dump)
}

/// Dumps an object to a binary array in the same format as [`dump_to_writer`]
///
/// [`dump_to_writer`]: fn.dump_to_writer.html
#[cfg(any(feature = "dump-create", feature = "dump-create-rs"))]
pub fn dump_binary<T: Serialize>(o: &T) -> Vec<u8> {
    let mut v = Vec::new();
    dump_to_writer(o, &mut v).unwrap();
    v
}

/// Dumps an encodable object to a file at a given path, in the same format as [`dump_to_writer`]
///
/// If a file already exists at that path it will be overwritten. The files created are encoded with
/// the `bincode` crate and then compressed with the `flate2` crate.
///
/// [`dump_to_writer`]: fn.dump_to_writer.html
#[cfg(any(feature = "dump-create", feature = "dump-create-rs"))]
pub fn dump_to_file<T: Serialize, P: AsRef<Path>>(o: &T, path: P) -> Result<()> {
    let out = BufWriter::new(File::create(path)?);
    dump_to_writer(o, out)
}

/// A helper function for decoding and decompressing data from a reader
#[cfg(any(feature = "dump-load", feature = "dump-load-rs"))]
pub fn from_reader<T: DeserializeOwned, R: BufRead>(input: R) -> Result<T> {
    let mut decoder = ZlibDecoder::new(input);
    deserialize_from(&mut decoder)
}

/// Returns a fully loaded syntax set from a binary dump.
///
/// This function panics if the dump is invalid.
#[cfg(any(feature = "dump-load", feature = "dump-load-rs"))]
pub fn from_binary<T: DeserializeOwned>(v: &[u8]) -> T {
    from_reader(v).unwrap()
}

/// Returns a fully loaded syntax set from a binary dump file.
#[cfg(any(feature = "dump-load", feature = "dump-load-rs"))]
pub fn from_dump_file<T: DeserializeOwned, P: AsRef<Path>>(path: P) -> Result<T> {
    let contents = std::fs::read(path)?;
    from_reader(&contents[..])
}

#[cfg(all(feature = "parsing", feature = "assets", any(feature = "dump-load", feature = "dump-load-rs")))]
impl SyntaxSet {
    /// Instantiates a new syntax set from a binary dump of Sublime Text's default open source
    /// syntax definitions.
    ///
    /// These dumps are included in this library's binary for convenience.
    ///
    /// This method loads the version for parsing line strings with no `\n` characters at the end.
    /// If you're able to efficiently include newlines at the end of strings, use
    /// [`load_defaults_newlines`] since it works better. See [`SyntaxSetBuilder::add_from_folder`]
    /// for more info on this issue.
    ///
    /// This is the recommended way of creating a syntax set for non-advanced use cases. It is also
    /// significantly faster than loading the YAML files.
    ///
    /// Note that you can load additional syntaxes after doing this. If you want you can even use
    /// the fact that SyntaxDefinitions are serializable with the bincode crate to cache dumps of
    /// additional syntaxes yourself.
    ///
    /// [`load_defaults_newlines`]: #method.load_defaults_nonewlines
    /// [`SyntaxSetBuilder::add_from_folder`]: struct.SyntaxSetBuilder.html#method.add_from_folder
    pub fn load_defaults_nonewlines() -> SyntaxSet {

        #[cfg(feature = "metadata")]
        {
            let mut ps: SyntaxSet = from_binary(include_bytes!("../assets/default_nonewlines.packdump"));
            let metadata = from_binary(include_bytes!("../assets/default_metadata.packdump"));
            ps.metadata = metadata;
            ps
        }
        #[cfg(not(feature = "metadata"))]
        {
            from_binary(include_bytes!("../assets/default_nonewlines.packdump"))
        }
    }

    /// Same as [`load_defaults_nonewlines`] but for parsing line strings with newlines at the end.
    ///
    /// These are separate methods because thanks to linker garbage collection, only the serialized
    /// dumps for the method(s) you call will be included in the binary (each is ~200kb for now).
    ///
    /// [`load_defaults_nonewlines`]: #method.load_defaults_nonewlines
    pub fn load_defaults_newlines() -> SyntaxSet {

        #[cfg(feature = "metadata")]
        {
            let mut ps: SyntaxSet = from_binary(include_bytes!("../assets/default_newlines.packdump"));
            let metadata = from_binary(include_bytes!("../assets/default_metadata.packdump"));
            ps.metadata = metadata;
            ps
        }
        #[cfg(not(feature = "metadata"))]
        {
            from_binary(include_bytes!("../assets/default_newlines.packdump"))
        }
    }
}

#[cfg(all(feature = "assets", any(feature = "dump-load", feature = "dump-load-rs")))]
impl ThemeSet {
    /// Loads the set of default themes
    /// Currently includes (these are the keys for the map):
    ///
    /// - `base16-ocean.dark`,`base16-eighties.dark`,`base16-mocha.dark`,`base16-ocean.light`
    /// - `InspiredGitHub` from [here](https://github.com/sethlopezme/InspiredGitHub.tmtheme)
    /// - `Solarized (dark)` and `Solarized (light)`
    pub fn load_defaults() -> ThemeSet {
        from_binary(include_bytes!("../assets/default.themedump"))
    }
}

#[cfg(test)]
mod tests {
    #[cfg(all(feature = "yaml-load", any(feature = "dump-create", feature = "dump-create-rs"), any(feature = "dump-load", feature = "dump-load-rs")))]
    #[test]
    fn can_dump_and_load() {
        use super::*;
        use crate::parsing::SyntaxSetBuilder;
        let mut builder = SyntaxSetBuilder::new();
        builder.add_from_folder("testdata/Packages", false).unwrap();
        let ss = builder.build();

        let bin = dump_binary(&ss);
        println!("{:?}", bin.len());
        let ss2: SyntaxSet = from_binary(&bin[..]);
        assert_eq!(ss.syntaxes().len(), ss2.syntaxes().len());
    }

    #[cfg(all(feature = "yaml-load", any(feature = "dump-create", feature = "dump-create-rs"), any(feature = "dump-load", feature = "dump-load-rs")))]
    #[test]
    fn dump_is_deterministic() {
        use super::*;
        use crate::parsing::SyntaxSetBuilder;

        let mut builder1 = SyntaxSetBuilder::new();
        builder1.add_from_folder("testdata/Packages", false).unwrap();
        let ss1 = builder1.build();
        let bin1 = dump_binary(&ss1);

        let mut builder2 = SyntaxSetBuilder::new();
        builder2.add_from_folder("testdata/Packages", false).unwrap();
        let ss2 = builder2.build();
        let bin2 = dump_binary(&ss2);
        // This is redundant, but assert_eq! can be really slow on a large
        // vector, so check the length first to fail faster.
        assert_eq!(bin1.len(), bin2.len());
        assert_eq!(bin1, bin2);
    }

    #[cfg(all(feature = "assets", any(feature = "dump-load", feature = "dump-load-rs")))]
    #[test]
    fn has_default_themes() {
        use crate::highlighting::ThemeSet;
        let themes = ThemeSet::load_defaults();
        assert!(themes.themes.len() > 4);
    }
}
<|endoftext|>