<commit_before>//! Tidy check to ensure that there are no stray `.stderr` files in UI test directories.

use std::fs;
use std::path::Path;

pub fn check(path: &Path, bad: &mut bool) {
    for path in &[&path.join("test/ui"), &path.join("test/ui-fulldeps")] {
        super::walk_no_read(path, &mut |_| false, &mut |entry| {
            let file_path = entry.path();
            if let Some(ext) = file_path.extension() {
                if ext == "stderr" || ext == "stdout" {
                    // Test output filenames have one of the formats:
                    // ```
                    // $testname.stderr
                    // $testname.$mode.stderr
                    // $testname.$revision.stderr
                    // $testname.$revision.$mode.stderr
                    // ```
                    //
                    // For now, just make sure that there is a corresponding
                    // `$testname.rs` file.
                    //
                    // NB: We do not use file_stem() as some file names have multiple `.`s and we
                    // must strip all of them.
                    let testname =
                        file_path.file_name().unwrap().to_str().unwrap().split_once('.').unwrap().0;
                    if !file_path.with_file_name(testname).with_extension("rs").exists() {
                        println!("Stray file with UI testing output: {:?}", file_path);
                        *bad = true;
                    }

                    if let Ok(metadata) = fs::metadata(file_path) {
                        if metadata.len() == 0 {
                            println!("Empty file with UI testing output: {:?}", file_path);
                            *bad = true;
                        }
                    }
                }
            }
        });
    }
}
<commit_msg>Auto merge of #79959 - JohnTitor:tidy-entries, r=petrochenkov<commit_after>//! Tidy check to ensure below in UI test directories:
//! - the number of entries in each directory must be less than `ENTRY_LIMIT`
//! - there are no stray `.stderr` files

use std::fs;
use std::path::Path;

const ENTRY_LIMIT: usize = 1000;
// FIXME: The following limits should be reduced eventually.
const ROOT_ENTRY_LIMIT: usize = 1580;
const ISSUES_ENTRY_LIMIT: usize = 2830;

fn check_entries(path: &Path, bad: &mut bool) {
    let dirs = walkdir::WalkDir::new(&path.join("test/ui"))
        .into_iter()
        .filter_entry(|e| e.file_type().is_dir());
    for dir in dirs {
        if let Ok(dir) = dir {
            let dir_path = dir.path();

            // Use special values for these dirs.
            let is_root = path.join("test/ui") == dir_path;
            let is_issues_dir = path.join("test/ui/issues") == dir_path;
            let limit = if is_root {
                ROOT_ENTRY_LIMIT
            } else if is_issues_dir {
                ISSUES_ENTRY_LIMIT
            } else {
                ENTRY_LIMIT
            };

            let count = std::fs::read_dir(dir_path).unwrap().count();
            if count >= limit {
                tidy_error!(
                    bad,
                    "following path contains more than {} entries, \
                    you should move the test to some relevant subdirectory (current: {}): {}",
                    limit,
                    count,
                    dir_path.display()
                );
            }
        }
    }
}

pub fn check(path: &Path, bad: &mut bool) {
    check_entries(&path, bad);
    for path in &[&path.join("test/ui"), &path.join("test/ui-fulldeps")] {
        super::walk_no_read(path, &mut |_| false, &mut |entry| {
            let file_path = entry.path();
            if let Some(ext) = file_path.extension() {
                if ext == "stderr" || ext == "stdout" {
                    // Test output filenames have one of the formats:
                    // ```
                    // $testname.stderr
                    // $testname.$mode.stderr
                    // $testname.$revision.stderr
                    // $testname.$revision.$mode.stderr
                    // ```
                    //
                    // For now, just make sure that there is a corresponding
                    // `$testname.rs` file.
                    //
                    // NB: We do not use file_stem() as some file names have multiple `.`s and we
                    // must strip all of them.
                    let testname =
                        file_path.file_name().unwrap().to_str().unwrap().split_once('.').unwrap().0;
                    if !file_path.with_file_name(testname).with_extension("rs").exists() {
                        println!("Stray file with UI testing output: {:?}", file_path);
                        *bad = true;
                    }

                    if let Ok(metadata) = fs::metadata(file_path) {
                        if metadata.len() == 0 {
                            println!("Empty file with UI testing output: {:?}", file_path);
                            *bad = true;
                        }
                    }
                }
            }
        });
    }
}
<|endoftext|>


<commit_before>use wayland_sys::server::wl_display as wl_server_display;
use wlroots_sys::{wl_display, wlr_server_decoration_manager, wlr_server_decoration_manager_create,
                  wlr_server_decoration_manager_destroy,
                  wlr_server_decoration_manager_set_default_mode};
use wlroots_sys::protocols::server_decoration::server::org_kde_kwin_server_decoration_manager::Mode
as ServerDecorationMode;

#[derive(Debug)]
pub struct ServerDecorationManager {
    manager: *mut wlr_server_decoration_manager
}

impl ServerDecorationManager {
    pub(crate) unsafe fn new(display: *mut wl_server_display) -> Option<Self> {
        let manager_raw = wlr_server_decoration_manager_create(display as *mut wl_display);

        if !manager_raw.is_null() {
            Some(ServerDecorationManager { manager: manager_raw })
        } else {
            None
        }
    }

    pub fn set_default_mode(&mut self, mode: ServerDecorationMode) {
        wlr_log!(L_INFO, "New server decoration mode: {:?}", mode);
        unsafe { wlr_server_decoration_manager_set_default_mode(self.manager, mode.to_raw()) }
    }
}

impl Drop for ServerDecorationManager {
    fn drop(&mut self) {
        unsafe { wlr_server_decoration_manager_destroy(self.manager) }
    }
}
<commit_msg>Fixed private ServerDecorationMode<commit_after>use wayland_sys::server::wl_display as wl_server_display;
use wlroots_sys::{wl_display, wlr_server_decoration_manager, wlr_server_decoration_manager_create,
                  wlr_server_decoration_manager_destroy,
                  wlr_server_decoration_manager_set_default_mode};
pub use wlroots_sys::protocols::server_decoration
::server::org_kde_kwin_server_decoration_manager::Mode
as ServerDecorationMode;

#[derive(Debug)]
pub struct ServerDecorationManager {
    manager: *mut wlr_server_decoration_manager
}

impl ServerDecorationManager {
    pub(crate) unsafe fn new(display: *mut wl_server_display) -> Option<Self> {
        let manager_raw = wlr_server_decoration_manager_create(display as *mut wl_display);

        if !manager_raw.is_null() {
            Some(ServerDecorationManager { manager: manager_raw })
        } else {
            None
        }
    }

    pub fn set_default_mode(&mut self, mode: ServerDecorationMode) {
        wlr_log!(L_INFO, "New server decoration mode: {:?}", mode);
        unsafe { wlr_server_decoration_manager_set_default_mode(self.manager, mode.to_raw()) }
    }
}

impl Drop for ServerDecorationManager {
    fn drop(&mut self) {
        unsafe { wlr_server_decoration_manager_destroy(self.manager) }
    }
}
<|endoftext|>


<commit_before>use std::io::stdin;
use std::convert::AsRef;

fn main() {

	let mut x = stdin();

	loop{
		let y: &mut String = &mut "".to_string();
		let _ = x.read_line(y);

	    println!("Hello, world! {}", match y.as_ref(){
	    	"+" => "addition!",
	    	"-" => "subtraction!",
	    	_ => "other!",
	    });
	}
}
<commit_msg>matching chars<commit_after>use std::io::stdin;

fn main() {

	let mut x = stdin();

	loop{
		let mut y: String = "".to_string();
		let _ = x.read_line(&mut y);

		let z = y.chars().next();
	    println!("Hello, world! {}", match z{
	    	Some(b) => match b{
	    		'+' => "addition!",
	    		_ => "other!",
	    	},
	    	None => "none!",
	    });
	}
}
<|endoftext|>


<commit_before>//! Host header validation.

use crate::matcher::{Matcher, Pattern};
use std::collections::HashSet;
use std::net::SocketAddr;

const SPLIT_PROOF: &str = "split always returns non-empty iterator.";

/// Port pattern
#[derive(Clone, Hash, PartialEq, Eq, Debug)]
pub enum Port {
	/// No port specified (default port)
	None,
	/// Port specified as a wildcard pattern
	Pattern(String),
	/// Fixed numeric port
	Fixed(u16),
}

impl From<Option<u16>> for Port {
	fn from(opt: Option<u16>) -> Self {
		match opt {
			Some(port) => Port::Fixed(port),
			None => Port::None,
		}
	}
}

impl From<u16> for Port {
	fn from(port: u16) -> Port {
		Port::Fixed(port)
	}
}

/// Host type
#[derive(Clone, Hash, PartialEq, Eq, Debug)]
pub struct Host {
	hostname: String,
	port: Port,
	as_string: String,
	matcher: Matcher,
}

impl<T: AsRef<str>> From<T> for Host {
	fn from(string: T) -> Self {
		Host::parse(string.as_ref())
	}
}

impl Host {
	/// Creates a new `Host` given hostname and port number.
	pub fn new<T: Into<Port>>(hostname: &str, port: T) -> Self {
		let port = port.into();
		let hostname = Self::pre_process(hostname);
		let string = Self::to_string(&hostname, &port);
		let matcher = Matcher::new(&string);

		Host {
			hostname,
			port,
			as_string: string,
			matcher,
		}
	}

	/// Attempts to parse given string as a `Host`.
	/// NOTE: This method always succeeds and falls back to sensible defaults.
	pub fn parse(hostname: &str) -> Self {
		let hostname = Self::pre_process(hostname);
		let mut hostname = hostname.split(':');
		let host = hostname.next().expect(SPLIT_PROOF);
		let port = match hostname.next() {
			None => Port::None,
			Some(port) => match port.parse::<u16>().ok() {
				Some(num) => Port::Fixed(num),
				None => Port::Pattern(port.into()),
			},
		};

		Host::new(host, port)
	}

