<commit_before>//! Client Requests
use std::io::{BufferedWriter, IoResult};

use url::Url;

use method::{mod, Get, Post, Delete, Put, Patch, Head, Options};
use header::Headers;
use header::common::{mod, Host};
use net::{NetworkStream, HttpStream, Fresh, Streaming};
use http::{HttpWriter, ThroughWriter, ChunkedWriter, SizedWriter, LINE_ENDING};
use version;
use {HttpResult, HttpUriError};
use client::Response;

/// A client request to a remote server.
pub struct Request<W> {
    /// The target URI for this request.
    pub url: Url,

    /// The HTTP version of this request.
    pub version: version::HttpVersion,

    body: HttpWriter<BufferedWriter<Box<NetworkStream + Send>>>,
    headers: Headers,
    method: method::Method,
}

impl<W> Request<W> {
    /// Read the Request headers.
    #[inline]
    pub fn headers(&self) -> &Headers { &self.headers }

    /// Read the Request method.
    #[inline]
    pub fn method(&self) -> method::Method { self.method.clone() }
}

impl Request<Fresh> {
    /// Create a new client request.
    pub fn new(method: method::Method, url: Url) -> HttpResult<Request<Fresh>> {
        Request::with_stream::<HttpStream>(method, url)
    }

    /// Create a new client request with a specific underlying NetworkStream.
    pub fn with_stream<S: NetworkStream>(method: method::Method, url: Url) -> HttpResult<Request<Fresh>> {
        debug!("{} {}", method, url);
        let host = match url.serialize_host() {
            Some(host) => host,
            None => return Err(HttpUriError)
        };
        debug!("host={}", host);
        let port = match url.port_or_default() {
            Some(port) => port,
            None => return Err(HttpUriError)
        };
        debug!("port={}", port);

        let stream: S = try_io!(NetworkStream::connect(host.as_slice(), port, url.scheme.as_slice()));
        let stream = ThroughWriter(BufferedWriter::new(stream.dynamic()));
        let mut headers = Headers::new();
        headers.set(Host(host));

        Ok(Request {
            method: method,
            headers: headers,
            url: url,
            version: version::Http11,
            body: stream
        })
    }

    /// Create a new GET request.
    #[inline]
    pub fn get(url: Url) -> HttpResult<Request<Fresh>> { Request::new(Get, url) }

    /// Create a new POST request.
    #[inline]
    pub fn post(url: Url) -> HttpResult<Request<Fresh>> { Request::new(Post, url) }

    /// Create a new DELETE request.
    #[inline]
    pub fn delete(url: Url) -> HttpResult<Request<Fresh>> { Request::new(Delete, url) }

    /// Create a new PUT request.
    #[inline]
    pub fn put(url: Url) -> HttpResult<Request<Fresh>> { Request::new(Put, url) }

    /// Create a new PATCH request.
    #[inline]
    pub fn patch(url: Url) -> HttpResult<Request<Fresh>> { Request::new(Patch, url) }

    /// Create a new HEAD request.
    #[inline]
    pub fn head(url: Url) -> HttpResult<Request<Fresh>> { Request::new(Head, url) }

    /// Create a new OPTIONS request.
    #[inline]
    pub fn options(url: Url) -> HttpResult<Request<Fresh>> { Request::new(Options, url) }

    /// Consume a Fresh Request, writing the headers and method,
    /// returning a Streaming Request.
    pub fn start(mut self) -> HttpResult<Request<Streaming>> {
        let mut uri = self.url.serialize_path().unwrap();
        //TODO: this needs a test
        if let Some(ref q) = self.url.query {
            uri.push('?');
            uri.push_str(q[]);
        }

        debug!("writing head: {} {} {}", self.method, uri, self.version);
        try_io!(write!(self.body, "{} {} {}", self.method, uri, self.version))
        try_io!(self.body.write(LINE_ENDING));

        let mut chunked = true;
        let mut len = 0;

        match self.headers.get::<common::ContentLength>() {
            Some(cl) => {
                chunked = false;
                len = cl.len();
            },
            None => ()
        };

        // cant do in match above, thanks borrowck
        if chunked {
            let encodings = match self.headers.get_mut::<common::TransferEncoding>() {
                Some(&common::TransferEncoding(ref mut encodings)) => {
                    //TODO: check if chunked is already in encodings. use HashSet?
                    encodings.push(common::transfer_encoding::Chunked);
                    false
                },
                None => true
            };

            if encodings {
                self.headers.set::<common::TransferEncoding>(
                    common::TransferEncoding(vec![common::transfer_encoding::Chunked]))
            }
        }

        debug!("headers [\n{}]", self.headers);
        try_io!(write!(self.body, "{}", self.headers));

        try_io!(self.body.write(LINE_ENDING));

        let stream = if chunked {
            ChunkedWriter(self.body.unwrap())
        } else {
            SizedWriter(self.body.unwrap(), len)
        };

        Ok(Request {
            method: self.method,
            headers: self.headers,
            url: self.url,
            version: self.version,
            body: stream
        })
    }

    /// Get a mutable reference to the Request headers.
    #[inline]
    pub fn headers_mut(&mut self) -> &mut Headers { &mut self.headers }
}

impl Request<Streaming> {
    /// Completes writing the request, and returns a response to read from.
    ///
    /// Consumes the Request.
    pub fn send(self) -> HttpResult<Response> {
        let raw = try_io!(self.body.end()).unwrap();
        Response::new(raw)
    }
}

impl Writer for Request<Streaming> {
    #[inline]
    fn write(&mut self, msg: &[u8]) -> IoResult<()> {
        self.body.write(msg)
    }

    #[inline]
    fn flush(&mut self) -> IoResult<()> {
        self.body.flush()
    }
}
<commit_msg>Include port in Host header<commit_after>//! Client Requests
use std::io::{BufferedWriter, IoResult};

use url::Url;

use method::{mod, Get, Post, Delete, Put, Patch, Head, Options};
use header::Headers;
use header::common::{mod, Host};
use net::{NetworkStream, HttpStream, Fresh, Streaming};
use http::{HttpWriter, ThroughWriter, ChunkedWriter, SizedWriter, LINE_ENDING};
use version;
use {HttpResult, HttpUriError};
use client::Response;

/// A client request to a remote server.
pub struct Request<W> {
    /// The target URI for this request.
    pub url: Url,

    /// The HTTP version of this request.
    pub version: version::HttpVersion,

    body: HttpWriter<BufferedWriter<Box<NetworkStream + Send>>>,
    headers: Headers,
    method: method::Method,
}

impl<W> Request<W> {
    /// Read the Request headers.
    #[inline]
    pub fn headers(&self) -> &Headers { &self.headers }

    /// Read the Request method.
    #[inline]
    pub fn method(&self) -> method::Method { self.method.clone() }
}

impl Request<Fresh> {
    /// Create a new client request.
    pub fn new(method: method::Method, url: Url) -> HttpResult<Request<Fresh>> {
        Request::with_stream::<HttpStream>(method, url)
    }

    /// Create a new client request with a specific underlying NetworkStream.
    pub fn with_stream<S: NetworkStream>(method: method::Method, url: Url) -> HttpResult<Request<Fresh>> {
        debug!("{} {}", method, url);
        let host = match url.serialize_host() {
            Some(host) => host,
            None => return Err(HttpUriError)
        };
        debug!("host={}", host);
        let port = match url.port_or_default() {
            Some(port) => port,
            None => return Err(HttpUriError)
        };
        debug!("port={}", port);

        let stream: S = try_io!(NetworkStream::connect(host.as_slice(), port, url.scheme.as_slice()));
        let stream = ThroughWriter(BufferedWriter::new(stream.dynamic()));
        let mut headers = Headers::new();
        headers.set(Host(format!("{}:{}", host, port)));

        Ok(Request {
            method: method,
            headers: headers,
            url: url,
            version: version::Http11,
            body: stream
        })
    }

    /// Create a new GET request.
    #[inline]
    pub fn get(url: Url) -> HttpResult<Request<Fresh>> { Request::new(Get, url) }

    /// Create a new POST request.
    #[inline]
    pub fn post(url: Url) -> HttpResult<Request<Fresh>> { Request::new(Post, url) }

    /// Create a new DELETE request.
    #[inline]
    pub fn delete(url: Url) -> HttpResult<Request<Fresh>> { Request::new(Delete, url) }

    /// Create a new PUT request.
    #[inline]
    pub fn put(url: Url) -> HttpResult<Request<Fresh>> { Request::new(Put, url) }

    /// Create a new PATCH request.
    #[inline]
    pub fn patch(url: Url) -> HttpResult<Request<Fresh>> { Request::new(Patch, url) }

    /// Create a new HEAD request.
    #[inline]
    pub fn head(url: Url) -> HttpResult<Request<Fresh>> { Request::new(Head, url) }

    /// Create a new OPTIONS request.
    #[inline]
    pub fn options(url: Url) -> HttpResult<Request<Fresh>> { Request::new(Options, url) }

    /// Consume a Fresh Request, writing the headers and method,
    /// returning a Streaming Request.
    pub fn start(mut self) -> HttpResult<Request<Streaming>> {
        let mut uri = self.url.serialize_path().unwrap();
        //TODO: this needs a test
        if let Some(ref q) = self.url.query {
            uri.push('?');
            uri.push_str(q[]);
        }

        debug!("writing head: {} {} {}", self.method, uri, self.version);
        try_io!(write!(self.body, "{} {} {}", self.method, uri, self.version))
        try_io!(self.body.write(LINE_ENDING));

        let mut chunked = true;
        let mut len = 0;

        match self.headers.get::<common::ContentLength>() {
            Some(cl) => {
                chunked = false;
                len = cl.len();
            },
            None => ()
        };

        // cant do in match above, thanks borrowck
        if chunked {
            let encodings = match self.headers.get_mut::<common::TransferEncoding>() {
                Some(&common::TransferEncoding(ref mut encodings)) => {
                    //TODO: check if chunked is already in encodings. use HashSet?
                    encodings.push(common::transfer_encoding::Chunked);
                    false
                },
                None => true
            };

            if encodings {
                self.headers.set::<common::TransferEncoding>(
                    common::TransferEncoding(vec![common::transfer_encoding::Chunked]))
            }
        }

        debug!("headers [\n{}]", self.headers);
        try_io!(write!(self.body, "{}", self.headers));

        try_io!(self.body.write(LINE_ENDING));

        let stream = if chunked {
            ChunkedWriter(self.body.unwrap())
        } else {
            SizedWriter(self.body.unwrap(), len)
        };

        Ok(Request {
            method: self.method,
            headers: self.headers,
            url: self.url,
            version: self.version,
            body: stream
        })
    }

    /// Get a mutable reference to the Request headers.
    #[inline]
    pub fn headers_mut(&mut self) -> &mut Headers { &mut self.headers }
}

impl Request<Streaming> {
    /// Completes writing the request, and returns a response to read from.
    ///
    /// Consumes the Request.
    pub fn send(self) -> HttpResult<Response> {
        let raw = try_io!(self.body.end()).unwrap();
        Response::new(raw)
    }
}

impl Writer for Request<Streaming> {
    #[inline]
    fn write(&mut self, msg: &[u8]) -> IoResult<()> {
        self.body.write(msg)
    }

    #[inline]
    fn flush(&mut self) -> IoResult<()> {
        self.body.flush()
    }
}

#[cfg(test)]
mod tests {
    use header::common::Host;
    use method::Get;
    use net::MockStream;
    use url::Url;
    use super::Request;