	fn pre_process(host: &str) -> String {
		// Remove possible protocol definition
		let mut it = host.split("://");
		let protocol = it.next().expect(SPLIT_PROOF);
		let host = match it.next() {
			Some(data) => data,
			None => protocol,
		};

		let mut it = host.split('/');
		it.next().expect(SPLIT_PROOF).to_lowercase()
	}

	fn to_string(hostname: &str, port: &Port) -> String {
		format!(
			"{}{}",
			hostname,
			match *port {
				Port::Fixed(port) => format!(":{}", port),
				Port::Pattern(ref port) => format!(":{}", port),
				Port::None => "".into(),
			},
		)
	}
}

impl Pattern for Host {
	fn matches<T: AsRef<str>>(&self, other: T) -> bool {
		self.matcher.matches(other)
	}
}

impl ::std::ops::Deref for Host {
	type Target = str;
	fn deref(&self) -> &Self::Target {
		&self.as_string
	}
}

/// Specifies if domains should be validated.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum DomainsValidation<T> {
	/// Allow only domains on the list.
	AllowOnly(Vec<T>),
	/// Disable domains validation completely.
	Disabled,
}

impl<T> Into<Option<Vec<T>>> for DomainsValidation<T> {
	fn into(self) -> Option<Vec<T>> {
		use self::DomainsValidation::*;
		match self {
			AllowOnly(list) => Some(list),
			Disabled => None,
		}
	}
}

impl<T> From<Option<Vec<T>>> for DomainsValidation<T> {
	fn from(other: Option<Vec<T>>) -> Self {
		match other {
			Some(list) => DomainsValidation::AllowOnly(list),
			None => DomainsValidation::Disabled,
		}
	}
}

/// Returns `true` when `Host` header is whitelisted in `allowed_hosts`.
pub fn is_host_valid(host: Option<&str>, allowed_hosts: &Option<Vec<Host>>) -> bool {
	match allowed_hosts.as_ref() {
		None => true,
		Some(ref allowed_hosts) => match host {
			None => false,
			Some(ref host) => allowed_hosts.iter().any(|h| h.matches(host)),
		},
	}
}

/// Updates given list of hosts with the address.
pub fn update(hosts: Option<Vec<Host>>, address: &SocketAddr) -> Option<Vec<Host>> {
	hosts.map(|current_hosts| {
		let mut new_hosts = current_hosts.into_iter().collect::<HashSet<_>>();
		let address = address.to_string();
		new_hosts.insert(address.clone().into());
		new_hosts.insert(address.replace("127.0.0.1", "localhost").into());
		new_hosts.into_iter().collect()
	})
}

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

	#[test]
	fn should_parse_host() {
		assert_eq!(Host::parse("http://parity.io"), Host::new("parity.io", None));
		assert_eq!(
			Host::parse("https://parity.io:8443"),
			Host::new("parity.io", Some(8443))
		);
		assert_eq!(
			Host::parse("chrome-extension://124.0.0.1"),
			Host::new("124.0.0.1", None)
		);
		assert_eq!(Host::parse("parity.io/somepath"), Host::new("parity.io", None));
		assert_eq!(
			Host::parse("127.0.0.1:8545/somepath"),
			Host::new("127.0.0.1", Some(8545))
		);
	}

	#[test]
	fn should_reject_when_there_is_no_header() {
		let valid = is_host_valid(None, &Some(vec![]));
		assert_eq!(valid, false);
	}

	#[test]
	fn should_reject_when_validation_is_disabled() {
		let valid = is_host_valid(Some("any"), &None);
		assert_eq!(valid, true);
	}

	#[test]
	fn should_reject_if_header_not_on_the_list() {
		let valid = is_host_valid(Some("parity.io"), &Some(vec![]));
		assert_eq!(valid, false);
	}

	#[test]
	fn should_accept_if_on_the_list() {
		let valid = is_host_valid(Some("parity.io"), &Some(vec!["parity.io".into()]));
		assert_eq!(valid, true);
	}

	#[test]
	fn should_accept_if_on_the_list_with_port() {
		let valid = is_host_valid(Some("parity.io:443"), &Some(vec!["parity.io:443".into()]));
		assert_eq!(valid, true);
	}

	#[test]
	fn should_support_wildcards() {
		let valid = is_host_valid(Some("parity.web3.site:8180"), &Some(vec!["*.web3.site:*".into()]));
		assert_eq!(valid, true);
	}
}
<commit_msg>hosts: when binding to unspecified address allow requests from localhost (#549)<commit_after>//! Host header validation.

use crate::matcher::{Matcher, Pattern};
use std::collections::HashSet;
use std::net::SocketAddr;

const SPLIT_PROOF: &str = "split always returns non-empty iterator.";

/// Port pattern
#[derive(Clone, Hash, PartialEq, Eq, Debug)]
pub enum Port {
	/// No port specified (default port)
	None,
	/// Port specified as a wildcard pattern
	Pattern(String),
	/// Fixed numeric port
	Fixed(u16),
}

impl From<Option<u16>> for Port {
	fn from(opt: Option<u16>) -> Self {
		match opt {
			Some(port) => Port::Fixed(port),
			None => Port::None,
		}
	}
}

impl From<u16> for Port {
	fn from(port: u16) -> Port {
		Port::Fixed(port)
	}
}

/// Host type
#[derive(Clone, Hash, PartialEq, Eq, Debug)]
pub struct Host {
	hostname: String,
	port: Port,
	as_string: String,
	matcher: Matcher,
}

impl<T: AsRef<str>> From<T> for Host {
	fn from(string: T) -> Self {
		Host::parse(string.as_ref())
	}
}

impl Host {
	/// Creates a new `Host` given hostname and port number.
	pub fn new<T: Into<Port>>(hostname: &str, port: T) -> Self {
		let port = port.into();
		let hostname = Self::pre_process(hostname);
		let string = Self::to_string(&hostname, &port);
		let matcher = Matcher::new(&string);

		Host {
			hostname,
			port,
			as_string: string,
			matcher,
		}
	}

	/// Attempts to parse given string as a `Host`.
	/// NOTE: This method always succeeds and falls back to sensible defaults.
	pub fn parse(hostname: &str) -> Self {
		let hostname = Self::pre_process(hostname);
		let mut hostname = hostname.split(':');
		let host = hostname.next().expect(SPLIT_PROOF);
		let port = match hostname.next() {
			None => Port::None,
			Some(port) => match port.parse::<u16>().ok() {
				Some(num) => Port::Fixed(num),
				None => Port::Pattern(port.into()),
			},
		};

		Host::new(host, port)
	}

	fn pre_process(host: &str) -> String {
		// Remove possible protocol definition
		let mut it = host.split("://");
		let protocol = it.next().expect(SPLIT_PROOF);
		let host = match it.next() {
			Some(data) => data,
			None => protocol,
		};

		let mut it = host.split('/');
		it.next().expect(SPLIT_PROOF).to_lowercase()
	}

	fn to_string(hostname: &str, port: &Port) -> String {
		format!(
			"{}{}",
			hostname,
			match *port {
				Port::Fixed(port) => format!(":{}", port),
				Port::Pattern(ref port) => format!(":{}", port),
				Port::None => "".into(),
			},
		)
	}
}

impl Pattern for Host {
	fn matches<T: AsRef<str>>(&self, other: T) -> bool {
		self.matcher.matches(other)
	}
}

impl ::std::ops::Deref for Host {
	type Target = str;
	fn deref(&self) -> &Self::Target {
		&self.as_string
	}
}

/// Specifies if domains should be validated.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum DomainsValidation<T> {
	/// Allow only domains on the list.
	AllowOnly(Vec<T>),
	/// Disable domains validation completely.
	Disabled,
}

impl<T> Into<Option<Vec<T>>> for DomainsValidation<T> {
	fn into(self) -> Option<Vec<T>> {
		use self::DomainsValidation::*;
		match self {
			AllowOnly(list) => Some(list),
			Disabled => None,
		}
	}
}

impl<T> From<Option<Vec<T>>> for DomainsValidation<T> {
	fn from(other: Option<Vec<T>>) -> Self {
		match other {
			Some(list) => DomainsValidation::AllowOnly(list),
			None => DomainsValidation::Disabled,
		}
	}
}

/// Returns `true` when `Host` header is whitelisted in `allowed_hosts`.
pub fn is_host_valid(host: Option<&str>, allowed_hosts: &Option<Vec<Host>>) -> bool {
	match allowed_hosts.as_ref() {
		None => true,
		Some(ref allowed_hosts) => match host {
			None => false,
			Some(ref host) => allowed_hosts.iter().any(|h| h.matches(host)),
		},
	}
}

/// Updates given list of hosts with the address.
pub fn update(hosts: Option<Vec<Host>>, address: &SocketAddr) -> Option<Vec<Host>> {
	use std::net::{IpAddr, Ipv4Addr};

	hosts.map(|current_hosts| {
		let mut new_hosts = current_hosts.into_iter().collect::<HashSet<_>>();
		let address_string = address.to_string();

		if address.ip() == IpAddr::V4(Ipv4Addr::UNSPECIFIED) {
			new_hosts.insert(address_string.replace("0.0.0.0", "127.0.0.1").into());
			new_hosts.insert(address_string.replace("0.0.0.0", "localhost").into());
		} else if address.ip() == IpAddr::V4(Ipv4Addr::LOCALHOST) {
			new_hosts.insert(address_string.replace("127.0.0.1", "localhost").into());
		}

		new_hosts.insert(address_string.into());
		new_hosts.into_iter().collect()
	})
}

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

	#[test]
	fn should_parse_host() {
		assert_eq!(Host::parse("http://parity.io"), Host::new("parity.io", None));
		assert_eq!(
			Host::parse("https://parity.io:8443"),
			Host::new("parity.io", Some(8443))
		);
		assert_eq!(
			Host::parse("chrome-extension://124.0.0.1"),
			Host::new("124.0.0.1", None)
		);
		assert_eq!(Host::parse("parity.io/somepath"), Host::new("parity.io", None));
		assert_eq!(
			Host::parse("127.0.0.1:8545/somepath"),
			Host::new("127.0.0.1", Some(8545))
		);
	}

	#[test]
	fn should_reject_when_there_is_no_header() {
		let valid = is_host_valid(None, &Some(vec![]));
		assert_eq!(valid, false);
	}

	#[test]
	fn should_reject_when_validation_is_disabled() {
		let valid = is_host_valid(Some("any"), &None);
		assert_eq!(valid, true);
	}

	#[test]
	fn should_reject_if_header_not_on_the_list() {
		let valid = is_host_valid(Some("parity.io"), &Some(vec![]));
		assert_eq!(valid, false);
	}

	#[test]
	fn should_accept_if_on_the_list() {
		let valid = is_host_valid(Some("parity.io"), &Some(vec!["parity.io".into()]));
		assert_eq!(valid, true);
	}

	#[test]
	fn should_accept_if_on_the_list_with_port() {
		let valid = is_host_valid(Some("parity.io:443"), &Some(vec!["parity.io:443".into()]));
		assert_eq!(valid, true);
	}

	#[test]
	fn should_support_wildcards() {
		let valid = is_host_valid(Some("parity.web3.site:8180"), &Some(vec!["*.web3.site:*".into()]));
		assert_eq!(valid, true);
	}
}
<|endoftext|>


<commit_before>// Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0

use crate::shared::{get_shuffle_dir, send, MAIN_PKG_PATH};
use anyhow::{anyhow, Result};
use diem_crypto::PrivateKey;
use diem_sdk::{
    client::BlockingClient,
    transaction_builder::TransactionFactory,
    types::{
        transaction::{Module, TransactionPayload},
        LocalAccount,
    },
};
use diem_types::{
    account_state::AccountState, account_state_blob::AccountStateBlob, chain_id::ChainId,
    transaction::authenticator::AuthenticationKey,
};
use generate_key::load_key;
use move_binary_format::{file_format::CompiledModule, normalized};
use move_lang::compiled_unit::{CompiledUnit, NamedCompiledModule};
use move_package::compilation::compiled_package::CompiledPackage;
use std::{collections::HashSet, convert::TryFrom, path::Path};

/// Deploys shuffle's main Move Package to the sender's address.
pub fn handle(project_path: &Path) -> Result<()> {
    let account_key_path = get_shuffle_dir()
        .join("accounts")
        .join("latest")
        .join("dev.key");
    if !account_key_path.exists() {
        return Err(anyhow!(
            "An account hasn't been created yet! Run shuffle account first."
        ));
    }
    let compiled_package = build_move_packages(project_path)?;
    publish_packages_as_transaction(&account_key_path, compiled_package)
}

/// Builds the packages in the shuffle project using the move package system.
fn build_move_packages(project_path: &Path) -> Result<CompiledPackage> {
    println!("Building Examples...");
    let pkgdir = project_path.join(MAIN_PKG_PATH);
    let config = move_package::BuildConfig {
        dev_mode: true,
        test_mode: false,
        generate_docs: false,
        generate_abis: true,
    };

    config.compile_package(pkgdir.as_path(), &mut std::io::stdout())
}

fn publish_packages_as_transaction(
    account_key_path: &Path,
    compiled_package: CompiledPackage,
) -> Result<()> {
    let new_account_key = load_key(account_key_path);
    let json_rpc_url = format!("http://0.0.0.0:{}", 8080); // TODO: Hardcoded to local devnet
    let factory = TransactionFactory::new(ChainId::test());
    println!("Connecting to {}", json_rpc_url);

    let client = BlockingClient::new(json_rpc_url);

    println!("Using Public Key {}", &new_account_key.public_key());
    let derived_address =
        AuthenticationKey::ed25519(&new_account_key.public_key()).derived_address();
    println!(
        "Sending txn from address {}",
        derived_address.to_hex_literal()
    );

    // ================= Send a module transaction ========================

    let mut new_account = LocalAccount::new(derived_address, new_account_key, 0);
    let compiled_units = compiled_package.compiled_units;
    let mut uniq_modules: HashSet<String> = HashSet::new(); // Apparently modules can appear twice in compiled units, ensure uniq
    for unit in compiled_units {
        match unit {
            CompiledUnit::Module(NamedCompiledModule { name, module, .. }) => {
                let namecpy = name.to_string();
                if uniq_modules.contains(&namecpy) {
                    continue;
                }
                println!("Deploying Module: {}", namecpy);
                uniq_modules.insert(namecpy);
                let mut binary = vec![];
                module.serialize(&mut binary)?;
                let publish_txn = new_account.sign_with_transaction_builder(
                    factory.payload(TransactionPayload::Module(Module::new(binary))),
                );

                send(&client, publish_txn)?;
            }
            _ => {
                continue;
            }
        }
    }
    println!("Success!");

    // ================= Get modules in the account  ========================
    // Assumes we've deployed to the shuffle developer's address.

    let account_state_blob: AccountStateBlob = {
        let blob = client
            .get_account_state_with_proof(new_account.address(), None, None)
            .unwrap()
            .into_inner()
            .blob
            .ok_or_else(|| anyhow::anyhow!("missing account state blob"))?;
        bcs::from_bytes(&blob)?
    };
    let account_state = AccountState::try_from(&account_state_blob)?;
    let mut modules = vec![];
    for module_bytes in account_state.get_modules() {
        modules.push(normalized::Module::new(
            &CompiledModule::deserialize(module_bytes)
                .map_err(|e| anyhow!("Failure deserializing module: {:?}", e))?,
        ));
    }
    println!("move modules length: {}", modules.len());
    println!("move modules name: {}", modules[0].name);

    Ok(())
}
<commit_msg>Added updated sequence number for new account<commit_after>// Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0

use crate::shared::{get_shuffle_dir, send, MAIN_PKG_PATH};
use anyhow::{anyhow, Result};
use diem_crypto::PrivateKey;
use diem_sdk::{
    client::BlockingClient,
    transaction_builder::TransactionFactory,
    types::{
        transaction::{Module, TransactionPayload},
        LocalAccount,
    },
};
use diem_types::{
    account_state::AccountState, account_state_blob::AccountStateBlob, chain_id::ChainId,
    transaction::authenticator::AuthenticationKey,
};
use generate_key::load_key;
use move_binary_format::{file_format::CompiledModule, normalized};
use move_lang::compiled_unit::{CompiledUnit, NamedCompiledModule};
use move_package::compilation::compiled_package::CompiledPackage;
use std::{collections::HashSet, convert::TryFrom, path::Path};

/// Deploys shuffle's main Move Package to the sender's address.
pub fn handle(project_path: &Path) -> Result<()> {
    let account_key_path = get_shuffle_dir()
        .join("accounts")
        .join("latest")
        .join("dev.key");
    if !account_key_path.exists() {
        return Err(anyhow!(
            "An account hasn't been created yet! Run shuffle account first."
        ));
    }
    let compiled_package = build_move_packages(project_path)?;
    publish_packages_as_transaction(&account_key_path, compiled_package)
}

/// Builds the packages in the shuffle project using the move package system.
fn build_move_packages(project_path: &Path) -> Result<CompiledPackage> {
    println!("Building Examples...");
    let pkgdir = project_path.join(MAIN_PKG_PATH);
    let config = move_package::BuildConfig {
        dev_mode: true,
        test_mode: false,
        generate_docs: false,
        generate_abis: true,
    };

    config.compile_package(pkgdir.as_path(), &mut std::io::stdout())
}

fn publish_packages_as_transaction(
    account_key_path: &Path,
    compiled_package: CompiledPackage,
) -> Result<()> {
    let new_account_key = load_key(account_key_path);
    let json_rpc_url = format!("http://0.0.0.0:{}", 8080); // TODO: Hardcoded to local devnet
    let factory = TransactionFactory::new(ChainId::test());
    println!("Connecting to {}", json_rpc_url);

    let client = BlockingClient::new(json_rpc_url);

    println!("Using Public Key {}", &new_account_key.public_key());
    let derived_address =
        AuthenticationKey::ed25519(&new_account_key.public_key()).derived_address();
    println!(
        "Sending txn from address {}",
        derived_address.to_hex_literal()
    );

    // ================= Send a module transaction ========================
    let seq_number = client
        .get_account(derived_address)
        .unwrap()
        .into_inner()
        .unwrap()
        .sequence_number;
    let mut new_account = LocalAccount::new(derived_address, new_account_key, seq_number);
    let compiled_units = compiled_package.compiled_units;
    let mut uniq_modules: HashSet<String> = HashSet::new(); // Apparently modules can appear twice in compiled units, ensure uniq
    for unit in compiled_units {
        match unit {
            CompiledUnit::Module(NamedCompiledModule { name, module, .. }) => {
                let namecpy = name.to_string();
                if uniq_modules.contains(&namecpy) {
                    continue;
                }
                println!("Deploying Module: {}", namecpy);
                uniq_modules.insert(namecpy);
                let mut binary = vec![];
                module.serialize(&mut binary)?;
                let publish_txn = new_account.sign_with_transaction_builder(
                    factory.payload(TransactionPayload::Module(Module::new(binary))),
                );

                send(&client, publish_txn)?;
            }
            _ => {
                continue;
            }
        }
    }
    println!("Success!");

    // ================= Get modules in the account  ========================
    // Assumes we've deployed to the shuffle developer's address.

    let account_state_blob: AccountStateBlob = {
        let blob = client
            .get_account_state_with_proof(new_account.address(), None, None)
            .unwrap()
            .into_inner()
            .blob
            .ok_or_else(|| anyhow::anyhow!("missing account state blob"))?;
        bcs::from_bytes(&blob)?
    };
    let account_state = AccountState::try_from(&account_state_blob)?;
    let mut modules = vec![];
    for module_bytes in account_state.get_modules() {
        modules.push(normalized::Module::new(
            &CompiledModule::deserialize(module_bytes)
                .map_err(|e| anyhow!("Failure deserializing module: {:?}", e))?,
        ));
    }
    println!("move modules length: {}", modules.len());
    println!("move modules name: {}", modules[0].name);

    Ok(())
}
<|endoftext|>