    #[test]
    fn test_host_header() {
        fn check_host(url: &str, host_header: &str) {
            let request = Request::with_stream::<MockStream>(
                Get,
                Url::parse(url).unwrap(),
            ).unwrap();

            assert_eq!(
                &Host(host_header.to_string()),
                request.headers().get::<Host>().unwrap()
            );
        }

        check_host("http://www.example.com/path", "www.example.com:80");
        check_host("https://www.example.com/path", "www.example.com:443");
        check_host("http://www.example.com:8080/path", "www.example.com:8080");
    }
}
<|endoftext|>


<commit_before>//! A simple program to fetch two HTTP pages in parallel
//!
//! This exfample will fetch the rust-lang home page as well as GitHub's home
//! page. Both transfers are executed in parallel one thread using futures.

extern crate env_logger;
extern crate curl;
extern crate futures;
extern crate futures_curl;
extern crate futures_mio;

use curl::easy::Easy;
use futures::Future;
use futures_mio::Loop;
use futures_curl::Session;

fn main() {
    env_logger::init().unwrap();

    let mut lp = Loop::new().unwrap();
    let session = Session::new(lp.handle());

    // Once we've got our session available to us, execute our two requests.
    // Each request will be a GET request and for now we just ignore the actual
    // downloaded data.
    let requests = session.and_then(|sess| {
        let mut a = Easy::new();
        a.get(true).unwrap();
        a.url("https://www.rust-lang.org").unwrap();
        a.write_function(|data| Ok(data.len())).unwrap();

        let mut b = Easy::new();
        b.get(true).unwrap();
        b.url("https://github.com").unwrap();
        b.write_function(|data| Ok(data.len())).unwrap();

        sess.perform(a).join(sess.perform(b))
    });

    // Run both requests, waiting for them to finish. Once done we print out
    // their response codes and errors.
    let ((mut a, aerr), (mut b, berr)) = lp.run(requests).unwrap();
    println!("{:?} {:?}", a.response_code(), aerr);
    println!("{:?} {:?}", b.response_code(), berr);
}
<commit_msg>Fixed a typo.<commit_after>//! A simple program to fetch two HTTP pages in parallel
//!
//! This example will fetch the rust-lang home page as well as GitHub's home
//! page. Both transfers are executed in parallel one thread using futures.

extern crate env_logger;
extern crate curl;
extern crate futures;
extern crate futures_curl;
extern crate futures_mio;

use curl::easy::Easy;
use futures::Future;
use futures_mio::Loop;
use futures_curl::Session;

fn main() {
    env_logger::init().unwrap();

    let mut lp = Loop::new().unwrap();
    let session = Session::new(lp.handle());

    // Once we've got our session available to us, execute our two requests.
    // Each request will be a GET request and for now we just ignore the actual
    // downloaded data.
    let requests = session.and_then(|sess| {
        let mut a = Easy::new();
        a.get(true).unwrap();
        a.url("https://www.rust-lang.org").unwrap();
        a.write_function(|data| Ok(data.len())).unwrap();

        let mut b = Easy::new();
        b.get(true).unwrap();
        b.url("https://github.com").unwrap();
        b.write_function(|data| Ok(data.len())).unwrap();

        sess.perform(a).join(sess.perform(b))
    });

    // Run both requests, waiting for them to finish. Once done we print out
    // their response codes and errors.
    let ((mut a, aerr), (mut b, berr)) = lp.run(requests).unwrap();
    println!("{:?} {:?}", a.response_code(), aerr);
    println!("{:?} {:?}", b.response_code(), berr);
}
<|endoftext|>


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

use std::gc::GC;
use std::iter::FromIterator;
use syntax::ast;
use syntax::ast::P;
use syntax::codemap::{respan, mk_sp};
use syntax::ext::base::ExtCtxt;
use syntax::ext::build::AstBuilder;
use syntax::ext::quote::rt::ToTokens;
use syntax::parse::token;

use super::Builder;
use super::utils;
use super::super::node;

/// A visitor to build the struct for each register
pub struct BuildRegStructs<'a, 'b, 'c> {
  builder: &'a mut Builder,
  cx: &'b ExtCtxt<'c>,
}

impl<'a, 'b, 'c> node::RegVisitor for BuildRegStructs<'a, 'b, 'c> {
  fn visit_prim_reg(&mut self, path: &Vec<String>, reg: &node::Reg,
                    width: node::RegWidth, fields: &Vec<node::Field>) {
    for field in fields.iter() {
      match build_field_type(self.cx, path, reg, field) {
        Some(item) => self.builder.push_item(item),
        None       => {}
      }
    }

    let reg_struct = build_reg_struct(self.cx, path, reg, width);
    self.builder.push_item(reg_struct);
  }
}

impl<'a, 'b, 'c> BuildRegStructs<'a, 'b, 'c> {
  pub fn new(builder: &'a mut Builder, cx: &'b ExtCtxt<'c>)
             -> BuildRegStructs<'a, 'b, 'c> {
    BuildRegStructs {builder: builder, cx: cx}
  }
}

/// Build a field type if necessary (e.g. in the case of an `EnumField`)
fn build_field_type<'a>(cx: &'a ExtCtxt, path: &Vec<String>,
                        reg: &node::Reg, field: &node::Field)
                        -> Option<P<ast::Item>> {
  match field.ty.node {
    node::EnumField { variants: ref variants, .. } => {
      // FIXME(bgamari): We construct a path, then only take the last
      // segment, this could be more efficient
      let name: ast::Ident =
        utils::field_type_path(cx, path, reg, field)
        .segments.last().unwrap().identifier;
      let enum_def: ast::EnumDef = ast::EnumDef {
        variants: FromIterator::from_iter(
          variants.iter().map(|v| box(GC) build_enum_variant(cx, v))),
      };
      let attrs: Vec<ast::Attribute> = vec!(
        utils::list_attribute(cx, "deriving", vec!("FromPrimitive")),
        utils::list_attribute(cx, "allow",
                              vec!("uppercase_variables",
                                   "dead_code",
                                   "non_camel_case_types")));
      let item: P<ast::Item> = box(GC) ast::Item {
        ident: name,
        id: ast::DUMMY_NODE_ID,
        node: ast::ItemEnum(enum_def, utils::no_generics()),
        vis: ast::Public,
        attrs: attrs,
        span: field.ty.span,
      };
      Some(item)
    },
    _ => None,
  }
}

/// Produce a register struct if necessary (for primitive typed registers).
/// In this case `None` indicates no struct is necessary, not failure.
/// For instance,
///
///     pub struct REG {_value: u32}
fn build_reg_struct<'a>(cx: &'a ExtCtxt, path: &Vec<String>,
    reg: &node::Reg, _width: node::RegWidth) -> P<ast::Item> {
  let packed_ty =
    utils::reg_primitive_type(cx, reg)
    .expect("Unexpected non-primitive reg");

  let reg_doc = match reg.docstring {
    Some(d) => token::get_ident(d.node).get().into_string(),
    None => "no documentation".into_string(),
  };
  let docstring = format!("Register `{}`: {}",
                          reg.name.node,
                          reg_doc);
  let doc_attr = utils::doc_attribute(cx, utils::intern_string(cx, docstring));

  let ty_name = utils::path_ident(cx, path);
  let item = quote_item!(cx,
    $doc_attr
    #[allow(non_camel_case_types)]
    pub struct $ty_name {
      value: VolatileCell<$packed_ty>,
    }
  );
  item.unwrap()
}

/// Build a variant of an `EnumField`
fn build_enum_variant<'a>(cx: &'a ExtCtxt,
                          variant: &node::Variant) -> ast::Variant {
  let doc = match variant.docstring {
    Some(d) => token::get_ident(d.node).get().into_string(),
    None => "no documentation".into_string(),
  };
  let docstring = format!("`0x{:x}`. {}",
                          variant.value.node,
                          doc);
  let doc_attr = utils::doc_attribute(cx, utils::intern_string(cx, docstring));
  respan(
    mk_sp(variant.name.span.lo, variant.value.span.hi),
    ast::Variant_ {
      name: cx.ident_of(variant.name.node.as_slice()),
      attrs: vec!(doc_attr),
      kind: ast::TupleVariantKind(Vec::new()),
      id: ast::DUMMY_NODE_ID,
      disr_expr: Some(utils::expr_int(cx, variant.value.node as i64)),
      vis: ast::Inherited,
    }
  )
}
<commit_msg>ioreg: Allow enums to lack documentation<commit_after>// Zinc, the bare metal stack for rust.
// Copyright 2014 Ben Gamari <bgamari@gmail.com>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

use std::gc::GC;
use std::iter::FromIterator;
use syntax::ast;
use syntax::ast::P;
use syntax::codemap::{respan, mk_sp};
use syntax::ext::base::ExtCtxt;
use syntax::ext::build::AstBuilder;
use syntax::ext::quote::rt::ToTokens;
use syntax::parse::token;

use super::Builder;
use super::utils;
use super::super::node;

/// A visitor to build the struct for each register
pub struct BuildRegStructs<'a, 'b, 'c> {
  builder: &'a mut Builder,
  cx: &'b ExtCtxt<'c>,
}

impl<'a, 'b, 'c> node::RegVisitor for BuildRegStructs<'a, 'b, 'c> {
  fn visit_prim_reg(&mut self, path: &Vec<String>, reg: &node::Reg,
                    width: node::RegWidth, fields: &Vec<node::Field>) {
    for field in fields.iter() {
      match build_field_type(self.cx, path, reg, field) {
        Some(item) => self.builder.push_item(item),
        None       => {}
      }
    }

    let reg_struct = build_reg_struct(self.cx, path, reg, width);
    self.builder.push_item(reg_struct);
  }
}

impl<'a, 'b, 'c> BuildRegStructs<'a, 'b, 'c> {
  pub fn new(builder: &'a mut Builder, cx: &'b ExtCtxt<'c>)
             -> BuildRegStructs<'a, 'b, 'c> {
    BuildRegStructs {builder: builder, cx: cx}
  }
}

/// Build a field type if necessary (e.g. in the case of an `EnumField`)
fn build_field_type<'a>(cx: &'a ExtCtxt, path: &Vec<String>,
                        reg: &node::Reg, field: &node::Field)
                        -> Option<P<ast::Item>> {
  match field.ty.node {
    node::EnumField { variants: ref variants, .. } => {
      // FIXME(bgamari): We construct a path, then only take the last
      // segment, this could be more efficient
      let name: ast::Ident =
        utils::field_type_path(cx, path, reg, field)
        .segments.last().unwrap().identifier;
      let enum_def: ast::EnumDef = ast::EnumDef {
        variants: FromIterator::from_iter(
          variants.iter().map(|v| box(GC) build_enum_variant(cx, v))),
      };
      let attrs: Vec<ast::Attribute> = vec!(
        utils::list_attribute(cx, "deriving", vec!("FromPrimitive")),
        utils::list_attribute(cx, "allow",
                              vec!("uppercase_variables",
                                   "dead_code",
                                   "non_camel_case_types",
                                   "missing_doc")));
      let item: P<ast::Item> = box(GC) ast::Item {
        ident: name,
        id: ast::DUMMY_NODE_ID,
        node: ast::ItemEnum(enum_def, utils::no_generics()),
        vis: ast::Public,
        attrs: attrs,
        span: field.ty.span,
      };
      Some(item)
    },
    _ => None,
  }
}

/// Produce a register struct if necessary (for primitive typed registers).
/// In this case `None` indicates no struct is necessary, not failure.
/// For instance,
///
///     pub struct REG {_value: u32}
fn build_reg_struct<'a>(cx: &'a ExtCtxt, path: &Vec<String>,
    reg: &node::Reg, _width: node::RegWidth) -> P<ast::Item> {
  let packed_ty =
    utils::reg_primitive_type(cx, reg)
    .expect("Unexpected non-primitive reg");

  let reg_doc = match reg.docstring {
    Some(d) => token::get_ident(d.node).get().into_string(),
    None => "no documentation".into_string(),
  };
  let docstring = format!("Register `{}`: {}",
                          reg.name.node,
                          reg_doc);
  let doc_attr = utils::doc_attribute(cx, utils::intern_string(cx, docstring));

  let ty_name = utils::path_ident(cx, path);
  let item = quote_item!(cx,
    $doc_attr
    #[allow(non_camel_case_types)]
    pub struct $ty_name {
      value: VolatileCell<$packed_ty>,
    }
  );
  item.unwrap()
}

/// Build a variant of an `EnumField`
fn build_enum_variant<'a>(cx: &'a ExtCtxt,
                          variant: &node::Variant) -> ast::Variant {
  let doc = match variant.docstring {
    Some(d) => token::get_ident(d.node).get().into_string(),
    None => "no documentation".into_string(),
  };
  let docstring = format!("`0x{:x}`. {}",
                          variant.value.node,
                          doc);
  let doc_attr = utils::doc_attribute(cx, utils::intern_string(cx, docstring));
  respan(
    mk_sp(variant.name.span.lo, variant.value.span.hi),
    ast::Variant_ {
      name: cx.ident_of(variant.name.node.as_slice()),
      attrs: vec!(doc_attr),
      kind: ast::TupleVariantKind(Vec::new()),
      id: ast::DUMMY_NODE_ID,
      disr_expr: Some(utils::expr_int(cx, variant.value.node as i64)),
      vis: ast::Inherited,
    }
  )
}
<|endoftext|>


<commit_before>//! An UDP echo server that just sends back everything that it receives.
//!
//! If you're on unix you can test this out by in one terminal executing:
//!
//! ```sh
//! $ cargo run --example echo-udp
//! ```
//!
//! and in another terminal you can run:
//!
//! ```sh
//! $ nc -u localhost 8080
//! ```
//!
//! Each line you type in to the `nc` terminal should be echo'd back to you!

extern crate futures;
#[macro_use]
extern crate tokio_core;

use std::{env, io};
use std::net::SocketAddr;

use futures::{Future, Poll};
use tokio_core::net::UdpSocket;
use tokio_core::reactor::Core;

struct Server {
    socket: UdpSocket,
    buf: Vec<u8>,
    to_send: Option<(usize, SocketAddr)>,
}

impl Future for Server {
    type Item = ();
    type Error = io::Error;

    fn poll(&mut self) -> Poll<(), io::Error> {
        loop {
            // First we check to see if there's a message we need to echo back.
            // If so then we try to send it back to the original source, waiting
            // until we're writable and able to do so.
            if let Some((size, peer)) = self.to_send {
                let amt = try_nb!(self.socket.send_to(&self.buf[..size], &peer));
                println!("Echoed {}/{} bytes to {}", amt, size, peer);
                self.to_send = None;
            }

            // If we're here then `to_send` is `None`, so we take a look for the
            // next message we're going to echo back.
            self.to_send = Some(try_nb!(self.socket.recv_from(&mut self.buf)));
        }
    }
}

fn main() {
    let addr = env::args().nth(1).unwrap_or("127.0.0.1:8080".to_string());
    let addr = addr.parse::<SocketAddr>().unwrap();

    // Create the event loop that will drive this server, and also bind the
    // socket we'll be listening to.
    let mut l = Core::new().unwrap();
    let handle = l.handle();
    let socket = UdpSocket::bind(&addr, &handle).unwrap();
    println!("Listening on: {}", addr);

    // Next we'll create a future to spawn (the one we defined above) and then
    // we'll run the event loop by running the future.
    l.run(Server {
        socket: socket,
        buf: vec![0; 1024],
        to_send: None,
    }).unwrap();
}
<commit_msg>Correct client invocation example<commit_after>//! An UDP echo server that just sends back everything that it receives.
//!
//! If you're on unix you can test this out by in one terminal executing:
//!
//! ```sh
//! $ cargo run --example echo-udp
//! ```
//!
//! and in another terminal you can run:
//!
//! ```sh
//! $ echo -n "hello" | nc -4u localhost 8080
//! ```
//!
//! Each line you type in to the `nc` terminal should be echo'd back to you!

extern crate futures;
#[macro_use]
extern crate tokio_core;

use std::{env, io};
use std::net::SocketAddr;

use futures::{Future, Poll};
use tokio_core::net::UdpSocket;
use tokio_core::reactor::Core;

struct Server {
    socket: UdpSocket,
    buf: Vec<u8>,
    to_send: Option<(usize, SocketAddr)>,
}

impl Future for Server {
    type Item = ();
    type Error = io::Error;

    fn poll(&mut self) -> Poll<(), io::Error> {
        loop {
            // First we check to see if there's a message we need to echo back.
            // If so then we try to send it back to the original source, waiting
            // until we're writable and able to do so.
            if let Some((size, peer)) = self.to_send {
                let amt = try_nb!(self.socket.send_to(&self.buf[..size], &peer));
                println!("Echoed {}/{} bytes to {}", amt, size, peer);
                self.to_send = None;
            }

            // If we're here then `to_send` is `None`, so we take a look for the
            // next message we're going to echo back.
            self.to_send = Some(try_nb!(self.socket.recv_from(&mut self.buf)));
        }
    }
}

fn main() {
    let addr = env::args().nth(1).unwrap_or("127.0.0.1:8080".to_string());
    let addr = addr.parse::<SocketAddr>().unwrap();

    // Create the event loop that will drive this server, and also bind the
    // socket we'll be listening to.
    let mut l = Core::new().unwrap();
    let handle = l.handle();
    let socket = UdpSocket::bind(&addr, &handle).unwrap();
    println!("Listening on: {}", addr);

    // Next we'll create a future to spawn (the one we defined above) and then
    // we'll run the event loop by running the future.
    l.run(Server {
        socket: socket,
        buf: vec![0; 1024],
        to_send: None,
    }).unwrap();
}
<|endoftext|>


<commit_before>use serenity::prelude::*;
use serenity::framework::standard::Args;
use serenity::voice;

command!(join(ctx, msg) {
    let mut target = msg.author.id;

    if msg.mentions.len() >= 1 {
        target = msg.mentions[0].id;
    }

    let channel = msg.guild().and_then(|guild| {
        let mut result = None;
        for (_, vs) in guild.read().unwrap().voice_states.iter() {
            if target == vs.user_id {
                result = vs.channel_id;
            }
        }
        result
    });

    let connect_to = match channel {
        Some(id) => id,
        None => {
            let _ = msg.channel_id.say("You need to join a voice channel first");
            return Ok(());
        }
    };

    let guild_id = match msg.guild_id() {
        Some(id) => id,
        None => {
            let _ = msg.channel_id.say("Groups and DMs not supported");
            return Ok(());
        }
    };

    let mut shard = ctx.shard.lock();
    shard.manager.join(guild_id, connect_to);

    let _ = msg.channel_id.say(&format!("Joined {}", connect_to.mention()));
});

command!(leave(ctx, msg) {
    let guild_id = match msg.guild_id() {
        Some(id) => id,
        None => {
            let _ = msg.channel_id.say("Groups and DMs not supported");
            return Ok(());
        }
    };

    let mut shard = ctx.shard.lock();
    let has_handler = shard.manager.get(guild_id).is_some();

    if has_handler {
        shard.manager.remove(guild_id);
        let _ = msg.channel_id.say("Left voice channel");
    } else {
        let _ = msg.channel_id.say("Not in a voice channel");
    }
});

command!(play(ctx, msg, args) {
    let guild_id = match msg.guild_id() {
        Some(id) => id,
        None => {
            let _ = msg.channel_id.say("Error finding guild id");
            return Ok(());
        }
    };

    let default_path = ".\\audio\\airhorn.dca";

    let path = match args.get(0) {
        Some(path) => path,
        None => default_path,
    };

    if let Some(handler) = ctx.shard.lock().manager.get(guild_id) {
        let source = match voice::dca(path) {
            Ok(source) => source,
            Err(why) => {
                println!("Err starting source: {:?}", why);

                let _ = msg.channel_id.say("Couldn't find file");

                return Ok(());
            },
        };

        handler.play(source);

        let _ = msg.channel_id.say("Playing");
    } else {
        let _ = msg.channel_id.say("Not in a voice channel");
    }
});

command!(airhorn(ctx, msg, _args) {
    let _ = play(ctx, msg, Args::new(".\\audio\\airhorn.dca", ","));
});

command!(patrick(ctx, msg, _args) {
    let _ = play(ctx, msg, Args::new(".\\audio\\patrick.dca", ","));
});<commit_msg>Play command accepts options for files<commit_after>use serenity::prelude::*;
use serenity::framework::standard::Args;
use serenity::voice;
use std::collections::HashMap;

command!(join(ctx, msg) {
    let mut target = msg.author.id;

    if msg.mentions.len() >= 1 {
        target = msg.mentions[0].id;
    }

    let channel = msg.guild().and_then(|guild| {
        let mut result = None;
        for (_, vs) in guild.read().unwrap().voice_states.iter() {
            if target == vs.user_id {
                result = vs.channel_id;
            }
        }
        result
    });

    let connect_to = match channel {
        Some(id) => id,
        None => {
            let _ = msg.channel_id.say("You need to join a voice channel first");
            return Ok(());
        }
    };

    let guild_id = match msg.guild_id() {
        Some(id) => id,
        None => {
            let _ = msg.channel_id.say("Groups and DMs not supported");
            return Ok(());
        }
    };

    let mut shard = ctx.shard.lock();
    shard.manager.join(guild_id, connect_to);

    let _ = msg.channel_id.say(&format!("Joined {}", connect_to.mention()));
});

command!(leave(ctx, msg) {
    let guild_id = match msg.guild_id() {
        Some(id) => id,
        None => {
            let _ = msg.channel_id.say("Groups and DMs not supported");
            return Ok(());
        }
    };

    let mut shard = ctx.shard.lock();
    let has_handler = shard.manager.get(guild_id).is_some();

    if has_handler {
        shard.manager.remove(guild_id);
        let _ = msg.channel_id.say("Left voice channel");
    } else {
        let _ = msg.channel_id.say("Not in a voice channel");
    }
});

command!(play(ctx, msg, args) {
    let sounds: HashMap<&str, &str> =
        [("airhorn", ".\\audio\\airhorn.dca"),
         ("patrick", ".\\audio\\patrick.dca")]
         .iter().cloned().collect();

    let guild_id = match msg.guild_id() {
        Some(id) => id,
        None => {
            let _ = msg.channel_id.say("Error finding guild id");
            return Ok(());
        }
    };

    let sound = match args.get(0) {
        Some(sound) => sound,
        None => "airhorn",
    };

    let path = match sounds.get(sound) {
        Some(path) => path,
        None => {
            let _ = msg.channel_id.say("Couldn't find file");
            return Ok(());
        },
    };

    if let Some(handler) = ctx.shard.lock().manager.get(guild_id) {
        let source = match voice::dca(path) {
            Ok(source) => source,
            Err(why) => {
                println!("Err starting source: {:?}", why);

                let _ = msg.channel_id.say("Couldn't find file");

                return Ok(());
            },
        };

        handler.play(source);

        let _ = msg.channel_id.say("Playing");
    } else {
        let _ = msg.channel_id.say("Not in a voice channel");
    }
});

command!(airhorn(ctx, msg, _args) {
    let _ = play(ctx, msg, Args::new("airhorn", ","));
});

command!(patrick(ctx, msg, _args) {
    let _ = play(ctx, msg, Args::new("patrick", ","));
});<|endoftext|>


<commit_before>mod lib;

use clap::Parser;
use std::io;
use std::io::BufRead;
use std::path::Path;
use wordcut_engine::replacer;