<commit_before>
use num::*;
use mat::Mat4;
use vec::Vec3;
use std::ops::*;

#[derive(Debug, Clone, Copy, PartialEq)]
#[repr(C)]
pub struct Quaternion<T: Num + Float + Copy> {
    pub x: T,
    pub y: T,
    pub w: T,
    pub z: T,
}

impl<T: Num + Float + Copy> Default for Quaternion<T> {
    fn default() -> Quaternion<T> {
        Quaternion::new()
    }
}

impl<T: Num + Float + Copy> Quaternion<T> {
    /// Creates a new identity quaternion
    pub fn new() -> Quaternion<T> {
        Quaternion {
            x: T::zero(),
            y: T::zero(),
            z: T::zero(),
            w: T::one(),
        }
    }

    /// Creates a quaternion representing a counterclockwise rotation of `angle` radians around the
    /// given axis. This function normalizes the axis, but if the axis is `(0, 0, 0)` the quaternion
    /// will have its `x`, `y` and `z` fields set to 0.
    pub fn rotation(angle: T, axis: Vec3<T>) -> Quaternion<T> {
        let axis = axis.normalize();
        let angle = angle / (T::one() + T::one());
        let (sin, cos) = angle.sin_cos();
        Quaternion {
            x: axis.x*sin,
            y: axis.y*sin,
            z: axis.z*sin,
            w: cos,
        }
    }

    /// Calculates the length of this quaternion, raised to the power of two. Note that this is
    /// cheaper than computing the actual length.
    pub fn len_sqr(&self) -> T {
        self.x*self.x + self.y*self.y + self.z*self.z + self.w*self.w
    }

    /// Calculates the length of this quaternion.
    pub fn len(&self) -> T {
        (self.x*self.x + self.y*self.y + self.z*self.z + self.w*self.w).sqrt()
    }

    /// Normalizes this quaternion, returning a new quaternion with length 1.
    pub fn normalize(&self) -> Quaternion<T> {
        *self / self.len()
    }
}

impl<T: Num + Float + Copy> Mul for Quaternion<T> {
    type Output = Self;
    fn mul(self, other: Quaternion<T>) -> Self {
        Quaternion {
            x: self.w*other.x + self.x*other.w + self.y*other.z - self.z*other.y,
            y: self.w*other.y + self.y*other.w + self.z*other.x - self.x*other.z,
            z: self.w*other.z + self.z*other.w + self.x*other.y - self.y*other.x,
            w: self.w*other.w - self.x*other.x - self.y*other.y - self.z*other.z,
        }
    }
}
impl<T: Num + Float + Copy> MulAssign for Quaternion<T> {
    fn mul_assign(&mut self, other: Quaternion<T>) {
        let x = self.w*other.x + self.x*other.w + self.y*other.z - self.z*other.y;
        let y = self.w*other.y + self.y*other.w + self.z*other.x - self.x*other.z;
        let z = self.w*other.z + self.z*other.w + self.x*other.y - self.y*other.x;
        let w = self.w*other.w - self.x*other.x - self.y*other.y - self.z*other.z;
        self.x = x;
        self.y = y;
        self.z = z;
        self.w = w;
    }
}
impl<T: Num + Float + Copy> Mul<T> for Quaternion<T> {
    type Output = Self;
    fn mul(self, scalar: T) -> Self {
        Quaternion {
            x: self.x * scalar,
            y: self.y * scalar,
            z: self.z * scalar,
            w: self.w * scalar,
        }
    }
}
impl<T: Num + Float + Copy> MulAssign<T> for Quaternion<T> {
    fn mul_assign(&mut self, scalar: T) {
        self.x = self.x * scalar;
        self.y = self.y * scalar;
        self.z = self.z * scalar;
        self.w = self.w * scalar;
    }
}
impl<T: Num + Float + Copy> Div<T> for Quaternion<T> {
    type Output = Self;
    fn div(self, scalar: T) -> Self {
        Quaternion {
            x: self.x / scalar,
            y: self.y / scalar,
            z: self.z / scalar,
            w: self.w / scalar,
        }
    }
}
impl<T: Num + Float + Copy> DivAssign<T> for Quaternion<T> {
    fn div_assign(&mut self, scalar: T) {
        self.x = self.x / scalar;
        self.y = self.y / scalar;
        self.z = self.z / scalar;
        self.w = self.w / scalar;
    }
}

impl<T: Num + Float + Copy> From<Quaternion<T>> for Mat4<T> {
    fn from(quat: Quaternion<T>) -> Mat4<T> {
        Mat4::from_quaternion(quat.x, quat.y, quat.z, quat.w)
    }
}

#[cfg(test)]
mod tests {
    use std::f32;
    use super::*;
    use {Mat4, Vec4};

    #[test]
    fn identity() {
        let identity = Quaternion::<f32>::new();
        assert_eq!(identity, identity*identity);
        assert_eq!(identity, identity*identity*identity);
    }

    #[test]
    fn matrix_rotation() {
        let quat = Quaternion::<f32>::rotation(f32::consts::PI/2.0, Vec3::new(1.0, 0.0, 0.0));
        let mat: Mat4<f32> = quat.into();

        let a = Vec4::new(0.0, 1.0, 0.0, 1.0);
        let b = Vec4::new(0.0, 0.0, 1.0, 1.0);

        let dif = (mat*a - b).len();
        assert!(dif < 0.001);
    }

    #[test]
    fn matrix_rotation_reverse() {
        let mat_a: Mat4<f32> = Quaternion::rotation(f32::consts::PI/2.0, Vec3::new(1.0, 0.0, 0.0)).into();
        let mat_b: Mat4<f32> = Quaternion::rotation(-f32::consts::PI/2.0, Vec3::new(1.0, 0.0, 0.0)).into();

        let a = Vec4::new(0.0, 1.0, 0.0, 1.0);

        let dif = (mat_a*mat_b*a - a).len();
        assert!(dif < 0.001);
    }
}
<commit_msg>Directly use quaternion to transform angle<commit_after>
use num::*;
use mat::Mat4;
use vec::Vec3;
use std::ops::*;

#[derive(Debug, Clone, Copy, PartialEq)]
#[repr(C)]
pub struct Quaternion<T: Num + Float + Copy> {
    pub x: T,
    pub y: T,
    pub w: T,
    pub z: T,
}

impl<T: Num + Float + Copy> Default for Quaternion<T> {
    fn default() -> Quaternion<T> {
        Quaternion::new()
    }
}

impl<T: Num + Float + Copy> Quaternion<T> {
    /// Creates a new identity quaternion
    pub fn new() -> Quaternion<T> {
        Quaternion {
            x: T::zero(),
            y: T::zero(),
            z: T::zero(),
            w: T::one(),
        }
    }

    /// Creates a quaternion representing a counterclockwise rotation of `angle` radians around the
    /// given axis. This function normalizes the axis, but if the axis is `(0, 0, 0)` the quaternion
    /// will have its `x`, `y` and `z` fields set to 0.
    pub fn rotation(angle: T, axis: Vec3<T>) -> Quaternion<T> {
        let axis = axis.normalize();
        let angle = angle / (T::one() + T::one());
        let (sin, cos) = angle.sin_cos();
        Quaternion {
            x: axis.x*sin,
            y: axis.y*sin,
            z: axis.z*sin,
            w: cos,
        }
    }

    /// Calculates the length of this quaternion, raised to the power of two. Note that this is
    /// cheaper than computing the actual length.
    pub fn len_sqr(&self) -> T {
        self.x*self.x + self.y*self.y + self.z*self.z + self.w*self.w
    }

    /// Calculates the length of this quaternion.
    pub fn len(&self) -> T {
        (self.x*self.x + self.y*self.y + self.z*self.z + self.w*self.w).sqrt()
    }

    /// Normalizes this quaternion, returning a new quaternion with length 1.
    pub fn normalize(&self) -> Quaternion<T> {
        *self / self.len()
    }
}

// Quaternion vector multiplication
impl<T: Num + Float + Copy> Mul<Vec3<T>> for Quaternion<T> {
    type Output = Vec3<T>;
    fn mul(self, vec: Vec3<T>) -> Vec3<T> {
        let one = T::one();
        let two = one + one;

        let a11 = one - two*self.y*self.y - two*self.z*self.z;
        let a12 = two*self.x*self.y - two*self.z*self.w;
        let a13 = two*self.x*self.z + two*self.y*self.w;

        let a21 = two*self.x*self.y + two*self.w*self.z;
        let a22 = one - two*self.x*self.x - two*self.z*self.z;
        let a23 = two*self.y*self.z - two*self.w*self.x;

        let a31 = two*self.x*self.z - two*self.w*self.y;
        let a32 = two*self.y*self.z + two*self.w*self.x;
        let a33 = one - two*self.x*self.x - two*self.y*self.y;

        Vec3 {
            x: vec.x*a11 + vec.y*a12 + vec.z*a13,
            y: vec.x*a21 + vec.y*a22 + vec.z*a23,
            z: vec.x*a31 + vec.y*a32 + vec.z*a33,
        }
    }
}

// Quaternion quaternion multiplication
impl<T: Num + Float + Copy> Mul for Quaternion<T> {
    type Output = Self;
    fn mul(self, other: Quaternion<T>) -> Self {
        Quaternion {
            x: self.w*other.x + self.x*other.w + self.y*other.z - self.z*other.y,
            y: self.w*other.y + self.y*other.w + self.z*other.x - self.x*other.z,
            z: self.w*other.z + self.z*other.w + self.x*other.y - self.y*other.x,
            w: self.w*other.w - self.x*other.x - self.y*other.y - self.z*other.z,
        }
    }
}
impl<T: Num + Float + Copy> MulAssign for Quaternion<T> {
    fn mul_assign(&mut self, other: Quaternion<T>) {
        let x = self.w*other.x + self.x*other.w + self.y*other.z - self.z*other.y;
        let y = self.w*other.y + self.y*other.w + self.z*other.x - self.x*other.z;
        let z = self.w*other.z + self.z*other.w + self.x*other.y - self.y*other.x;
        let w = self.w*other.w - self.x*other.x - self.y*other.y - self.z*other.z;
        self.x = x;
        self.y = y;
        self.z = z;
        self.w = w;
    }
}