#[derive(clap::ValueEnum, Clone, Debug)]
enum Lang {
    Lao,
    Khmer,
    Myanmar,
    Thai,
}

#[derive(Parser, Debug)]
#[clap(author, version, about, long_about = None)]
struct Args {
    #[clap(short, long, value_parser)]
    dict_path: Option<String>,
    #[clap(short, long, value_parser)]
    cluster_rules_path: Option<String>,
    #[clap(short = 's', long, value_parser)]
    word_delimiter: Option<String>,
    #[clap(short, long, value_parser, value_enum)]
    lang: Option<Lang>,
}

fn main() {
    let args = Args::parse();
    let lang = args.lang;
    let dict_path = match args.dict_path.as_ref() {
        Some(dict_path) => Path::new(dict_path),
        None => match lang {
            Some(Lang::Lao) => lib::lao_path(),
            Some(Lang::Khmer) => lib::khmer_dict_path(),
            Some(Lang::Myanmar) => lib::myanmar_dict_path(),
            Some(Lang::Thai) | None => lib::default_path(),
        },
    };
    let word_delim = match args.word_delimiter.as_ref().map(|delim| delim.as_str()) {
        Some(word_delim) => word_delim,
        None => "|",
    };
    let dict = lib::load_dict(dict_path).unwrap();

    let cluster_rule_path = if let Some(cluster_rules_path) = args.cluster_rules_path {
        Some(cluster_rules_path.to_string())
    } else {
        match lang {
            Some(Lang::Lao) => lib::lao_clusters_path(),
            Some(Lang::Khmer) => lib::khmer_clusters_path(),
            Some(Lang::Myanmar) => lib::myanmar_clusters_path(),
            Some(Lang::Thai) | None => lib::thai_cluster_path(),
        }
    };

    let wordcut = match cluster_rule_path {
        Some(cluster_rule_path) => {
            let cluster_re =
                lib::wordcut_engine::load_cluster_rules(Path::new(&cluster_rule_path)).unwrap();
            lib::Wordcut::new_with_cluster_re(dict, cluster_re)
        }
        None => lib::Wordcut::new(dict),
    };

    let replace_rules = match lang {
        Some(Lang::Thai) | None => lib::thai_replace_rules_path()
            .map(|path| replacer::load_imm_rules(&path).expect("Load replace rules"))
            .unwrap_or(vec![]),
        _ => vec![],
    };

    for line_opt in io::stdin().lock().lines() {
        let cleaned_line = match line_opt {
            Ok(line) => line.trim_end_matches('\n').to_string(),
            Err(e) => panic!("Cannot read line {}", e),
        };
        let mod_line = replacer::replace(&replace_rules, &cleaned_line);
        let segmented_string = wordcut.put_delimiters(&mod_line, word_delim);
        println!("{}", segmented_string);
    }
}
<commit_msg>feat: add replace rules path parameter<commit_after>mod lib;

use clap::Parser;
use std::io;
use std::io::BufRead;
use std::path::Path;
use wordcut_engine::replacer;

#[derive(clap::ValueEnum, Clone, Debug)]
enum Lang {
    Lao,
    Khmer,
    Myanmar,
    Thai,
}

#[derive(Parser, Debug)]
#[clap(author, version, about, long_about = None)]
struct Args {
    #[clap(short, long, value_parser)]
    dict_path: Option<String>,
    #[clap(short, long, value_parser)]
    cluster_rules_path: Option<String>,
    #[clap(short = 's', long, value_parser)]
    word_delimiter: Option<String>,
    #[clap(short = 'r', long, value_parser)]
    replace_rules_path: Option<String>,
    #[clap(short, long, value_parser, value_enum)]
    lang: Option<Lang>,
}

fn main() {
    let args = Args::parse();
    let lang = args.lang;
    let dict_path = match args.dict_path.as_ref() {
        Some(dict_path) => Path::new(dict_path),
        None => match lang {
            Some(Lang::Lao) => lib::lao_path(),
            Some(Lang::Khmer) => lib::khmer_dict_path(),
            Some(Lang::Myanmar) => lib::myanmar_dict_path(),
            Some(Lang::Thai) | None => lib::default_path(),
        },
    };
    let word_delim = match args.word_delimiter.as_ref().map(|delim| delim.as_str()) {
        Some(word_delim) => word_delim,
        None => "|",
    };
    let dict = lib::load_dict(dict_path).unwrap();

    let cluster_rule_path = if let Some(cluster_rules_path) = args.cluster_rules_path {
        Some(cluster_rules_path.to_string())
    } else {
        match lang {
            Some(Lang::Lao) => lib::lao_clusters_path(),
            Some(Lang::Khmer) => lib::khmer_clusters_path(),
            Some(Lang::Myanmar) => lib::myanmar_clusters_path(),
            Some(Lang::Thai) | None => lib::thai_cluster_path(),
        }
    };

    let wordcut = match cluster_rule_path {
        Some(cluster_rule_path) => {
            let cluster_re =
                lib::wordcut_engine::load_cluster_rules(Path::new(&cluster_rule_path)).unwrap();
            lib::Wordcut::new_with_cluster_re(dict, cluster_re)
        }
        None => lib::Wordcut::new(dict),
    };

    let replace_rules_path = if let Some(replace_rules_path) = args.replace_rules_path {
        Some(replace_rules_path)
    } else {
        match lang {
            Some(Lang::Thai) | None => lib::thai_replace_rules_path(),
            _ => None,
        }
    };

    let replace_rules = if let Some(replace_rules_path) = replace_rules_path {
        replacer::load_imm_rules(&replace_rules_path).expect("Load replace rules")
    } else {
        vec![]
    };

    for line_opt in io::stdin().lock().lines() {
        let cleaned_line = match line_opt {
            Ok(line) => line.trim_end_matches('\n').to_string(),
            Err(e) => panic!("Cannot read line {}", e),
        };
        let mod_line = replacer::replace(&replace_rules, &cleaned_line);
        let segmented_string = wordcut.put_delimiters(&mod_line, word_delim);
        println!("{}", segmented_string);
    }
}
<|endoftext|>


<commit_before>use command::*;
use std::{env, path::PathBuf};
use structopt::{clap::ArgGroup, StructOpt};

const APP_NAME: &str = "git plz";
const CMD_BRANCH: &str = "BRANCH";

fn branch_arg_group<'a>() -> ArgGroup<'a> {
    ArgGroup::with_name("branch").required(true)
}

#[derive(StructOpt, Debug)]
struct PathArg {
    /// Path to execute command. Defaults to working directory.
    #[structopt(name = "PATH", parse(from_os_str))]
    value: Option<PathBuf>,
}

#[derive(StructOpt, Debug)]
#[structopt(raw(bin_name = "APP_NAME"))]
enum RunOption {
    /// Perform bulk local branch operations
    #[structopt(name = "branch", raw(group = "branch_arg_group()"))]
    Branch {
        #[structopt(
            short = "f",
            long = "find",
            group = "branch",
            raw(value_name = "CMD_BRANCH")
        )]
        find: Option<String>,
        #[structopt(
            short = "d",
            long = "delete",
            group = "branch",
            raw(value_name = "CMD_BRANCH")
        )]
        delete: Option<String>,
        #[structopt(flatten)]
        path: PathArg,
    },
    /// Checkout branch across repos
    #[structopt(name = "checkout")]
    Checkout {
        /// Branch name
        #[structopt(name = "BRANCH")]
        branch: String,
        #[structopt(flatten)]
        path: PathArg,
    },
    /// Recursive fetch
    #[structopt(name = "fetch")]
    Fetch {
        #[structopt(flatten)]
        path: PathArg,
    },
    /// Recursive hard reset
    #[structopt(name = "reset")]
    Reset {
        #[structopt(flatten)]
        path: PathArg,
    },
    /// Recursive directory search version of git status
    #[structopt(name = "status")]
    Status {
        #[structopt(flatten)]
        path: PathArg,
    },
}

pub struct MappedArgs {
    command: Box<dyn Command>,
    path: PathBuf,
}

impl MappedArgs {
    fn new(run_option: RunOption) -> Self {
        struct TempArgs(Box<dyn Command>, PathArg);

        let temp_args = match run_option {
            RunOption::Branch { path, delete, find } => {
                // TODO: This needs to be an enum again
                if let Some(branch) = delete {
                    TempArgs(Box::new(BranchDeleteCommand::new(branch)), path)
                } else if let Some(branch) = find {
                    TempArgs(Box::new(BranchFindCommand::new(branch)), path)
                } else {
                    panic!("Invalid branch option");
                }
            }
            RunOption::Checkout { path, branch } => {
                TempArgs(Box::new(CheckoutCommand::new(branch)), path)
            }
            RunOption::Fetch { path } => TempArgs(Box::new(FetchCommand::new()), path),
            RunOption::Reset { path } => TempArgs(Box::new(ResetCommand::new()), path),
            RunOption::Status { path } => TempArgs(Box::new(StatusCommand::new()), path),
        };

        Self {
            command: temp_args.0,
            path: temp_args
                .1
                .value
                .unwrap_or_else(|| env::current_dir().expect("Could not get working directory")),
        }
    }

    pub fn destructure(self) -> (Box<dyn Command>, PathBuf) {
        (self.command, self.path)
    }
}

pub fn handle_args() -> MappedArgs {
    MappedArgs::new(RunOption::from_args())
}
<commit_msg>Improved arg mapping structure<commit_after>use command::*;
use std::{env, path::PathBuf};
use structopt::{clap::ArgGroup, StructOpt};

const APP_NAME: &str = "git plz";
const CMD_BRANCH: &str = "BRANCH";

fn branch_arg_group<'a>() -> ArgGroup<'a> {
    ArgGroup::with_name("branch").required(true)
}

#[derive(StructOpt, Debug)]
struct PathArg {
    /// Path to execute command. Defaults to working directory.
    #[structopt(name = "PATH", parse(from_os_str))]
    value: Option<PathBuf>,
}

impl Into<PathBuf> for PathArg {
    fn into(self) -> PathBuf {
        self.value
            .unwrap_or_else(|| env::current_dir().expect("Could not get working directory"))
    }
}

#[derive(StructOpt, Debug)]
#[structopt(raw(bin_name = "APP_NAME"))]
enum RunOption {
    /// Perform bulk local branch operations
    #[structopt(name = "branch", raw(group = "branch_arg_group()"))]
    Branch {
        #[structopt(
            short = "f",
            long = "find",
            group = "branch",
            raw(value_name = "CMD_BRANCH")
        )]
        find: Option<String>,
        #[structopt(
            short = "d",
            long = "delete",
            group = "branch",
            raw(value_name = "CMD_BRANCH")
        )]
        delete: Option<String>,
        #[structopt(flatten)]
        path: PathArg,
    },
    /// Checkout branch across repos
    #[structopt(name = "checkout")]
    Checkout {
        /// Branch name
        #[structopt(name = "BRANCH")]
        branch: String,
        #[structopt(flatten)]
        path: PathArg,
    },
    /// Recursive fetch
    #[structopt(name = "fetch")]
    Fetch {
        #[structopt(flatten)]
        path: PathArg,
    },
    /// Recursive hard reset
    #[structopt(name = "reset")]
    Reset {
        #[structopt(flatten)]
        path: PathArg,
    },
    /// Recursive directory search version of git status
    #[structopt(name = "status")]
    Status {
        #[structopt(flatten)]
        path: PathArg,
    },
}

pub struct MappedArgs {
    command: Box<dyn Command>,
    path: PathBuf,
}

impl MappedArgs {
    fn new(run_option: RunOption) -> Self {
        struct ArgPair(Box<dyn Command>, PathArg);

        let ArgPair(command, path) = match run_option {
            RunOption::Branch { path, delete, find } => {
                // TODO: This needs to be an enum again
                if let Some(branch) = delete {
                    ArgPair(Box::new(BranchDeleteCommand::new(branch)), path)
                } else if let Some(branch) = find {
                    ArgPair(Box::new(BranchFindCommand::new(branch)), path)
                } else {
                    panic!("Invalid branch option");
                }
            }
            RunOption::Checkout { path, branch } => {
                ArgPair(Box::new(CheckoutCommand::new(branch)), path)
            }
            RunOption::Fetch { path } => ArgPair(Box::new(FetchCommand::new()), path),
            RunOption::Reset { path } => ArgPair(Box::new(ResetCommand::new()), path),
            RunOption::Status { path } => ArgPair(Box::new(StatusCommand::new()), path),
        };

        Self {
            command,
            path: path.into(),
        }
    }

    pub fn destructure(self) -> (Box<dyn Command>, PathBuf) {
        (self.command, self.path)
    }
}

pub fn handle_args() -> MappedArgs {
    MappedArgs::new(RunOption::from_args())
}
<|endoftext|>


<commit_before>extern crate cgmath;
extern crate vulkan;
extern crate xcb;

use vulkan::ffi::*;
use xcb::*;

fn main() {
}
<commit_msg>ffi_cube: have translated a tiny amount, now it builds<commit_after>#![allow(unused_imports, dead_code, non_snake_case)]

extern crate cgmath;
extern crate vulkan;
extern crate xcb;

use vulkan::ffi::vulkan::*;
use vulkan::ffi::vk_ext_debug_report::*;
use vulkan::ffi::vk_sdk_platform::*;
use cgmath::*;

const DEMO_TEXTURE_COUNT: usize = 1;
const APP_SHORT_NAME: &'static str = "cube";
const APP_LONG_NAME: &'static str = "The Vulkan Cube Demo Program";

fn main() {
    let mut demo = Demo::init(std::env::args());
    demo.create_window();
    demo.init_vk_swapchain();

    demo.prepare();
    demo.run();

    demo.cleanup();
}

struct Demo<'a> {
    connection: Box<xcb::base::Connection>,
    screen: Box<xcb::xproto::Screen<'a>>,
    window: xcb::xproto::Window,
    atom_wm_delete_window: Box<xcb::xproto::InternAtomReply>,
    surface: VkSurfaceKHR,
    prepared: bool,
    use_staging_buffer: bool,

    inst: VkInstance,
    gpu: VkPhysicalDevice,
    device: VkDevice,
    queue: VkQueue,
    graphics_queue_node_index: u32,
    gpu_props: VkPhysicalDeviceProperties,
    queue_props: Box<VkQueueFamilyProperties>,
    memory_properties: VkPhysicalDeviceMemoryProperties,

    enabled_extension_count: u32,
    enabled_layer_count: u32,
    extension_names: Vec<&'static str>,
    device_validation_layers: Vec<&'static str>,

    width: i32,
    height: i32,
    format: VkFormat,
    color_space: VkColorSpaceKHR,

    fpGetPhysicalDeviceSurfaceSupportKHR:      PFN_vkGetPhysicalDeviceSurfaceSupportKHR,
    fpGetPhysicalDeviceSurfaceCapabilitiesKHR: PFN_vkGetPhysicalDeviceSurfaceCapabilitiesKHR,
    fpGetPhysicalDeviceSurfaceFormatsKHR:      PFN_vkGetPhysicalDeviceSurfaceFormatsKHR,
    fpGetPhysicalDeviceSurfacePresentModesKHR: PFN_vkGetPhysicalDeviceSurfacePresentModesKHR,
    fpCreateSwapchainKHR:                      PFN_vkCreateSwapchainKHR,
    fpDestroySwapchainKHR:                     PFN_vkDestroySwapchainKHR,
    fpGetSwapchainImagesKHR:                   PFN_vkGetSwapchainImagesKHR,
    fpAcquireNextImageKHR:                     PFN_vkAcquireNextImageKHR,
    fpQueuePresentKHR:                         PFN_vkQueuePresentKHR,
    swapchainImageCount: u32,
    swapchain: VkSwapchainKHR,
    buffers: Box<SwapchainBuffers>,

    cmd_pool: VkCommandPool,

    depth: Depth,

    textures: [TextureObject; DEMO_TEXTURE_COUNT],

    uniform_data: UniformData,

    cmd: VkCommandBuffer,
    pipeline_layout: VkPipelineLayout,
    desc_layout: VkDescriptorSetLayout,
    pipelineCache: VkPipelineCache,
    render_pass: VkRenderPass,
    pipeline: VkPipeline,

    projection_matrix: Matrix4<f32>,
    view_matrix: Matrix4<f32>,
    model_matrix: Matrix4<f32>,

    spin_angle: f32,
    spin_increment: f32,
    pause: bool,

    vert_shader_module: VkShaderModule,
    frag_shader_module: VkShaderModule,

    desc_pool: VkDescriptorPool,
    desc_set: VkDescriptorSet,

    framebuffers: Box<VkFramebuffer>,

    quit: bool,
    curFrame: i32,
    frameCount: i32,
    validate: bool,
    use_break: bool,
    CreateDebugReportCallback: PFN_vkCreateDebugReportCallbackEXT,
    DestroyDebugReportCallback: PFN_vkDestroyDebugReportCallbackEXT,
    msg_callback: VkDebugReportCallbackEXT,
    DebugReportMessage: PFN_vkDebugReportMessageEXT,

    current_buffer: u32,
    queue_count: u32,
}

struct Depth {
    format: VkFormat,
    image: VkImage,
    mem_alloc: VkMemoryAllocateInfo,
    mem: VkDeviceMemory,
    view: VkImageView,
}

struct UniformData {
    buf: VkBuffer,
    mem_alloc: VkMemoryAllocateInfo,
    mem: VkDeviceMemory,
    buffer_info: VkDescriptorBufferInfo,
}

struct SwapchainBuffers {
    image: VkImage,
    cmd: VkCommandBuffer,
    view: VkImageView,
}

struct TextureObject {
    sampler: VkSampler,
    image: VkImage,
    imageLayout: VkImageLayout,
    mem_alloc: VkMemoryAllocateInfo,
    mem: VkDeviceMemory,
    view: VkImageView,
    tex_width: i32,
    tex_height: i32,
}

impl<'a> Demo<'a> {
    fn init(args: std::env::Args) -> Demo<'a> {
        let eye: Point3<f32> = Point3::new(0.0, 3.0, 5.0);
        let origin: Point3<f32> = Point3::origin();
        let up: Vector3<f32> = Vector3::unit_y();

        let mut demo: Demo<'a> = unsafe { std::mem::zeroed() };
        demo.frameCount = std::i32::MAX;

        for arg in args.skip(1) {
            if arg == "--use_staging" {
                demo.use_staging_buffer = true;
            } else if arg == "--break" {
                demo.use_break = true;
            } else if arg == "--validate" {
                demo.validate = true;
            } else if arg == "--c" {
                if demo.frameCount == std::i32::MAX {
                }
            } else {
                println!(
                    "Usage:\n  {} [--use_staging] \
                    [--validate] [--break] [--c <framecount>]",
                    APP_SHORT_NAME
                    );
                std::process::exit(1);
            }
        }

        demo.init_connection();
        demo.init_vk();

        demo.width = 500;
        demo.height = 500;

        demo.spin_angle = 0.01;
        demo.spin_increment = 0.01;
        demo.pause = false;

        demo.projection_matrix = perspective(Deg::new(45f32), 1.0, 0.1, 100.0);
        demo.view_matrix = Matrix4::look_at(eye, origin, up);
        demo.model_matrix = Matrix4::identity();

        demo
    }

    fn init_connection(&mut self) {
    }

    fn init_vk(&mut self) {
    }

    fn create_window(&mut self) {
    }

    fn init_vk_swapchain(&mut self) {
    }

    fn prepare(&mut self) {
    }

    fn run(&mut self) {
    }

    fn cleanup(&mut self) {
    }
}
<|endoftext|>


<commit_before>///! Generate a base bitmap for drawing an overland map with a paint program.

extern crate structopt;
#[macro_use]
extern crate structopt_derive;
extern crate calx;
extern crate world;
extern crate image;
extern crate euclid;

use calx::hex_disc;
use euclid::{Rect, rect};
use image::{GenericImage, Pixel};
use structopt::StructOpt;
use world::{Sector, Location, Terrain};

#[derive(StructOpt, Debug)]
struct Opt {
    #[structopt(short = "w", long = "width", default_value = "8", help = "Width in sectors")]
    width: u32,

    #[structopt(short = "h", long = "height", default_value = "12", help = "Height in sectors")]
    height: u32,

    #[structopt(subcommand)]
    cmd: Command,
}

#[derive(StructOpt, Debug)]
enum Command {
    #[structopt(name = "generate", help = "Generate a blank overland map image")]
    Generate {
        #[structopt(help = "Output PNG file", default_value = "overland_base.png")]
        output: String,
    },

    #[structopt(name = "normalize",
                help = "Normalize the sector checkerboard coloring in existing image")]
    Normalize {
        #[structopt(help = "Input file")]
        input: String,

        #[structopt(help = "Output file (if different from input)")]
        output: Option<String>,
    },
}

fn overland_locs(width: u32, height: u32) -> Vec<Location> {
    let mut ret = Vec::new();
    for y in 0..(height as i16) {
        for x in 0..(width as i16) {
            let sec = Sector::new(x, y, 0);
            for loc in sec.iter() {
                ret.push(loc);
            }
        }
    }
    ret
}

fn location_area(width: u32, height: u32) -> Rect<i16> {
    let locs = overland_locs(width, height);
    let (mut min_x, mut min_y) = locs.iter().fold(
        (0, 0),
        |(x, y), loc| (x.min(loc.x), y.min(loc.y)),
    );
    min_x -= 1;
    min_y -= 1;

    let (max_x, max_y) = locs.iter().fold(
        (0, 0),
        |(x, y), loc| (x.max(loc.x), y.max(loc.y)),
    );

    rect(min_x, min_y, max_x - min_x + 2, max_y - min_y + 2)
}

fn valid_sector(sec: Sector, width: u32, height: u32) -> bool {
    sec.x >= 0 && sec.y >= 0 && sec.x < (width as i16) && sec.y < (height as i16)
}

trait Dark {
    fn is_dark(self) -> bool;
}

impl Dark for Sector {
    fn is_dark(self) -> bool { (self.x + self.y) % 2 != 0 }
}

fn generate(width: u32, height: u32, output: &str) {
    let area = location_area(width, height);

    println!("Origin {{ x: {}, y: {} }}", area.origin.x, area.origin.y);

    let mut buf = image::ImageBuffer::new(area.size.width as u32, (area.size.height + 1) as u32);

    for (x, y, p) in buf.enumerate_pixels_mut() {
        let loc = Location::new(x as i16 + area.origin.x, y as i16 + area.origin.y, 0);
        let sec = loc.sector();
        let terrain = if valid_sector(sec, width, height) {
            Terrain::Grass
        } else if hex_disc(loc, 1).any(|loc| valid_sector(loc.sector(), width, height)) {
            // Not a valid sector, but touching one.
            Terrain::Water
        } else {
            *p = image::Rgb::from_channels(0x00, 0x00, 0x00, 0xff);
            continue;
        };

        let color = if sec.is_dark() {
            terrain.dark_color()
        } else {
            terrain.color()
        };

        *p = image::Rgb::from_channels(color.r, color.g, color.b, 0xff);
    }

    // XXX: Hacky way to force terrain colors into image palette
    // Didn't find direct indexed palette manipulation in piston-image.
    for (x, t) in Terrain::iter().filter(|t| t.is_regular()).enumerate() {
        let light = t.color();
        let dark = t.dark_color();
        let y = buf.height() - 1;
        buf.put_pixel(
            x as u32 * 2,
            y,
            image::Rgb::from_channels(light.r, light.g, light.b, 0xff),
        );
        buf.put_pixel(
            x as u32 * 2 + 1,
            y,
            image::Rgb::from_channels(dark.r, dark.g, dark.b, 0xff),
        );
    }

    image::save_buffer(
        output,
        &buf,
        buf.width(),
        buf.height(),
        image::ColorType::RGB(8),
    ).unwrap();
}