// Quaternion scalar multiplication
impl<T: Num + Float + Copy> Mul<T> for Quaternion<T> {
    type Output = Self;
    fn mul(self, scalar: T) -> Self {
        Quaternion {
            x: self.x * scalar,
            y: self.y * scalar,
            z: self.z * scalar,
            w: self.w * scalar,
        }
    }
}
impl<T: Num + Float + Copy> MulAssign<T> for Quaternion<T> {
    fn mul_assign(&mut self, scalar: T) {
        self.x = self.x * scalar;
        self.y = self.y * scalar;
        self.z = self.z * scalar;
        self.w = self.w * scalar;
    }
}
impl<T: Num + Float + Copy> Div<T> for Quaternion<T> {
    type Output = Self;
    fn div(self, scalar: T) -> Self {
        Quaternion {
            x: self.x / scalar,
            y: self.y / scalar,
            z: self.z / scalar,
            w: self.w / scalar,
        }
    }
}
impl<T: Num + Float + Copy> DivAssign<T> for Quaternion<T> {
    fn div_assign(&mut self, scalar: T) {
        self.x = self.x / scalar;
        self.y = self.y / scalar;
        self.z = self.z / scalar;
        self.w = self.w / scalar;
    }
}

impl<T: Num + Float + Copy> From<Quaternion<T>> for Mat4<T> {
    fn from(quat: Quaternion<T>) -> Mat4<T> {
        Mat4::from_quaternion(quat.x, quat.y, quat.z, quat.w)
    }
}

#[cfg(test)]
mod tests {
    use std::f32;
    use super::*;
    use {Mat4, Vec4};

    #[test]
    fn identity() {
        let identity = Quaternion::<f32>::new();
        assert_eq!(identity, identity*identity);
        assert_eq!(identity, identity*identity*identity);
    }

    #[test]
    fn matrix_rotation() {
        let quat = Quaternion::<f32>::rotation(f32::consts::PI/2.0, Vec3::new(1.0, 0.0, 0.0));
        let mat: Mat4<f32> = quat.into();

        let a = Vec4::new(0.0, 1.0, 0.0, 1.0);
        let b = Vec4::new(0.0, 0.0, 1.0, 1.0);

        let diff = (mat*a - b).len();
        assert!(diff < 0.001);
    }

    #[test]
    fn matrix_rotation_reverse() {
        let mat_a: Mat4<f32> = Quaternion::rotation(f32::consts::PI/2.0, Vec3::new(1.0, 0.0, 0.0)).into();
        let mat_b: Mat4<f32> = Quaternion::rotation(-f32::consts::PI/2.0, Vec3::new(1.0, 0.0, 0.0)).into();

        let a = Vec4::new(0.0, 1.0, 0.0, 1.0);

        let diff = (mat_a*mat_b*a - a).len();
        assert!(diff < 0.001);
    }

    #[test]
    fn quaternion_rotation() {
        let quat: Quaternion<f32> = Quaternion::rotation(f32::consts::PI/2.0, Vec3::new(1.0, 0.0, 0.0)).into();

        let a = Vec3::new(0.0, 1.0, 0.0);
        let b = Vec3::new(0.0, 0.0, 1.0);

        let diff = (quat*a - b).len();
        assert!(diff < 0.001);
    }
}
<|endoftext|>


<commit_before>
#[cfg(test)]

extern crate serde;
extern crate libc;

#[macro_use]
extern crate serde_json;

#[macro_use]
extern crate serde_derive;

use serde_json::from_str;
use std::ops::Carrier;

/// HelloWorld as a target from the JSON from Ruby
#[derive(Serialize, Deserialize)]
pub struct HelloWorld {
    hello: String,
    world: String
}

/// This is an example of passing complex objects
/// from Ruby to Rust with strong type checking as JSON
#[no_mangle]
pub extern "C" fn hello_world(json: &str, count: u32) -> u32 {
    let mut hw: HelloWorld = from_str(json)?;

    // We simply want to show how to pass primitives as well
    for i in 0..count {
        println!("vec: {:?}", hw);
    }
    // return one less than the count given
    --count
}

/// Here we must free strings from Rust when we are done
/// with them.
#[no_mangle]
pub extern "C" fn rust_free(c_ptr: *mut libc::c_void) {
    unsafe {
        libc::free(c_ptr);
    }
}
<commit_msg>rust part compiles flawlessly<commit_after>
#[cfg(test)]

extern crate serde;
extern crate libc;
extern crate serde_json;

#[macro_use]
extern crate serde_derive;

use serde_json::from_str;
use serde_json::Error;
use std::result::Result;

/// HelloWorld as a target from the JSON from Ruby
#[derive(Debug)]
#[derive(Serialize, Deserialize)]
pub struct HelloWorld {
    hello: String,
    world: String
}

/// This is an example of passing complex objects
/// from Ruby to Rust with strong type checking as JSON
#[no_mangle]
pub extern "C" fn hello_world(json: &str, count: u32) ->  Result<u32, Error> {
    let hw: HelloWorld = from_str(json)?;

    // We simply want to show how to pass primitives as well
    for i in 0..count {
        println!("{}: vec: {:?}", i, hw);
    }
    // return one less than the count given
    Ok(count - 1)
}

/// Here we must free strings from Rust when we are done
/// with them.
#[no_mangle]
pub extern "C" fn rust_free(c_ptr: *mut libc::c_void) {
    unsafe {
        libc::free(c_ptr);
    }
}
<|endoftext|>


<commit_before>/// Implements `Type` for some struct.
///
/// This is used to enable serialization of fields for arbitrary structs.
///
/// ```none
/// pub struct Foo { a: u8, b: u16 };
///
/// implement_composite_type!(Foo { a, b });
/// ```
#[macro_export]
macro_rules! implement_composite_type {
    ($ty:ident { $( $field_name:ident ),+ }) => {
        impl $crate::Type for $ty
        {
            fn read(read: &mut ::std::io::Read) -> Result<Self, $crate::Error> {
                Ok($ty {
                    $( $field_name: $crate::Type::read(read)? ),+
                })
            }

            fn write(&self, write: &mut ::std::io::Write) -> Result<(), $crate::Error> {
                $( self.$field_name.write(write)?; )+

                Ok(())
            }
        }
    }
}

/// Defines a type built out of other types.
///
/// ```none
/// define_composite_type!(Foo {
///     a: u8,
///     b: u16
/// });
/// ```
#[macro_export]
macro_rules! define_composite_type {
    ($ty:ident { $( $field_name:ident : $field_ty:ty ),+ }) => {
        #[derive(Clone,Debug, PartialEq)]
        pub struct $ty
        {
            $( $field_name : $field_ty ),+
        }

        implement_composite_type!($ty {
            $( $field_name ),+
        });
    }
}

#[cfg(test)]
#[allow(unused_variables)]
mod test
{
    pub use Type;
    pub use std::io::Cursor;

    #[derive(Clone, Debug)]
    pub struct Foo
    {
        baz: String,
        bing: i64,
    }

    implement_composite_type!(Foo { baz, bing });

    define_composite_type!(Bar {
        baz: String,
        bing: i64
    });

    define_composite_type!(Bing {
        a: u8,
        b: u8,
        c: u8
    });

    describe! composite_types {
        before_each {
            let foo = Foo { baz: "baz".to_string(), bing: 32 };
            let bar = Bar { baz: "baz".to_string(), bing: 32 };
            let bing = Bing { a: 3, b: 2, c: 1 };
        }

        describe! macros {
            it "is consistent when using the different macros" {
                assert_eq!(foo.raw_bytes().unwrap(), bar.raw_bytes().unwrap());
            }
        }

        describe! writing {
            it "matches the expected output" {
                assert_eq!(&bing.raw_bytes().unwrap(), &[bing.a, bing.b, bing.c]);
            }
        }

        describe! reading {
            it "reads the expected value" {
                let mut buffer = Cursor::new([bing.a, bing.b, bing.c]);
                let read = Bing::read(&mut buffer).unwrap();

                assert_eq!(read, bing);
            }
        }
    }
}

<commit_msg>Declare fields private when defining composite types<commit_after>/// Implements `Type` for some struct.
///
/// This is used to enable serialization of fields for arbitrary structs.
///
/// ```none
/// pub struct Foo { a: u8, b: u16 };
///
/// implement_composite_type!(Foo { a, b });
/// ```
#[macro_export]
macro_rules! implement_composite_type {
    ($ty:ident { $( $field_name:ident ),+ }) => {
        impl $crate::Type for $ty
        {
            fn read(read: &mut ::std::io::Read) -> Result<Self, $crate::Error> {
                Ok($ty {
                    $( $field_name: $crate::Type::read(read)? ),+
                })
            }

            fn write(&self, write: &mut ::std::io::Write) -> Result<(), $crate::Error> {
                $( self.$field_name.write(write)?; )+

                Ok(())
            }
        }
    }
}

/// Defines a type built out of other types.
///
/// ```none
/// define_composite_type!(Foo {
///     a: u8,
///     b: u16
/// });
/// ```
#[macro_export]
macro_rules! define_composite_type {
    ($ty:ident { $( $field_name:ident : $field_ty:ty ),+ }) => {
        #[derive(Clone,Debug, PartialEq)]
        pub struct $ty
        {
            $( pub $field_name : $field_ty ),+
        }

        implement_composite_type!($ty {
            $( $field_name ),+
        });
    }
}

#[cfg(test)]
#[allow(unused_variables)]
mod test
{
    pub use Type;
    pub use std::io::Cursor;

    #[derive(Clone, Debug)]
    pub struct Foo
    {
        baz: String,
        bing: i64,
    }

    implement_composite_type!(Foo { baz, bing });

    define_composite_type!(Bar {
        baz: String,
        bing: i64
    });

    define_composite_type!(Bing {
        a: u8,
        b: u8,
        c: u8
    });