fn normalize(width: u32, height: u32, input: &str, out_path: &str) {
    let input = image::open(input).expect(&format!("Unable to load '{}'", input));
    let mut output: image::ImageBuffer<image::Rgba<u8>, Vec<u8>> =
        image::ImageBuffer::new(input.width(), input.height());

    let area = location_area(width, height);

    for y in 0..input.height() {
        for x in 0..input.width() {
            let in_map_space = y < input.height() - 1;

            let p = input.get_pixel(x, y);
            let sector = Location::new((x as i16) + area.origin.x, (y as i16) + area.origin.y, 0)
                .sector();

            let output_pixel = if in_map_space {
                if let Some(t) = Terrain::from_color(p.into()) {
                    if sector.is_dark() {
                        t.dark_color()
                    } else {
                        t.color()
                    }.into()
                } else {
                    p
                }
            } else {
                p
            };

            output.put_pixel(x, y, output_pixel);
        }
    }

    image::save_buffer(
        out_path,
        &output,
        output.width(),
        output.height(),
        image::ColorType::RGBA(8),
    ).unwrap();
}

fn main() {
    let opt = Opt::from_args();
    match opt.cmd {
        Command::Generate { output } => {
            generate(opt.width, opt.height, &output);
        }

        Command::Normalize { input, output } => {
            normalize(
                opt.width,
                opt.height,
                &input.clone(),
                &output.unwrap_or(input),
            );
        }
    }
}
<commit_msg>Fix map height for screen-fitting minimap<commit_after>///! Generate a base bitmap for drawing an overland map with a paint program.

extern crate structopt;
#[macro_use]
extern crate structopt_derive;
extern crate calx;
extern crate world;
extern crate image;
extern crate euclid;

use calx::hex_disc;
use euclid::{Rect, rect};
use image::{GenericImage, Pixel};
use structopt::StructOpt;
use world::{Sector, Location, Terrain};

#[derive(StructOpt, Debug)]
struct Opt {
    #[structopt(short = "w", long = "width", default_value = "8", help = "Width in sectors")]
    width: u32,

    #[structopt(short = "h", long = "height", default_value = "9", help = "Height in sectors")]
    height: u32,

    #[structopt(subcommand)]
    cmd: Command,
}

#[derive(StructOpt, Debug)]
enum Command {
    #[structopt(name = "generate", help = "Generate a blank overland map image")]
    Generate {
        #[structopt(help = "Output PNG file", default_value = "overland_base.png")]
        output: String,
    },

    #[structopt(name = "normalize",
                help = "Normalize the sector checkerboard coloring in existing image")]
    Normalize {
        #[structopt(help = "Input file")]
        input: String,

        #[structopt(help = "Output file (if different from input)")]
        output: Option<String>,
    },
}

fn overland_locs(width: u32, height: u32) -> Vec<Location> {
    let mut ret = Vec::new();
    for y in 0..(height as i16) {
        for x in 0..(width as i16) {
            let sec = Sector::new(x, y, 0);
            for loc in sec.iter() {
                ret.push(loc);
            }
        }
    }
    ret
}

fn location_area(width: u32, height: u32) -> Rect<i16> {
    let locs = overland_locs(width, height);
    let (mut min_x, mut min_y) = locs.iter().fold(
        (0, 0),
        |(x, y), loc| (x.min(loc.x), y.min(loc.y)),
    );
    min_x -= 1;
    min_y -= 1;

    let (max_x, max_y) = locs.iter().fold(
        (0, 0),
        |(x, y), loc| (x.max(loc.x), y.max(loc.y)),
    );

    rect(min_x, min_y, max_x - min_x + 2, max_y - min_y + 2)
}

fn valid_sector(sec: Sector, width: u32, height: u32) -> bool {
    sec.x >= 0 && sec.y >= 0 && sec.x < (width as i16) && sec.y < (height as i16)
}

trait Dark {
    fn is_dark(self) -> bool;
}

impl Dark for Sector {
    fn is_dark(self) -> bool { (self.x + self.y) % 2 != 0 }
}

fn generate(width: u32, height: u32, output: &str) {
    let area = location_area(width, height);

    println!("Origin {{ x: {}, y: {} }}", area.origin.x, area.origin.y);

    let mut buf = image::ImageBuffer::new(area.size.width as u32, (area.size.height + 1) as u32);

    for (x, y, p) in buf.enumerate_pixels_mut() {
        let loc = Location::new(x as i16 + area.origin.x, y as i16 + area.origin.y, 0);
        let sec = loc.sector();
        let terrain = if valid_sector(sec, width, height) {
            Terrain::Grass
        } else if hex_disc(loc, 1).any(|loc| valid_sector(loc.sector(), width, height)) {
            // Not a valid sector, but touching one.
            Terrain::Water
        } else {
            *p = image::Rgb::from_channels(0x00, 0x00, 0x00, 0xff);
            continue;
        };

        let color = if sec.is_dark() {
            terrain.dark_color()
        } else {
            terrain.color()
        };

        *p = image::Rgb::from_channels(color.r, color.g, color.b, 0xff);
    }

    // XXX: Hacky way to force terrain colors into image palette
    // Didn't find direct indexed palette manipulation in piston-image.
    for (x, t) in Terrain::iter().filter(|t| t.is_regular()).enumerate() {
        let light = t.color();
        let dark = t.dark_color();
        let y = buf.height() - 1;
        buf.put_pixel(
            x as u32 * 2,
            y,
            image::Rgb::from_channels(light.r, light.g, light.b, 0xff),
        );
        buf.put_pixel(
            x as u32 * 2 + 1,
            y,
            image::Rgb::from_channels(dark.r, dark.g, dark.b, 0xff),
        );
    }

    image::save_buffer(
        output,
        &buf,
        buf.width(),
        buf.height(),
        image::ColorType::RGB(8),
    ).unwrap();
}

fn normalize(width: u32, height: u32, input: &str, out_path: &str) {
    let input = image::open(input).expect(&format!("Unable to load '{}'", input));
    let mut output: image::ImageBuffer<image::Rgba<u8>, Vec<u8>> =
        image::ImageBuffer::new(input.width(), input.height());

    let area = location_area(width, height);

    for y in 0..input.height() {
        for x in 0..input.width() {
            let in_map_space = y < input.height() - 1;

            let p = input.get_pixel(x, y);
            let sector = Location::new((x as i16) + area.origin.x, (y as i16) + area.origin.y, 0)
                .sector();

            let output_pixel = if in_map_space {
                if let Some(t) = Terrain::from_color(p.into()) {
                    if sector.is_dark() {
                        t.dark_color()
                    } else {
                        t.color()
                    }.into()
                } else {
                    p
                }
            } else {
                p
            };

            output.put_pixel(x, y, output_pixel);
        }
    }

    image::save_buffer(
        out_path,
        &output,
        output.width(),
        output.height(),
        image::ColorType::RGBA(8),
    ).unwrap();
}

fn main() {
    let opt = Opt::from_args();
    match opt.cmd {
        Command::Generate { output } => {
            generate(opt.width, opt.height, &output);
        }

        Command::Normalize { input, output } => {
            normalize(
                opt.width,
                opt.height,
                &input.clone(),
                &output.unwrap_or(input),
            );
        }
    }
}
<|endoftext|>


<commit_before>#![allow(unused_imports, dead_code)]
extern crate env_logger;
extern crate handlebars;
#[cfg(all(feature = "rustc_ser_type", not(feature = "serde_type")))]
extern crate rustc_serialize;
#[macro_use]
extern crate maplit;

use std::path::Path;
use handlebars::Handlebars;

#[cfg(all(feature = "rustc_ser_type", not(feature = "serde_type"), feature = "partial_legacy", not(feature = "partial4")))]
fn main() {
    env_logger::init().unwrap();
    let mut handlebars = Handlebars::new();

    handlebars.register_template_file("template",
                                      &Path::new("./examples/partials_legacy/template2.hbs"))
              .ok()
              .unwrap();
    handlebars.register_template_file("base0", &Path::new("./examples/partials_legacy/base0.hbs"))
              .ok()
              .unwrap();
    handlebars.register_template_file("base1", &Path::new("./examples/partials_legacy/base1.hbs"))
              .ok()
              .unwrap();

    let data0 = btreemap! {
        "title".to_string() => "example 0".to_string(),
        "parent".to_string() => "base0".to_string()
    };
    let data1 = btreemap! {
        "title".to_string() => "example 1".to_string(),
        "parent".to_string() => "base1".to_string()
    };

    println!("Page 0");
    println!("{}", handlebars.render("template", &data0).ok().unwrap());
    println!("=======================================================");

    println!("Page 1");
    println!("{}", handlebars.render("template", &data1).ok().unwrap());
}

#[cfg(feature = "serde_type")]
fn main() {}

#[cfg(all(feature = "partial4", feature = "rustc_ser_type"))]
fn main() {
    env_logger::init().unwrap();
    let mut handlebars = Handlebars::new();

    handlebars.register_template_file("template", &Path::new("./examples/partials/template2.hbs"))
              .ok()
              .unwrap();

    handlebars.register_template_file("base0", &Path::new("./examples/partials/base0.hbs"))
              .ok()
              .unwrap();
    handlebars.register_template_file("base1", &Path::new("./examples/partials/base1.hbs"))
              .ok()
              .unwrap();

    let data0 = btreemap! {
        "title".to_string() => "example 0".to_string(),
        "parent".to_string() => "base0".to_string()
    };
    let data1 = btreemap! {
        "title".to_string() => "example 1".to_string(),
        "parent".to_string() => "base1".to_string()
    };

    println!("Page 0");
    println!("{}", handlebars.render("template", &data0).ok().unwrap());
    println!("=======================================================");

    println!("Page 1");
    println!("{}", handlebars.render("template", &data1).ok().unwrap());
}
<commit_msg>(fix) fix test for serde_type<commit_after>#![allow(unused_imports, dead_code)]
extern crate env_logger;
extern crate handlebars;
#[cfg(all(feature = "rustc_ser_type", not(feature = "serde_type")))]
extern crate rustc_serialize;
#[macro_use]
extern crate maplit;

use std::path::Path;
use handlebars::Handlebars;

#[cfg(all(feature = "rustc_ser_type", not(feature = "serde_type"), feature = "partial_legacy", not(feature = "partial4")))]
fn main() {
    env_logger::init().unwrap();
    let mut handlebars = Handlebars::new();

    handlebars.register_template_file("template",
                                      &Path::new("./examples/partials_legacy/template2.hbs"))
              .ok()
              .unwrap();
    handlebars.register_template_file("base0", &Path::new("./examples/partials_legacy/base0.hbs"))
              .ok()
              .unwrap();
    handlebars.register_template_file("base1", &Path::new("./examples/partials_legacy/base1.hbs"))
              .ok()
              .unwrap();

    let data0 = btreemap! {
        "title".to_string() => "example 0".to_string(),
        "parent".to_string() => "base0".to_string()
    };
    let data1 = btreemap! {
        "title".to_string() => "example 1".to_string(),
        "parent".to_string() => "base1".to_string()
    };

    println!("Page 0");
    println!("{}", handlebars.render("template", &data0).ok().unwrap());
    println!("=======================================================");

    println!("Page 1");
    println!("{}", handlebars.render("template", &data1).ok().unwrap());
}