    describe! composite_types {
        before_each {
            let foo = Foo { baz: "baz".to_string(), bing: 32 };
            let bar = Bar { baz: "baz".to_string(), bing: 32 };
            let bing = Bing { a: 3, b: 2, c: 1 };
        }

        describe! macros {
            it "is consistent when using the different macros" {
                assert_eq!(foo.raw_bytes().unwrap(), bar.raw_bytes().unwrap());
            }
        }

        describe! writing {
            it "matches the expected output" {
                assert_eq!(&bing.raw_bytes().unwrap(), &[bing.a, bing.b, bing.c]);
            }
        }

        describe! reading {
            it "reads the expected value" {
                let mut buffer = Cursor::new([bing.a, bing.b, bing.c]);
                let read = Bing::read(&mut buffer).unwrap();

                assert_eq!(read, bing);
            }
        }
    }
}

<|endoftext|>


<commit_before>use buffer::{Content, Buffer, BufferAny, BufferType, BufferMode, BufferCreationError};
use buffer::{BufferSlice, BufferMutSlice};
use uniforms::{AsUniformValue, UniformBlock, UniformValue, LayoutMismatchError};
use program;

use gl;
use GlObject;

use std::ops::{Deref, DerefMut};

use backend::Facade;

/// Buffer that contains a uniform block.
///
/// For example, to use a `UniformBuffer<[u32; 8]>`, you must declare it as
///
///     uniform MyBlock {
///         uint array[8];
///     };
///
/// and pass it to `uniform!` like this:
///
///     uniform! {
///         MyBlock: &buffer,
///     }
#[derive(Debug)]
pub struct UniformBuffer<T: ?Sized> where T: Content {
    buffer: Buffer<T>,
}

/// Same as `UniformBuffer` but doesn't contain any information about the type.
#[derive(Debug)]
pub struct TypelessUniformBuffer {
    buffer: BufferAny,
}

impl<T: ?Sized + Content> GlObject for UniformBuffer<T> {
    type Id = gl::types::GLuint;

    #[inline]
    fn get_id(&self) -> gl::types::GLuint {
        self.buffer.get_id()
    }
}

impl<T> UniformBuffer<T> where T: Copy {
    /// Uploads data in the uniforms buffer.
    #[inline]
    pub fn new<F: ?Sized>(facade: &F, data: T) -> Result<UniformBuffer<T>, BufferCreationError>
                  where F: Facade
    {
        UniformBuffer::new_impl(facade, data, BufferMode::Default)
    }

    /// Uploads data in the uniforms buffer.
    #[inline]
    pub fn dynamic<F: ?Sized>(facade: &F, data: T) -> Result<UniformBuffer<T>, BufferCreationError>
                      where F: Facade
    {
        UniformBuffer::new_impl(facade, data, BufferMode::Dynamic)
    }

    /// Uploads data in the uniforms buffer.
    #[inline]
    pub fn persistent<F: ?Sized>(facade: &F, data: T) -> Result<UniformBuffer<T>, BufferCreationError>
                  where F: Facade
    {
        UniformBuffer::new_impl(facade, data, BufferMode::Persistent)
    }

    /// Uploads data in the uniforms buffer.
    #[inline]
    pub fn immutable<F: ?Sized>(facade: &F, data: T) -> Result<UniformBuffer<T>, BufferCreationError>
                        where F: Facade
    {
        UniformBuffer::new_impl(facade, data, BufferMode::Immutable)
    }

    #[inline]
    fn new_impl<F: ?Sized>(facade: &F, data: T, mode: BufferMode)
                   -> Result<UniformBuffer<T>, BufferCreationError>
                   where F: Facade
    {
        let buffer = Buffer::new(facade, &data, BufferType::UniformBuffer, mode)?;

        Ok(UniformBuffer {
            buffer: buffer,
        })
    }

    /// Creates an empty buffer.
    #[inline]
    pub fn empty<F: ?Sized>(facade: &F) -> Result<UniformBuffer<T>, BufferCreationError> where F: Facade {
        UniformBuffer::empty_impl(facade, BufferMode::Default)
    }

    /// Creates an empty buffer.
    #[inline]
    pub fn empty_dynamic<F: ?Sized>(facade: &F) -> Result<UniformBuffer<T>, BufferCreationError>
                            where F: Facade
    {
        UniformBuffer::empty_impl(facade, BufferMode::Dynamic)
    }

    /// Creates an empty buffer.
    #[inline]
    pub fn empty_persistent<F: ?Sized>(facade: &F) -> Result<UniformBuffer<T>, BufferCreationError>
                               where F: Facade
    {
        UniformBuffer::empty_impl(facade, BufferMode::Persistent)
    }

    /// Creates an empty buffer.
    #[inline]
    pub fn empty_immutable<F: ?Sized>(facade: &F) -> Result<UniformBuffer<T>, BufferCreationError>
                              where F: Facade
    {
        UniformBuffer::empty_impl(facade, BufferMode::Immutable)
    }

    #[inline]
    fn empty_impl<F: ?Sized>(facade: &F, mode: BufferMode) -> Result<UniformBuffer<T>, BufferCreationError>
                     where F: Facade
    {
        let buffer = Buffer::empty(facade, BufferType::UniformBuffer, mode)?;

        Ok(UniformBuffer {
            buffer: buffer,
        })
    }
}

impl<T: ?Sized> UniformBuffer<T> where T: Content {
    /// Creates an empty buffer.
    ///
    /// # Panic
    ///
    /// Panics if the size passed as parameter is not suitable for the type of data.
    ///
    #[inline]
    pub fn empty_unsized<F: ?Sized>(facade: &F, size: usize)
                            -> Result<UniformBuffer<T>, BufferCreationError>
                            where F: Facade
    {
        UniformBuffer::empty_unsized_impl(facade, size, BufferMode::Default)
    }

    /// Creates an empty buffer.
    ///
    /// # Panic
    ///
    /// Panics if the size passed as parameter is not suitable for the type of data.
    ///
    #[inline]
    pub fn empty_unsized_dynamic<F: ?Sized>(facade: &F, size: usize)
                                    -> Result<UniformBuffer<T>, BufferCreationError>
                                    where F: Facade
    {
        UniformBuffer::empty_unsized_impl(facade, size, BufferMode::Dynamic)
    }

    /// Creates an empty buffer.
    ///
    /// # Panic
    ///
    /// Panics if the size passed as parameter is not suitable for the type of data.
    ///
    #[inline]
    pub fn empty_unsized_persistent<F: ?Sized>(facade: &F, size: usize)
                                       -> Result<UniformBuffer<T>, BufferCreationError>
                                       where F: Facade
    {
        UniformBuffer::empty_unsized_impl(facade, size, BufferMode::Persistent)
    }

    /// Creates an empty buffer.
    ///
    /// # Panic
    ///
    /// Panics if the size passed as parameter is not suitable for the type of data.
    ///
    #[inline]
    pub fn empty_unsized_immutable<F: ?Sized>(facade: &F, size: usize)
                                      -> Result<UniformBuffer<T>, BufferCreationError>
                                      where F: Facade
    {
        UniformBuffer::empty_unsized_impl(facade, size, BufferMode::Immutable)
    }

    #[inline]
    fn empty_unsized_impl<F: ?Sized>(facade: &F, size: usize, mode: BufferMode)
                             -> Result<UniformBuffer<T>, BufferCreationError>
                             where F: Facade
    {
        let buffer = Buffer::empty_unsized(facade, BufferType::UniformBuffer, size, mode)?;

        Ok(UniformBuffer {
            buffer: buffer,
        })
    }
}

impl<T: ?Sized> Deref for UniformBuffer<T> where T: Content {
    type Target = Buffer<T>;

    #[inline]
    fn deref(&self) -> &Buffer<T> {
        &self.buffer
    }
}

impl<T: ?Sized> DerefMut for UniformBuffer<T> where T: Content {
    #[inline]
    fn deref_mut(&mut self) -> &mut Buffer<T> {
        &mut self.buffer
    }
}

impl<'a, T: ?Sized> From<&'a UniformBuffer<T>> for BufferSlice<'a, T> where T: Content {
    #[inline]
    fn from(b: &'a UniformBuffer<T>) -> BufferSlice<'a, T> {
        b.buffer.as_slice()
    }
}

impl<'a, T: ?Sized> From<&'a mut UniformBuffer<T>> for BufferMutSlice<'a, T> where T: Content {
    #[inline]
    fn from(b: &'a mut UniformBuffer<T>) -> BufferMutSlice<'a, T> {
        b.buffer.as_mut_slice()
    }
}

impl<'a, T: ?Sized> AsUniformValue for &'a UniformBuffer<T> where T: UniformBlock + Content {
    #[inline]
    fn as_uniform_value(&self) -> UniformValue {
        #[inline]
        fn f<T: ?Sized>(block: &program::UniformBlock)
                        -> Result<(), LayoutMismatchError> where T: UniformBlock + Content
        {
            // TODO: more checks?
            T::matches(&block.layout, 0)
        }

        UniformValue::Block(self.buffer.as_slice_any(), f::<T>)
    }
}
<commit_msg>Fix doc-tests in uniforms::buffer module.<commit_after>use buffer::{Content, Buffer, BufferAny, BufferType, BufferMode, BufferCreationError};
use buffer::{BufferSlice, BufferMutSlice};
use uniforms::{AsUniformValue, UniformBlock, UniformValue, LayoutMismatchError};
use program;

use gl;
use GlObject;

use std::ops::{Deref, DerefMut};

use backend::Facade;

/// Buffer that contains a uniform block.
///
/// For example, to use a `UniformBuffer<[u32; 8]>`, you must declare it in GLSL as
///```ignore
///     uniform MyBlock {
///         uint array[8];
///     };
///```
///
/// and pass it to `uniform!` like this:
///     # use glium::uniform;
///     uniform! {
///         MyBlock: &buffer,
///     }
#[derive(Debug)]
pub struct UniformBuffer<T: ?Sized> where T: Content {
    buffer: Buffer<T>,
}

/// Same as `UniformBuffer` but doesn't contain any information about the type.
#[derive(Debug)]
pub struct TypelessUniformBuffer {
    buffer: BufferAny,
}

impl<T: ?Sized + Content> GlObject for UniformBuffer<T> {
    type Id = gl::types::GLuint;

    #[inline]
    fn get_id(&self) -> gl::types::GLuint {
        self.buffer.get_id()
    }
}

impl<T> UniformBuffer<T> where T: Copy {
    /// Uploads data in the uniforms buffer.
    #[inline]
    pub fn new<F: ?Sized>(facade: &F, data: T) -> Result<UniformBuffer<T>, BufferCreationError>
                  where F: Facade
    {
        UniformBuffer::new_impl(facade, data, BufferMode::Default)
    }

    /// Uploads data in the uniforms buffer.
    #[inline]
    pub fn dynamic<F: ?Sized>(facade: &F, data: T) -> Result<UniformBuffer<T>, BufferCreationError>
                      where F: Facade
    {
        UniformBuffer::new_impl(facade, data, BufferMode::Dynamic)
    }

    /// Uploads data in the uniforms buffer.
    #[inline]
    pub fn persistent<F: ?Sized>(facade: &F, data: T) -> Result<UniformBuffer<T>, BufferCreationError>
                  where F: Facade
    {
        UniformBuffer::new_impl(facade, data, BufferMode::Persistent)
    }

    /// Uploads data in the uniforms buffer.
    #[inline]
    pub fn immutable<F: ?Sized>(facade: &F, data: T) -> Result<UniformBuffer<T>, BufferCreationError>
                        where F: Facade
    {
        UniformBuffer::new_impl(facade, data, BufferMode::Immutable)
    }

    #[inline]
    fn new_impl<F: ?Sized>(facade: &F, data: T, mode: BufferMode)
                   -> Result<UniformBuffer<T>, BufferCreationError>
                   where F: Facade
    {
        let buffer = Buffer::new(facade, &data, BufferType::UniformBuffer, mode)?;

        Ok(UniformBuffer {
            buffer: buffer,
        })
    }

    /// Creates an empty buffer.
    #[inline]
    pub fn empty<F: ?Sized>(facade: &F) -> Result<UniformBuffer<T>, BufferCreationError> where F: Facade {
        UniformBuffer::empty_impl(facade, BufferMode::Default)
    }

    /// Creates an empty buffer.
    #[inline]
    pub fn empty_dynamic<F: ?Sized>(facade: &F) -> Result<UniformBuffer<T>, BufferCreationError>
                            where F: Facade
    {
        UniformBuffer::empty_impl(facade, BufferMode::Dynamic)
    }

    /// Creates an empty buffer.
    #[inline]
    pub fn empty_persistent<F: ?Sized>(facade: &F) -> Result<UniformBuffer<T>, BufferCreationError>
                               where F: Facade
    {
        UniformBuffer::empty_impl(facade, BufferMode::Persistent)
    }

    /// Creates an empty buffer.
    #[inline]
    pub fn empty_immutable<F: ?Sized>(facade: &F) -> Result<UniformBuffer<T>, BufferCreationError>
                              where F: Facade
    {
        UniformBuffer::empty_impl(facade, BufferMode::Immutable)
    }

    #[inline]
    fn empty_impl<F: ?Sized>(facade: &F, mode: BufferMode) -> Result<UniformBuffer<T>, BufferCreationError>
                     where F: Facade
    {
        let buffer = Buffer::empty(facade, BufferType::UniformBuffer, mode)?;

        Ok(UniformBuffer {
            buffer: buffer,
        })
    }
}

impl<T: ?Sized> UniformBuffer<T> where T: Content {
    /// Creates an empty buffer.
    ///
    /// # Panic
    ///
    /// Panics if the size passed as parameter is not suitable for the type of data.
    ///
    #[inline]
    pub fn empty_unsized<F: ?Sized>(facade: &F, size: usize)
                            -> Result<UniformBuffer<T>, BufferCreationError>
                            where F: Facade
    {
        UniformBuffer::empty_unsized_impl(facade, size, BufferMode::Default)
    }

    /// Creates an empty buffer.
    ///
    /// # Panic
    ///
    /// Panics if the size passed as parameter is not suitable for the type of data.
    ///
    #[inline]
    pub fn empty_unsized_dynamic<F: ?Sized>(facade: &F, size: usize)
                                    -> Result<UniformBuffer<T>, BufferCreationError>
                                    where F: Facade
    {
        UniformBuffer::empty_unsized_impl(facade, size, BufferMode::Dynamic)
    }

    /// Creates an empty buffer.
    ///
    /// # Panic
    ///
    /// Panics if the size passed as parameter is not suitable for the type of data.
    ///
    #[inline]
    pub fn empty_unsized_persistent<F: ?Sized>(facade: &F, size: usize)
                                       -> Result<UniformBuffer<T>, BufferCreationError>
                                       where F: Facade
    {
        UniformBuffer::empty_unsized_impl(facade, size, BufferMode::Persistent)
    }

    /// Creates an empty buffer.
    ///
    /// # Panic
    ///
    /// Panics if the size passed as parameter is not suitable for the type of data.
    ///
    #[inline]
    pub fn empty_unsized_immutable<F: ?Sized>(facade: &F, size: usize)
                                      -> Result<UniformBuffer<T>, BufferCreationError>
                                      where F: Facade
    {
        UniformBuffer::empty_unsized_impl(facade, size, BufferMode::Immutable)
    }

    #[inline]
    fn empty_unsized_impl<F: ?Sized>(facade: &F, size: usize, mode: BufferMode)
                             -> Result<UniformBuffer<T>, BufferCreationError>
                             where F: Facade
    {
        let buffer = Buffer::empty_unsized(facade, BufferType::UniformBuffer, size, mode)?;

        Ok(UniformBuffer {
            buffer: buffer,
        })
    }
}

impl<T: ?Sized> Deref for UniformBuffer<T> where T: Content {
    type Target = Buffer<T>;

    #[inline]
    fn deref(&self) -> &Buffer<T> {
        &self.buffer
    }
}

impl<T: ?Sized> DerefMut for UniformBuffer<T> where T: Content {
    #[inline]
    fn deref_mut(&mut self) -> &mut Buffer<T> {
        &mut self.buffer
    }
}

impl<'a, T: ?Sized> From<&'a UniformBuffer<T>> for BufferSlice<'a, T> where T: Content {
    #[inline]
    fn from(b: &'a UniformBuffer<T>) -> BufferSlice<'a, T> {
        b.buffer.as_slice()
    }
}

impl<'a, T: ?Sized> From<&'a mut UniformBuffer<T>> for BufferMutSlice<'a, T> where T: Content {
    #[inline]
    fn from(b: &'a mut UniformBuffer<T>) -> BufferMutSlice<'a, T> {
        b.buffer.as_mut_slice()
    }
}

impl<'a, T: ?Sized> AsUniformValue for &'a UniformBuffer<T> where T: UniformBlock + Content {
    #[inline]
    fn as_uniform_value(&self) -> UniformValue {
        #[inline]
        fn f<T: ?Sized>(block: &program::UniformBlock)
                        -> Result<(), LayoutMismatchError> where T: UniformBlock + Content
        {
            // TODO: more checks?
            T::matches(&block.layout, 0)
        }

        UniformValue::Block(self.buffer.as_slice_any(), f::<T>)
    }
}
<|endoftext|>


<commit_before>use serde::{Deserialize, Serialize};
use std::sync::Arc;

pub mod addr;
pub mod admin;
pub mod code;
pub mod context;
pub mod coord;
pub mod i18n_properties;
pub mod poi;
pub mod stop;
pub mod street;

pub mod utils;

use addr::Addr;
use admin::Admin;
use poi::Poi;
use stop::Stop;
use street::Street;

/// Object stored in Elasticsearch
#[allow(clippy::large_enum_variant)]
#[derive(Deserialize, Debug, Clone)]
#[serde(rename_all = "snake_case", tag = "type")]
pub enum Place {
    Admin(Admin),
    Street(Street),
    Addr(Addr),
    Poi(Poi),
    Stop(Stop),
}

/// Object stored in Elasticsearch
#[allow(clippy::large_enum_variant)]
#[derive(Serialize, Deserialize, Debug, Clone)]
#[serde(rename_all = "snake_case", tag = "type")]
pub enum Address {
    Street(Street),
    Addr(Addr),
}

impl Place {
    pub fn is_admin(&self) -> bool {
        matches!(self, Place::Admin(_))
    }

    pub fn is_street(&self) -> bool {
        matches!(self, Place::Street(_))
    }

    pub fn is_addr(&self) -> bool {
        matches!(self, Place::Addr(_))
    }

    pub fn is_poi(&self) -> bool {
        matches!(self, Place::Poi(_))
    }

    pub fn is_stop(&self) -> bool {
        matches!(self, Place::Stop(_))
    }

    pub fn poi(&self) -> Option<&Poi> {
        match *self {
            Place::Poi(ref poi) => Some(poi),
            _ => None,
        }
    }

    pub fn id(&self) -> &str {
        match *self {
            Place::Admin(ref o) => &o.id,
            Place::Street(ref o) => &o.id,
            Place::Addr(ref o) => &o.id,
            Place::Poi(ref o) => &o.id,
            Place::Stop(ref o) => &o.id,
        }
    }

    pub fn label(&self) -> &str {
        match *self {
            Place::Admin(ref o) => o.label(),
            Place::Street(ref o) => o.label(),
            Place::Addr(ref o) => o.label(),
            Place::Poi(ref o) => o.label(),
            Place::Stop(ref o) => o.label(),
        }
    }

    pub fn admins(&self) -> Vec<Arc<Admin>> {
        match *self {
            Place::Admin(ref o) => o.admins(),
            Place::Street(ref o) => o.admins(),
            Place::Addr(ref o) => o.admins(),
            Place::Poi(ref o) => o.admins(),
            Place::Stop(ref o) => o.admins(),
        }
    }