#[cfg(feature = "serde_type")]
fn main() {}

#[cfg(all(feature = "partial4", feature = "rustc_ser_type", not(feature="serde_type")))]
fn main() {
    env_logger::init().unwrap();
    let mut handlebars = Handlebars::new();

    handlebars.register_template_file("template", &Path::new("./examples/partials/template2.hbs"))
              .ok()
              .unwrap();

    handlebars.register_template_file("base0", &Path::new("./examples/partials/base0.hbs"))
              .ok()
              .unwrap();
    handlebars.register_template_file("base1", &Path::new("./examples/partials/base1.hbs"))
              .ok()
              .unwrap();

    let data0 = btreemap! {
        "title".to_string() => "example 0".to_string(),
        "parent".to_string() => "base0".to_string()
    };
    let data1 = btreemap! {
        "title".to_string() => "example 1".to_string(),
        "parent".to_string() => "base1".to_string()
    };

    println!("Page 0");
    println!("{}", handlebars.render("template", &data0).ok().unwrap());
    println!("=======================================================");

    println!("Page 1");
    println!("{}", handlebars.render("template", &data1).ok().unwrap());
}
<|endoftext|>


<commit_before>use neb::ram::schema::Field;
use neb::ram::types::{TypeId, Id, key_hash, Map, Value};
use neb::ram::cell::{Cell, WriteError};
use neb::client::{Client as NebClient};
use neb::client::transaction::TxnError;
use bifrost::rpc::RPCError;

use server::schema::{MorpheusSchema, SchemaType, SchemaContainer, SchemaError};
use graph::vertex::Vertex;

use std::sync::Arc;
use serde::Serialize;

pub mod vertex;
pub mod edge;

pub enum NewVertexError {
    SchemaNotFound,
    SchemaNotVertex,
    CannotGenerateCellByData,
    DataNotMap,
    RPCError(RPCError),
    WriteError(WriteError),
}

#[derive(Clone, Copy, Serialize, Deserialize)]
pub enum CellType {
    Vertex,
    Edge(edge::EdgeType)
}

lazy_static! {
    pub static ref ID_LINKED_LIST: Vec<Field> = vec![
            Field::new(&String::from("next"), TypeId::Id as u32, true, false, None),
            Field::new(&String::from("list"), TypeId::Id as u32, false, true, None)
        ];
}

pub fn cell_to_vertex(cell: Cell) -> Vertex {
    Vertex {
        id: cell.header.id(),
        schema: cell.header.schema,
        data: cell.data
    }
}

pub fn vertex_to_cell(vertex: Vertex) -> Cell {
    Cell::new_with_id(vertex.schema, &vertex.id, vertex.data)
}

pub struct Graph {
    schema: Arc<SchemaContainer>,
    neb_client: Arc<NebClient>
}

impl Graph {
    pub fn new_vertex_group(&self, schema: &mut MorpheusSchema) -> Result<(), SchemaError> {
        schema.schema_type = SchemaType::Vertex;
        self.schema.new_schema(schema)
    }
    pub fn new_edge_group(&self, schema: &mut MorpheusSchema, edge_type: edge::EdgeType) -> Result<(), SchemaError> {
        if edge_type == edge::EdgeType::Simple {
            return Err(SchemaError::SimpleEdgeShouldNotHaveSchema)
        }
        schema.schema_type = SchemaType::Edge(edge_type);
        self.schema.new_schema(schema)
    }
    pub fn new_vertex(&self, mut vertex: Vertex) -> Result<Vertex, NewVertexError> {
        let schema_id = vertex.schema;
        if let Some(stype) = self.schema.schema_type(schema_id) {
            if stype != SchemaType::Vertex {
                return Err(NewVertexError::SchemaNotVertex)
            }
        } else {
            return Err(NewVertexError::SchemaNotFound)
        }
        let neb_schema = match self.schema.get_neb_schema(schema_id) {
            Some(schema) => schema,
            None => return Err(NewVertexError::SchemaNotFound)
        };
        let mut data = {
            match vertex.data {
                Value::Map(mut map) => map,
                _ => return Err(NewVertexError::DataNotMap)
            }
        };
        data.insert_key_id(*vertex::INBOUND_KEY_ID, Value::Id(Id::unit_id()));
        data.insert_key_id(*vertex::OUTBOUND_KEY_ID, Value::Id(Id::unit_id()));
        data.insert_key_id(*vertex::INDIRECTED_KEY_ID, Value::Id(Id::unit_id()));
        let mut cell = match Cell::new(&neb_schema, Value::Map(data)) {
            Some(cell) => cell,
            None => return Err(NewVertexError::CannotGenerateCellByData)
        };
        let header = match self.neb_client.write_cell(&cell) {
            Ok(Ok(header)) => header,
            Ok(Err(e)) => return Err(NewVertexError::WriteError(e)),
            Err(e) => return Err(NewVertexError::RPCError(e))
        };
        cell.header = header;
        Ok(cell_to_vertex(cell))
    }
    // TODO: Update edge list
    pub fn remove_vertex(&self, id: &Id) -> Result<(), TxnError> {
        self.neb_client.transaction(|txn| {
            match txn.read(id)? {
                Some(cell) => {
                    let vertex = cell_to_vertex(cell); // for remove it from neighbourhoods
                    txn.remove(id)
                },
                None => txn.abort()
            }
        })
    }
    pub fn remove_vertex_by_key<K>(&self, schema_id: u32, key: &K) -> Result<(), TxnError>
        where K: Serialize {
        let id = Cell::encode_cell_key(schema_id, key);
        self.remove_vertex(&id)
    }
    pub fn update_vertex<U>(&self, id: &Id, update: U) -> Result<(), TxnError>
        where U: Fn(Vertex) -> Option<Vertex> {
        let update_cell = |cell| {
            match update(cell_to_vertex(cell)) {
                Some(vertex) => Some(vertex_to_cell(vertex)),
                None => None
            }
        };
        self.neb_client.transaction(|txn|{
            let cell = txn.read(id)?;
            match cell {
                Some(cell) => {
                    match update_cell(cell) {
                        Some(cell) => txn.update(&cell),
                        None => txn.abort()
                    }
                },
                None => txn.abort()
            }
        })
    }
    pub fn update_vertex_by_key<K, U>(&self, schema_id: u32, key: &K, update: U)
        -> Result<(), TxnError>
        where K: Serialize, U: Fn(Vertex) -> Option<Vertex>{
        let id = Cell::encode_cell_key(schema_id, key);
        self.update_vertex(&id, update)
    }

}<commit_msg>refactor vertex -> cell for new vertex<commit_after>use neb::ram::schema::Field;
use neb::ram::types::{TypeId, Id, key_hash, Map, Value};
use neb::ram::cell::{Cell, WriteError};
use neb::client::{Client as NebClient};
use neb::client::transaction::TxnError;
use bifrost::rpc::RPCError;

use server::schema::{MorpheusSchema, SchemaType, SchemaContainer, SchemaError};
use graph::vertex::Vertex;

use std::sync::Arc;
use serde::Serialize;

pub mod vertex;
pub mod edge;

pub enum NewVertexError {
    SchemaNotFound,
    SchemaNotVertex,
    CannotGenerateCellByData,
    DataNotMap,
    RPCError(RPCError),
    WriteError(WriteError),
}

#[derive(Clone, Copy, Serialize, Deserialize)]
pub enum CellType {
    Vertex,
    Edge(edge::EdgeType)
}

lazy_static! {
    pub static ref ID_LINKED_LIST: Vec<Field> = vec![
            Field::new(&String::from("next"), TypeId::Id as u32, true, false, None),
            Field::new(&String::from("list"), TypeId::Id as u32, false, true, None)
        ];
}

pub fn cell_to_vertex(cell: Cell) -> Vertex {
    Vertex {
        id: cell.header.id(),
        schema: cell.header.schema,
        data: cell.data
    }
}

pub fn vertex_to_cell(vertex: Vertex) -> Cell {
    Cell::new_with_id(vertex.schema, &vertex.id, vertex.data)
}

fn vertex_to_cell_for_write(schemas: &Arc<SchemaContainer>, vertex: Vertex) -> Result<Cell, NewVertexError> {
    let schema_id = vertex.schema;
    if let Some(stype) = schemas.schema_type(schema_id) {
        if stype != SchemaType::Vertex {
            return Err(NewVertexError::SchemaNotVertex)
        }
    } else {
        return Err(NewVertexError::SchemaNotFound)
    }
    let neb_schema = match schemas.get_neb_schema(schema_id) {
        Some(schema) => schema,
        None => return Err(NewVertexError::SchemaNotFound)
    };
    let mut data = {
        match vertex.data {
            Value::Map(mut map) => map,
            _ => return Err(NewVertexError::DataNotMap)
        }
    };
    data.insert_key_id(*vertex::INBOUND_KEY_ID, Value::Id(Id::unit_id()));
    data.insert_key_id(*vertex::OUTBOUND_KEY_ID, Value::Id(Id::unit_id()));
    data.insert_key_id(*vertex::INDIRECTED_KEY_ID, Value::Id(Id::unit_id()));
    match Cell::new(&neb_schema, Value::Map(data)) {
        Some(cell) => Ok(cell),
        None => return Err(NewVertexError::CannotGenerateCellByData)
    }
}

pub struct Graph {
    schemas: Arc<SchemaContainer>,
    neb_client: Arc<NebClient>
}

impl Graph {
    pub fn new_vertex_group(&self, schema: &mut MorpheusSchema) -> Result<(), SchemaError> {
        schema.schema_type = SchemaType::Vertex;
        self.schemas.new_schema(schema)
    }
    pub fn new_edge_group(&self, schema: &mut MorpheusSchema, edge_type: edge::EdgeType) -> Result<(), SchemaError> {
        if edge_type == edge::EdgeType::Simple {
            return Err(SchemaError::SimpleEdgeShouldNotHaveSchema)
        }
        schema.schema_type = SchemaType::Edge(edge_type);
        self.schemas.new_schema(schema)
    }
    pub fn new_vertex(&self, vertex: Vertex) -> Result<Vertex, NewVertexError> {
        let mut cell = vertex_to_cell_for_write(&self.schemas, vertex)?;
        let header = match self.neb_client.write_cell(&cell) {
            Ok(Ok(header)) => header,
            Ok(Err(e)) => return Err(NewVertexError::WriteError(e)),
            Err(e) => return Err(NewVertexError::RPCError(e))
        };
        cell.header = header;
        Ok(cell_to_vertex(cell))
    }
    // TODO: Update edge list
    pub fn remove_vertex(&self, id: &Id) -> Result<(), TxnError> {
        self.neb_client.transaction(|txn| {
            match txn.read(id)? {
                Some(cell) => {
                    let vertex = cell_to_vertex(cell); // for remove it from neighbourhoods
                    txn.remove(id)
                },
                None => txn.abort()
            }
        })
    }
    pub fn remove_vertex_by_key<K>(&self, schema_id: u32, key: &K) -> Result<(), TxnError>
        where K: Serialize {
        let id = Cell::encode_cell_key(schema_id, key);
        self.remove_vertex(&id)
    }
    pub fn update_vertex<U>(&self, id: &Id, update: U) -> Result<(), TxnError>
        where U: Fn(Vertex) -> Option<Vertex> {
        let update_cell = |cell| {
            match update(cell_to_vertex(cell)) {
                Some(vertex) => Some(vertex_to_cell(vertex)),
                None => None
            }
        };
        self.neb_client.transaction(|txn|{
            let cell = txn.read(id)?;
            match cell {
                Some(cell) => {
                    match update_cell(cell) {
                        Some(cell) => txn.update(&cell),
                        None => txn.abort()
                    }
                },
                None => txn.abort()
            }
        })
    }
    pub fn update_vertex_by_key<K, U>(&self, schema_id: u32, key: &K, update: U)
        -> Result<(), TxnError>
        where K: Serialize, U: Fn(Vertex) -> Option<Vertex>{
        let id = Cell::encode_cell_key(schema_id, key);
        self.update_vertex(&id, update)
    }

}<|endoftext|>


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