    pub fn address(&self) -> Option<Address> {
        match *self {
            Place::Admin(_) => None,
            Place::Street(ref o) => Some(Address::Street(o.clone())),
            Place::Addr(ref o) => Some(Address::Addr(o.clone())),
            Place::Poi(_) => None,
            Place::Stop(_) => None,
        }
    }

    pub fn distance(&self) -> Option<u32> {
        match *self {
            Place::Admin(ref o) => o.distance,
            Place::Street(ref o) => o.distance,
            Place::Addr(ref o) => o.distance,
            Place::Poi(ref o) => o.distance,
            Place::Stop(ref o) => o.distance,
        }
    }

    pub fn set_distance(&mut self, d: u32) {
        match self {
            Place::Admin(ref mut o) => o.distance = Some(d),
            Place::Street(ref mut o) => o.distance = Some(d),
            Place::Addr(ref mut o) => o.distance = Some(d),
            Place::Poi(ref mut o) => o.distance = Some(d),
            Place::Stop(ref mut o) => o.distance = Some(d),
        }
    }

    pub fn coord(&self) -> &coord::Coord {
        match self {
            Place::Admin(ref o) => &o.coord,
            Place::Street(ref o) => &o.coord,
            Place::Addr(ref o) => &o.coord,
            Place::Poi(ref o) => &o.coord,
            Place::Stop(ref o) => &o.coord,
        }
    }

    pub fn set_context(&mut self, context: context::Context) {
        match self {
            Place::Admin(ref mut o) => o.context = Some(context),
            Place::Street(ref mut o) => o.context = Some(context),
            Place::Addr(ref mut o) => o.context = Some(context),
            Place::Poi(ref mut o) => o.context = Some(context),
            Place::Stop(ref mut o) => o.context = Some(context),
        }
    }

    /* We can afford to clone the context because we're in debug mode
     * and performance are less critical */
    pub fn context(&self) -> Option<context::Context> {
        match self {
            Place::Admin(ref o) => o.context.clone(),
            Place::Street(ref o) => o.context.clone(),
            Place::Addr(ref o) => o.context.clone(),
            Place::Poi(ref o) => o.context.clone(),
            Place::Stop(ref o) => o.context.clone(),
        }
    }
}

// This is a bit of a kludge to a get a string version for the doc_type.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum PlaceDocType {
    Admin,
    Street,
    Addr,
    Poi,
    Stop,
}

impl PlaceDocType {
    pub fn as_str(&self) -> &'static str {
        match self {
            PlaceDocType::Admin => "admin",
            PlaceDocType::Street => "street",
            PlaceDocType::Addr => "addr",
            PlaceDocType::Poi => "poi",
            PlaceDocType::Stop => "stop",
        }
    }
}

pub trait Members {
    fn label(&self) -> &str;
    fn admins(&self) -> Vec<Arc<Admin>>;
}

#[derive(Serialize, Deserialize, Debug, Clone, Hash, Eq, PartialEq, Ord, PartialOrd, Default)]
pub struct Property {
    pub key: String,
    pub value: String,
}

impl From<navitia_poi_model::Property> for Property {
    fn from(property: navitia_poi_model::Property) -> Property {
        Property {
            key: property.key,
            value: property.value,
        }
    }
}

impl From<&Place> for geojson::Geometry {
    fn from(place: &Place) -> Self {
        match place {
            Place::Admin(admin) => geojson::Geometry::from(admin),
            Place::Street(street) => geojson::Geometry::from(street),
            Place::Addr(addr) => geojson::Geometry::from(addr),
            Place::Poi(poi) => geojson::Geometry::from(poi),
            Place::Stop(stop) => geojson::Geometry::from(stop),
        }
    }
}
<commit_msg>Use untagged enum for serde rep of address<commit_after>use serde::{Deserialize, Serialize};
use std::sync::Arc;

pub mod addr;
pub mod admin;
pub mod code;
pub mod context;
pub mod coord;
pub mod i18n_properties;
pub mod poi;
pub mod stop;
pub mod street;

pub mod utils;

use addr::Addr;
use admin::Admin;
use poi::Poi;
use stop::Stop;
use street::Street;

/// Object stored in Elasticsearch
#[allow(clippy::large_enum_variant)]
#[derive(Deserialize, Debug, Clone)]
#[serde(rename_all = "snake_case", tag = "type")]
pub enum Place {
    Admin(Admin),
    Street(Street),
    Addr(Addr),
    Poi(Poi),
    Stop(Stop),
}

/// There are two kinds of addresses:
/// Note that the enum is 'untagged' with regards to serde because
/// each of `Addr` and `Street` already has a 'type' field.
#[allow(clippy::large_enum_variant)]
#[derive(Serialize, Deserialize, Debug, Clone)]
#[serde(rename_all = "snake_case", untagged)]
pub enum Address {
    Street(Street),
    Addr(Addr),
}

impl Place {
    pub fn is_admin(&self) -> bool {
        matches!(self, Place::Admin(_))
    }

    pub fn is_street(&self) -> bool {
        matches!(self, Place::Street(_))
    }

    pub fn is_addr(&self) -> bool {
        matches!(self, Place::Addr(_))
    }

    pub fn is_poi(&self) -> bool {
        matches!(self, Place::Poi(_))
    }

    pub fn is_stop(&self) -> bool {
        matches!(self, Place::Stop(_))
    }

    pub fn poi(&self) -> Option<&Poi> {
        match *self {
            Place::Poi(ref poi) => Some(poi),
            _ => None,
        }
    }

    pub fn id(&self) -> &str {
        match *self {
            Place::Admin(ref o) => &o.id,
            Place::Street(ref o) => &o.id,
            Place::Addr(ref o) => &o.id,
            Place::Poi(ref o) => &o.id,
            Place::Stop(ref o) => &o.id,
        }
    }

    pub fn label(&self) -> &str {
        match *self {
            Place::Admin(ref o) => o.label(),
            Place::Street(ref o) => o.label(),
            Place::Addr(ref o) => o.label(),
            Place::Poi(ref o) => o.label(),
            Place::Stop(ref o) => o.label(),
        }
    }

    pub fn admins(&self) -> Vec<Arc<Admin>> {
        match *self {
            Place::Admin(ref o) => o.admins(),
            Place::Street(ref o) => o.admins(),
            Place::Addr(ref o) => o.admins(),
            Place::Poi(ref o) => o.admins(),
            Place::Stop(ref o) => o.admins(),
        }
    }

    pub fn address(&self) -> Option<Address> {
        match *self {
            Place::Admin(_) => None,
            Place::Street(ref o) => Some(Address::Street(o.clone())),
            Place::Addr(ref o) => Some(Address::Addr(o.clone())),
            Place::Poi(_) => None,
            Place::Stop(_) => None,
        }
    }

    pub fn distance(&self) -> Option<u32> {
        match *self {
            Place::Admin(ref o) => o.distance,
            Place::Street(ref o) => o.distance,
            Place::Addr(ref o) => o.distance,
            Place::Poi(ref o) => o.distance,
            Place::Stop(ref o) => o.distance,
        }
    }

    pub fn set_distance(&mut self, d: u32) {
        match self {
            Place::Admin(ref mut o) => o.distance = Some(d),
            Place::Street(ref mut o) => o.distance = Some(d),
            Place::Addr(ref mut o) => o.distance = Some(d),
            Place::Poi(ref mut o) => o.distance = Some(d),
            Place::Stop(ref mut o) => o.distance = Some(d),
        }
    }

    pub fn coord(&self) -> &coord::Coord {
        match self {
            Place::Admin(ref o) => &o.coord,
            Place::Street(ref o) => &o.coord,
            Place::Addr(ref o) => &o.coord,
            Place::Poi(ref o) => &o.coord,
            Place::Stop(ref o) => &o.coord,
        }
    }

    pub fn set_context(&mut self, context: context::Context) {
        match self {
            Place::Admin(ref mut o) => o.context = Some(context),
            Place::Street(ref mut o) => o.context = Some(context),
            Place::Addr(ref mut o) => o.context = Some(context),
            Place::Poi(ref mut o) => o.context = Some(context),
            Place::Stop(ref mut o) => o.context = Some(context),
        }
    }

    /* We can afford to clone the context because we're in debug mode
     * and performance are less critical */
    pub fn context(&self) -> Option<context::Context> {
        match self {
            Place::Admin(ref o) => o.context.clone(),
            Place::Street(ref o) => o.context.clone(),
            Place::Addr(ref o) => o.context.clone(),
            Place::Poi(ref o) => o.context.clone(),
            Place::Stop(ref o) => o.context.clone(),
        }
    }
}

// This is a bit of a kludge to a get a string version for the doc_type.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum PlaceDocType {
    Admin,
    Street,
    Addr,
    Poi,
    Stop,
}

impl PlaceDocType {
    pub fn as_str(&self) -> &'static str {
        match self {
            PlaceDocType::Admin => "admin",
            PlaceDocType::Street => "street",
            PlaceDocType::Addr => "addr",
            PlaceDocType::Poi => "poi",
            PlaceDocType::Stop => "stop",
        }
    }
}

pub trait Members {
    fn label(&self) -> &str;
    fn admins(&self) -> Vec<Arc<Admin>>;
}

#[derive(Serialize, Deserialize, Debug, Clone, Hash, Eq, PartialEq, Ord, PartialOrd, Default)]
pub struct Property {
    pub key: String,
    pub value: String,
}

impl From<navitia_poi_model::Property> for Property {
    fn from(property: navitia_poi_model::Property) -> Property {
        Property {
            key: property.key,
            value: property.value,
        }
    }
}

impl From<&Place> for geojson::Geometry {
    fn from(place: &Place) -> Self {
        match place {
            Place::Admin(admin) => geojson::Geometry::from(admin),
            Place::Street(street) => geojson::Geometry::from(street),
            Place::Addr(addr) => geojson::Geometry::from(addr),
            Place::Poi(poi) => geojson::Geometry::from(poi),
            Place::Stop(stop) => geojson::Geometry::from(stop),
        }
    }
}
<|endoftext|>