//! Various macro helpers.

macro_rules! exclusive_value {
    (($value:ident, $set:expr) => $ident:path) => {
        if $value.intersects($set) {
            return Err(());
        } else {
            $ident
        }
    };
}

#[cfg(feature = "gecko")]
macro_rules! impl_gecko_keyword_conversions {
    ($name:ident, $utype:ty) => {
        impl From<$utype> for $name {
            fn from(bits: $utype) -> $name {
                $name::from_gecko_keyword(bits)
            }
        }

        impl From<$name> for $utype {
            fn from(v: $name) -> $utype {
                v.to_gecko_keyword()
            }
        }
    };
}

macro_rules! trivial_to_computed_value {
    ($name:ty) => {
        impl $crate::values::computed::ToComputedValue for $name {
            type ComputedValue = $name;

            fn to_computed_value(&self, _: &$crate::values::computed::Context) -> Self {
                self.clone()
            }

            fn from_computed_value(other: &Self) -> Self {
                other.clone()
            }
        }
    };
}

/// A macro to parse an identifier, or return an `UnexpectedIndent` error
/// otherwise.
///
/// FIXME(emilio): The fact that `UnexpectedIdent` is a `SelectorParseError`
/// doesn't make a lot of sense to me.
macro_rules! try_match_ident_ignore_ascii_case {
    ($input:expr, $( $match_body:tt )*) => {{
        let location = $input.current_source_location();
        let ident = $input.expect_ident_cloned()?;
        match_ignore_ascii_case! { &ident,
            $( $match_body )*
            _ => return Err(location.new_custom_error(
                ::selectors::parser::SelectorParseErrorKind::UnexpectedIdent(ident.clone())
            ))
        }
    }}
}

macro_rules! define_keyword_type {
    ($name:ident, $css:expr) => {
        #[allow(missing_docs)]
        #[derive(Animate, Clone, ComputeSquaredDistance, Copy, MallocSizeOf, PartialEq,
                 ToAnimatedValue, ToAnimatedZero, ToComputedValue, ToCss)]
        pub struct $name;

        impl fmt::Debug for $name {
            fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
                f.write_str($css)
            }
        }

        impl $crate::parser::Parse for $name {
            fn parse<'i, 't>(
                _context: &$crate::parser::ParserContext,
                input: &mut ::cssparser::Parser<'i, 't>,
            ) -> Result<$name, ::style_traits::ParseError<'i>> {
                input
                    .expect_ident_matching($css)
                    .map(|_| $name)
                    .map_err(|e| e.into())
            }
        }
    };
}

#[cfg(feature = "gecko")]
macro_rules! impl_bitflags_conversions {
    ($name:ident) => {
        impl From<u8> for $name {
            fn from(bits: u8) -> $name {
                $name::from_bits(bits).expect("bits contain valid flag")
            }
        }

        impl From<$name> for u8 {
            fn from(v: $name) -> u8 {
                v.bits()
            }
        }
    };
}
<commit_msg>Fix error name in comment for try_match_ident_ignore_ascii_case<commit_after>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

//! Various macro helpers.

macro_rules! exclusive_value {
    (($value:ident, $set:expr) => $ident:path) => {
        if $value.intersects($set) {
            return Err(());
        } else {
            $ident
        }
    };
}

#[cfg(feature = "gecko")]
macro_rules! impl_gecko_keyword_conversions {
    ($name:ident, $utype:ty) => {
        impl From<$utype> for $name {
            fn from(bits: $utype) -> $name {
                $name::from_gecko_keyword(bits)
            }
        }

        impl From<$name> for $utype {
            fn from(v: $name) -> $utype {
                v.to_gecko_keyword()
            }
        }
    };
}

macro_rules! trivial_to_computed_value {
    ($name:ty) => {
        impl $crate::values::computed::ToComputedValue for $name {
            type ComputedValue = $name;

            fn to_computed_value(&self, _: &$crate::values::computed::Context) -> Self {
                self.clone()
            }

            fn from_computed_value(other: &Self) -> Self {
                other.clone()
            }
        }
    };
}

/// A macro to parse an identifier, or return an `UnexpectedIdent` error
/// otherwise.
///
/// FIXME(emilio): The fact that `UnexpectedIdent` is a `SelectorParseError`
/// doesn't make a lot of sense to me.
macro_rules! try_match_ident_ignore_ascii_case {
    ($input:expr, $( $match_body:tt )*) => {{
        let location = $input.current_source_location();
        let ident = $input.expect_ident_cloned()?;
        match_ignore_ascii_case! { &ident,
            $( $match_body )*
            _ => return Err(location.new_custom_error(
                ::selectors::parser::SelectorParseErrorKind::UnexpectedIdent(ident.clone())
            ))
        }
    }}
}

macro_rules! define_keyword_type {
    ($name:ident, $css:expr) => {
        #[allow(missing_docs)]
        #[derive(Animate, Clone, ComputeSquaredDistance, Copy, MallocSizeOf, PartialEq,
                 ToAnimatedValue, ToAnimatedZero, ToComputedValue, ToCss)]
        pub struct $name;

        impl fmt::Debug for $name {
            fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
                f.write_str($css)
            }
        }

        impl $crate::parser::Parse for $name {
            fn parse<'i, 't>(
                _context: &$crate::parser::ParserContext,
                input: &mut ::cssparser::Parser<'i, 't>,
            ) -> Result<$name, ::style_traits::ParseError<'i>> {
                input
                    .expect_ident_matching($css)
                    .map(|_| $name)
                    .map_err(|e| e.into())
            }
        }
    };
}

#[cfg(feature = "gecko")]
macro_rules! impl_bitflags_conversions {
    ($name:ident) => {
        impl From<u8> for $name {
            fn from(bits: u8) -> $name {
                $name::from_bits(bits).expect("bits contain valid flag")
            }
        }

        impl From<$name> for u8 {
            fn from(v: $name) -> u8 {
                v.bits()
            }
        }
    };
}
<|endoftext|>


<commit_before>//! # TreeView Sample
//!
//! This sample demonstrates how to create a TreeView with either a ListStore or TreeStore.

#![feature(globs)]
#![crate_type = "bin"]

extern crate rgtk;

use rgtk::*;
use rgtk::gtk::signals;
use std::ptr;

fn append_text_column(tree: &mut gtk::TreeView) {
    let column = gtk::TreeViewColumn::new().unwrap();
    let cell = gtk::CellRendererText::new().unwrap();
    column.pack_start(&cell, true);
    column.add_attribute(&cell, "text", 0);
    tree.append_column(&column);
}

fn main() {
    gtk::init();

    let mut window = gtk::Window::new(gtk::window_type::TopLevel).unwrap();
    window.set_title("TreeView Sample");
    window.set_window_position(gtk::window_position::Center);

    window.connect(signals::DeleteEvent::new(|_| {
        gtk::main_quit();
        true
    }));

    // left pane

    let mut left_tree = gtk::TreeView::new().unwrap();
    let column_types = vec![glib::ffi::g_type_string];
    let left_store = gtk::ListStore::new(column_types).unwrap();
    let left_model = left_store.get_model().unwrap();
    left_tree.set_model(&left_model);
    left_tree.set_headers_visible(false);
    append_text_column(&mut left_tree);

    let mut iter = gtk::ffi::C_GtkTreeIter;
    left_model.get_iter_first(&mut iter);
    for _ in range(0i, 10i) {
        left_store.append(&mut iter);
        left_store.set_column_text(&mut iter, 0, "I'm in a list");
    }

    // right pane

    let mut right_tree = gtk::TreeView::new().unwrap();
    let column_types = vec![glib::ffi::g_type_string];
    let right_store = gtk::TreeStore::new(column_types).unwrap();
    let right_model = right_store.get_model().unwrap();
    right_tree.set_model(&right_model);
    right_tree.set_headers_visible(false);
    append_text_column(&mut right_tree);

    let mut iter = gtk::ffi::C_GtkTreeIter;
    right_model.get_iter_first(&mut iter);
    for _ in range(0i, 10i) {
        right_store.append(&mut iter, ptr::null_mut());
        right_store.set_column_text(&mut iter, 0, "I'm in a tree");

        let mut child = gtk::ffi::C_GtkTreeIter;
        right_store.append(&mut child, &mut iter);
        right_store.set_column_text(&mut child, 0, "I'm a child node");
    }

    // display the panes

    let mut split_pane = gtk::Box::new(gtk::orientation::Horizontal, 10).unwrap();
    split_pane.set_size_request(-1, -1);
    split_pane.add(&left_tree);
    split_pane.add(&right_tree);

	window.add(&split_pane);
    window.show_all();
    gtk::main();
}
<commit_msg>Fix indentation<commit_after>//! # TreeView Sample
//!
//! This sample demonstrates how to create a TreeView with either a ListStore or TreeStore.

#![feature(globs)]
#![crate_type = "bin"]

extern crate rgtk;

use rgtk::*;
use rgtk::gtk::signals;
use std::ptr;

fn append_text_column(tree: &mut gtk::TreeView) {
    let column = gtk::TreeViewColumn::new().unwrap();
    let cell = gtk::CellRendererText::new().unwrap();
    column.pack_start(&cell, true);
    column.add_attribute(&cell, "text", 0);
    tree.append_column(&column);
}

fn main() {
    gtk::init();

    let mut window = gtk::Window::new(gtk::window_type::TopLevel).unwrap();
    window.set_title("TreeView Sample");
    window.set_window_position(gtk::window_position::Center);

    window.connect(signals::DeleteEvent::new(|_| {
        gtk::main_quit();
        true
    }));

    // left pane

    let mut left_tree = gtk::TreeView::new().unwrap();
    let column_types = vec![glib::ffi::g_type_string];
    let left_store = gtk::ListStore::new(column_types).unwrap();
    let left_model = left_store.get_model().unwrap();
    left_tree.set_model(&left_model);
    left_tree.set_headers_visible(false);
    append_text_column(&mut left_tree);

    let mut iter = gtk::ffi::C_GtkTreeIter;
    left_model.get_iter_first(&mut iter);
    for _ in range(0i, 10i) {
        left_store.append(&mut iter);
        left_store.set_column_text(&mut iter, 0, "I'm in a list");
    }

    // right pane

    let mut right_tree = gtk::TreeView::new().unwrap();
    let column_types = vec![glib::ffi::g_type_string];
    let right_store = gtk::TreeStore::new(column_types).unwrap();
    let right_model = right_store.get_model().unwrap();
    right_tree.set_model(&right_model);
    right_tree.set_headers_visible(false);
    append_text_column(&mut right_tree);

    let mut iter = gtk::ffi::C_GtkTreeIter;
    right_model.get_iter_first(&mut iter);
    for _ in range(0i, 10i) {
        right_store.append(&mut iter, ptr::null_mut());
        right_store.set_column_text(&mut iter, 0, "I'm in a tree");

        let mut child = gtk::ffi::C_GtkTreeIter;
        right_store.append(&mut child, &mut iter);
        right_store.set_column_text(&mut child, 0, "I'm a child node");
    }

    // display the panes

    let mut split_pane = gtk::Box::new(gtk::orientation::Horizontal, 10).unwrap();
    split_pane.set_size_request(-1, -1);
    split_pane.add(&left_tree);
    split_pane.add(&right_tree);

    window.add(&split_pane);
    window.show_all();
    gtk::main();
}
<|endoftext|>