<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/. */

use std::sync::Arc;
use DeviceUintRect;

#[repr(C)]
#[derive(Clone, Copy, Debug, Deserialize, Eq, Hash, PartialEq, Serialize)]
pub struct ImageKey(pub u32, pub u32);

impl ImageKey {
    pub fn new(key0: u32, key1: u32) -> ImageKey {
        ImageKey(key0, key1)
    }
}

/// An arbitrary identifier for an external image provided by the
/// application. It must be a unique identifier for each external
/// image.
#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash, Serialize, Deserialize)]
pub struct ExternalImageId(pub u64);

#[repr(u32)]
#[derive(Clone, Copy, Debug, Deserialize, Eq, Hash, PartialEq, Serialize)]
pub enum ImageFormat {
    Invalid  = 0,
    A8       = 1,
    RGB8     = 2,
    RGBA8    = 3,
    RGBAF32  = 4,
}

impl ImageFormat {
    pub fn bytes_per_pixel(self) -> Option<u32> {
        match self {
            ImageFormat::A8 => Some(1),
            ImageFormat::RGB8 => Some(3),
            ImageFormat::RGBA8 => Some(4),
            ImageFormat::RGBAF32 => Some(16),
            ImageFormat::Invalid => None,
        }
    }
}

#[derive(Copy, Clone, Debug, Deserialize, PartialEq, Serialize)]
pub struct ImageDescriptor {
    pub format: ImageFormat,
    pub width: u32,
    pub height: u32,
    pub stride: Option<u32>,
    pub offset: u32,
    pub is_opaque: bool,
}

impl ImageDescriptor {
    pub fn new(width: u32, height: u32, format: ImageFormat, is_opaque: bool) -> Self {
        ImageDescriptor {
            width: width,
            height: height,
            format: format,
            stride: None,
            offset: 0,
            is_opaque: is_opaque,
        }
    }

    pub fn compute_stride(&self) -> u32 {
        self.stride.unwrap_or(self.width * self.format.bytes_per_pixel().unwrap())
    }
}

#[derive(Debug, Copy, Clone, Eq, Hash, PartialEq, Serialize, Deserialize)]
pub enum ExternalImageType {
    Texture2DHandle,    // gl TEXTURE_2D handle
    TextureRectHandle,  // gl TEXTURE_RECT handle
    ExternalBuffer,
}

#[derive(Debug, Copy, Clone, Eq, Hash, PartialEq, Serialize, Deserialize)]
pub struct ExternalImageData {
    pub id: ExternalImageId,
    pub image_type: ExternalImageType,
}

#[derive(Clone, Serialize, Deserialize)]
pub enum ImageData {
    Raw(Arc<Vec<u8>>),
    Blob(Arc<BlobImageData>),
    External(ExternalImageData),
}

impl ImageData {
    pub fn new(bytes: Vec<u8>) -> ImageData {
        ImageData::Raw(Arc::new(bytes))
    }

    pub fn new_shared(bytes: Arc<Vec<u8>>) -> ImageData {
        ImageData::Raw(bytes)
    }

    pub fn new_blob_image(commands: Vec<u8>) -> ImageData {
        ImageData::Blob(Arc::new(commands))
    }

    pub fn new_shared_blob_image(commands: Arc<Vec<u8>>) -> ImageData {
        ImageData::Blob(commands)
    }
}

pub trait BlobImageRenderer: Send {
    fn request_blob_image(&mut self,
                            key: ImageKey,
                            data: Arc<BlobImageData>,
                            descriptor: &BlobImageDescriptor,
                            dirty_rect: Option<DeviceUintRect>);
    fn resolve_blob_image(&mut self, key: ImageKey) -> BlobImageResult;
}

pub type BlobImageData = Vec<u8>;

pub type BlobImageResult = Result<RasterizedBlobImage, BlobImageError>;

#[repr(C)]
#[derive(Copy, Clone, Debug)]
pub struct BlobImageDescriptor {
    pub width: u32,
    pub height: u32,
    pub format: ImageFormat,
    pub scale_factor: f32,
}

pub struct RasterizedBlobImage {
    pub width: u32,
    pub height: u32,
    pub data: Vec<u8>,
}

#[derive(Clone, Debug)]
pub enum BlobImageError {
    Oom,
    InvalidKey,
    InvalidData,
    Other(String),
}
<commit_msg>Add repr(C) to ExternalImageId<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/. */

use std::sync::Arc;
use DeviceUintRect;

#[repr(C)]
#[derive(Clone, Copy, Debug, Deserialize, Eq, Hash, PartialEq, Serialize)]
pub struct ImageKey(pub u32, pub u32);

impl ImageKey {
    pub fn new(key0: u32, key1: u32) -> ImageKey {
        ImageKey(key0, key1)
    }
}

/// An arbitrary identifier for an external image provided by the
/// application. It must be a unique identifier for each external
/// image.
#[repr(C)]
#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash, Serialize, Deserialize)]
pub struct ExternalImageId(pub u64);

#[repr(u32)]
#[derive(Clone, Copy, Debug, Deserialize, Eq, Hash, PartialEq, Serialize)]
pub enum ImageFormat {
    Invalid  = 0,
    A8       = 1,
    RGB8     = 2,
    RGBA8    = 3,
    RGBAF32  = 4,
}

impl ImageFormat {
    pub fn bytes_per_pixel(self) -> Option<u32> {
        match self {
            ImageFormat::A8 => Some(1),
            ImageFormat::RGB8 => Some(3),
            ImageFormat::RGBA8 => Some(4),
            ImageFormat::RGBAF32 => Some(16),
            ImageFormat::Invalid => None,
        }
    }
}

#[derive(Copy, Clone, Debug, Deserialize, PartialEq, Serialize)]
pub struct ImageDescriptor {
    pub format: ImageFormat,
    pub width: u32,
    pub height: u32,
    pub stride: Option<u32>,
    pub offset: u32,
    pub is_opaque: bool,
}

impl ImageDescriptor {
    pub fn new(width: u32, height: u32, format: ImageFormat, is_opaque: bool) -> Self {
        ImageDescriptor {
            width: width,
            height: height,
            format: format,
            stride: None,
            offset: 0,
            is_opaque: is_opaque,
        }
    }

    pub fn compute_stride(&self) -> u32 {
        self.stride.unwrap_or(self.width * self.format.bytes_per_pixel().unwrap())
    }
}

#[derive(Debug, Copy, Clone, Eq, Hash, PartialEq, Serialize, Deserialize)]
pub enum ExternalImageType {
    Texture2DHandle,    // gl TEXTURE_2D handle
    TextureRectHandle,  // gl TEXTURE_RECT handle
    ExternalBuffer,
}

#[derive(Debug, Copy, Clone, Eq, Hash, PartialEq, Serialize, Deserialize)]
pub struct ExternalImageData {
    pub id: ExternalImageId,
    pub image_type: ExternalImageType,
}

#[derive(Clone, Serialize, Deserialize)]
pub enum ImageData {
    Raw(Arc<Vec<u8>>),
    Blob(Arc<BlobImageData>),
    External(ExternalImageData),
}

impl ImageData {
    pub fn new(bytes: Vec<u8>) -> ImageData {
        ImageData::Raw(Arc::new(bytes))
    }

    pub fn new_shared(bytes: Arc<Vec<u8>>) -> ImageData {
        ImageData::Raw(bytes)
    }

    pub fn new_blob_image(commands: Vec<u8>) -> ImageData {
        ImageData::Blob(Arc::new(commands))
    }

    pub fn new_shared_blob_image(commands: Arc<Vec<u8>>) -> ImageData {
        ImageData::Blob(commands)
    }
}

pub trait BlobImageRenderer: Send {
    fn request_blob_image(&mut self,
                            key: ImageKey,
                            data: Arc<BlobImageData>,
                            descriptor: &BlobImageDescriptor,
                            dirty_rect: Option<DeviceUintRect>);
    fn resolve_blob_image(&mut self, key: ImageKey) -> BlobImageResult;
}

pub type BlobImageData = Vec<u8>;

pub type BlobImageResult = Result<RasterizedBlobImage, BlobImageError>;

#[repr(C)]
#[derive(Copy, Clone, Debug)]
pub struct BlobImageDescriptor {
    pub width: u32,
    pub height: u32,
    pub format: ImageFormat,
    pub scale_factor: f32,
}

pub struct RasterizedBlobImage {
    pub width: u32,
    pub height: u32,
    pub data: Vec<u8>,
}

#[derive(Clone, Debug)]
pub enum BlobImageError {
    Oom,
    InvalidKey,
    InvalidData,
    Other(String),
}
<|endoftext|>


<commit_before>use liquid;

#[derive(Clone)]
struct TestFileSystem;

impl liquid::compiler::Include for TestFileSystem {
    fn include(&self, relative_path: &str) -> Result<String, liquid::Error> {
        let template = match relative_path {
            "product" => "Product: {{ product.title }} ",
            "locale_variables" => "Locale: {{echo1}} {{echo2}}",
            "variant" => "Variant: {{ variant.title }}",
            "nested_template" => {
                "{% include 'header' %} {% include 'body' %} {% include 'footer' %}"
            }
            "body" => "body {% include 'body_detail' %}",
            "nested_product_template" => {
                "Product: {{ nested_product_template.title }} {%include 'details'%} "
            }
            "recursively_nested_template" => "-{% include 'recursively_nested_template' %}",
            "pick_a_source" => "from TestFileSystem",
            "assignments" => "{% assign foo = 'bar' %}",
            _ => relative_path,
        };
        Ok(template.to_owned())
    }
}

fn liquid() -> liquid::Parser {
    liquid::ParserBuilder::with_liquid()
        .include_source(Box::new(TestFileSystem))
        .build()
}

#[test]
#[should_panic]
fn test_include_tag_looks_for_file_system_in_registers_first() {
    panic!("Implementation specific: exposing of registers API");
}

#[test]
#[should_panic] // liquid-rust#237
fn test_include_tag_with() {
    assert_template_result!(
        "Product: Draft 151cm ",
        "{% include 'product' with products[0] %}",
        v!({"products": [ { "title": "Draft 151cm" }, { "title": "Element 155cm" } ]}),
        liquid()
    );
}

#[test]
fn test_include_tag_with_default_name() {
    assert_template_result!(
        "Product: Draft 151cm ",
        "{% include 'product' %}",
        v!({"product": { "title": "Draft 151cm" }}),
        liquid()
    );
}

#[test]
#[should_panic] // liquid-rust#237
fn test_include_tag_for() {
    assert_template_result!(
        "Product: Draft 151cm Product: Element 155cm ",
        "{% include 'product' for products %}",
        v!({"products": [ { "title": "Draft 151cm" }, { "title": "Element 155cm" } ]}),
        liquid()
    );
}

#[test]
#[should_panic] // liquid-rust#237
fn test_include_tag_with_local_variables() {
    assert_template_result!(
        "Locale: test123 ",
        "{% include 'locale_variables' echo1: 'test123' %}",
        v!({}),
        liquid()
    );
}

#[test]
#[should_panic] // liquid-rust#237
fn test_include_tag_with_multiple_local_variables() {
    assert_template_result!(
        "Locale: test123 test321",
        "{% include 'locale_variables' echo1: 'test123', echo2: 'test321' %}",
        v!({}),
        liquid()
    );
}

#[test]
#[should_panic] // liquid-rust#237
fn test_include_tag_with_multiple_local_variables_from_context() {
    assert_template_result!(
        "Locale: test123 test321",
        "{% include 'locale_variables' echo1: echo1, echo2: more_echos.echo2 %}",
        v!({"echo1": "test123", "more_echos": { "echo2": "test321" }}),
        liquid()
    );
}

#[test]
fn test_included_templates_assigns_variables() {
    assert_template_result!(
        "bar",
        "{% include 'assignments' %}{{ foo }}",
        v!({}),
        liquid()
    );
}

#[test]
fn test_nested_include_tag() {
    assert_template_result!("body body_detail", "{% include 'body' %}", v!({}), liquid());

    assert_template_result!(
        "header body body_detail footer",
        "{% include 'nested_template' %}",
        v!({}),
        liquid()
    );
}

#[test]
#[should_panic] // liquid-rust#237
fn test_nested_include_with_variable() {
    assert_template_result!(
        "Product: Draft 151cm details ",
        "{% include 'nested_product_template' with product %}",
        v!({"product": { "title": "Draft 151cm" }}),
        liquid()
    );

    assert_template_result!(
        "Product: Draft 151cm details Product: Element 155cm details ",
        "{% include 'nested_product_template' for products %}",
        v!({"products": [{ "title": "Draft 151cm" }, { "title": "Element 155cm" }]}),
        liquid()
    );
}

#[derive(Clone)]
struct InfiniteFileSystem;

impl liquid::compiler::Include for InfiniteFileSystem {
    fn include(&self, _relative_path: &str) -> Result<String, liquid::Error> {
        Ok("-{% include 'loop' %}".to_owned())
    }
}

#[test]
#[should_panic]
fn test_recursively_included_template_does_not_produce_endless_loop() {
    panic!("We don't check recursion depth");
    /*
    let parser = liquid::ParserBuilder::with_liquid().include_source(Box::new(InfiniteFileSystem)).build();
    parser.parse("{% include 'loop' %}").unwrap();
    */
}

#[test]
#[should_panic] // liquid-rust#275
fn test_dynamically_choosen_template() {
    assert_template_result!(
        "Test123",
        "{% include template %}",
        v!({"template": "Test123"}),
        liquid()
    );
    assert_template_result!(
        "Test321",
        "{% include template %}",
        v!({"template": "Test321"}),
        liquid()
    );

    assert_template_result!(
        "Product: Draft 151cm ",
        "{% include template for product %}",
        v!({"template": "product", "product": { "title": "Draft 151cm" }}),
        liquid()
    );
}

#[test]
#[should_panic]
fn test_include_tag_caches_second_read_of_same_partial() {
    panic!("Implementation specific: caching policies");
}

#[test]
#[should_panic]
fn test_include_tag_doesnt_cache_partials_across_renders() {
    panic!("Implementation specific: caching policies");
}

#[test]
fn test_include_tag_within_if_statement() {
    assert_template_result!(
        "foo_if_true",
        "{% if true %}{% include 'foo_if_true' %}{% endif %}",
        v!({}),
        liquid()
    );
}

#[test]
#[should_panic]
fn test_custom_include_tag() {
    panic!("Implementation specific: API customization");
}

#[test]
#[should_panic]
fn test_custom_include_tag_within_if_statement() {
    panic!("Implementation specific: API customization");
}

#[test]
fn test_does_not_add_error_in_strict_mode_for_missing_variable() {
    let template = liquid()
        .parse(r#" {% include "nested_template" %}"#)
        .unwrap();
    template.render(v!({}).as_object().unwrap()).unwrap();
}

#[test]
#[should_panic]
fn test_passing_options_to_included_templates() {
    panic!("Implementation specific: API options");
}

#[test]
#[should_panic] // liquid-rust#275
fn test_render_raise_argument_error_when_template_is_undefined() {
    assert_parse_error!("{% include undefined_variable %}", liquid());
    assert_parse_error!("{% include nil %}", liquid());
}

#[test]
#[should_panic] // liquid-rust#275
fn test_including_via_variable_value() {
    assert_template_result!(
        "from TestFileSystem",
        "{% assign page = 'pick_a_source' %}{% include page %}",
        v!({}),
        liquid()
    );

    assert_template_result!(
        "Product: Draft 151cm ",
        "{% assign page = 'product' %}{% include page %}",
        v!({"product": { "title": "Draft 151cm" }}),
        liquid()
    );

    assert_template_result!(
        "Product: Draft 151cm ",
        "{% assign page = 'product' %}{% include page for foo %}",
        v!({"foo": { "title": "Draft 151cm" }}),
        liquid()
    );
}

#[test]
fn test_including_with_strict_variables() {
    let template = liquid().parse("{% include 'simple' %}").unwrap();
    template.render(v!({}).as_object().unwrap()).unwrap();
}
<commit_msg>tests: Note issue for infinite recursion<commit_after>use liquid;

#[derive(Clone)]
struct TestFileSystem;

impl liquid::compiler::Include for TestFileSystem {
    fn include(&self, relative_path: &str) -> Result<String, liquid::Error> {
        let template = match relative_path {
            "product" => "Product: {{ product.title }} ",
            "locale_variables" => "Locale: {{echo1}} {{echo2}}",
            "variant" => "Variant: {{ variant.title }}",
            "nested_template" => {
                "{% include 'header' %} {% include 'body' %} {% include 'footer' %}"
            }
            "body" => "body {% include 'body_detail' %}",
            "nested_product_template" => {
                "Product: {{ nested_product_template.title }} {%include 'details'%} "
            }
            "recursively_nested_template" => "-{% include 'recursively_nested_template' %}",
            "pick_a_source" => "from TestFileSystem",
            "assignments" => "{% assign foo = 'bar' %}",
            _ => relative_path,
        };
        Ok(template.to_owned())
    }
}

fn liquid() -> liquid::Parser {
    liquid::ParserBuilder::with_liquid()
        .include_source(Box::new(TestFileSystem))
        .build()
}

#[test]
#[should_panic]
fn test_include_tag_looks_for_file_system_in_registers_first() {
    panic!("Implementation specific: exposing of registers API");
}

#[test]
#[should_panic] // liquid-rust#237
fn test_include_tag_with() {
    assert_template_result!(
        "Product: Draft 151cm ",
        "{% include 'product' with products[0] %}",
        v!({"products": [ { "title": "Draft 151cm" }, { "title": "Element 155cm" } ]}),
        liquid()
    );
}

#[test]
fn test_include_tag_with_default_name() {
    assert_template_result!(
        "Product: Draft 151cm ",
        "{% include 'product' %}",
        v!({"product": { "title": "Draft 151cm" }}),
        liquid()
    );
}

#[test]
#[should_panic] // liquid-rust#237
fn test_include_tag_for() {
    assert_template_result!(
        "Product: Draft 151cm Product: Element 155cm ",
        "{% include 'product' for products %}",
        v!({"products": [ { "title": "Draft 151cm" }, { "title": "Element 155cm" } ]}),
        liquid()
    );
}

#[test]
#[should_panic] // liquid-rust#237
fn test_include_tag_with_local_variables() {
    assert_template_result!(
        "Locale: test123 ",
        "{% include 'locale_variables' echo1: 'test123' %}",
        v!({}),
        liquid()
    );
}

#[test]
#[should_panic] // liquid-rust#237
fn test_include_tag_with_multiple_local_variables() {
    assert_template_result!(
        "Locale: test123 test321",
        "{% include 'locale_variables' echo1: 'test123', echo2: 'test321' %}",
        v!({}),
        liquid()
    );
}

#[test]
#[should_panic] // liquid-rust#237
fn test_include_tag_with_multiple_local_variables_from_context() {
    assert_template_result!(
        "Locale: test123 test321",
        "{% include 'locale_variables' echo1: echo1, echo2: more_echos.echo2 %}",
        v!({"echo1": "test123", "more_echos": { "echo2": "test321" }}),
        liquid()
    );
}

#[test]
fn test_included_templates_assigns_variables() {
    assert_template_result!(
        "bar",
        "{% include 'assignments' %}{{ foo }}",
        v!({}),
        liquid()
    );
}

#[test]
fn test_nested_include_tag() {
    assert_template_result!("body body_detail", "{% include 'body' %}", v!({}), liquid());

    assert_template_result!(
        "header body body_detail footer",
        "{% include 'nested_template' %}",
        v!({}),
        liquid()
    );
}

#[test]
#[should_panic] // liquid-rust#237
fn test_nested_include_with_variable() {
    assert_template_result!(
        "Product: Draft 151cm details ",
        "{% include 'nested_product_template' with product %}",
        v!({"product": { "title": "Draft 151cm" }}),
        liquid()
    );

    assert_template_result!(
        "Product: Draft 151cm details Product: Element 155cm details ",
        "{% include 'nested_product_template' for products %}",
        v!({"products": [{ "title": "Draft 151cm" }, { "title": "Element 155cm" }]}),
        liquid()
    );
}

#[derive(Clone)]
struct InfiniteFileSystem;

impl liquid::compiler::Include for InfiniteFileSystem {
    fn include(&self, _relative_path: &str) -> Result<String, liquid::Error> {
        Ok("-{% include 'loop' %}".to_owned())
    }
}

#[test]
#[should_panic] // liquid-rust#300
fn test_recursively_included_template_does_not_produce_endless_loop() {
    panic!("We don't check recursion depth");
    /*
    let parser = liquid::ParserBuilder::with_liquid().include_source(Box::new(InfiniteFileSystem)).build();
    parser.parse("{% include 'loop' %}").unwrap();
    */
}

#[test]
#[should_panic] // liquid-rust#275
fn test_dynamically_choosen_template() {
    assert_template_result!(
        "Test123",
        "{% include template %}",
        v!({"template": "Test123"}),
        liquid()
    );
    assert_template_result!(
        "Test321",
        "{% include template %}",
        v!({"template": "Test321"}),
        liquid()
    );

    assert_template_result!(
        "Product: Draft 151cm ",
        "{% include template for product %}",
        v!({"template": "product", "product": { "title": "Draft 151cm" }}),
        liquid()
    );
}

#[test]
#[should_panic]
fn test_include_tag_caches_second_read_of_same_partial() {
    panic!("Implementation specific: caching policies");
}

#[test]
#[should_panic]
fn test_include_tag_doesnt_cache_partials_across_renders() {
    panic!("Implementation specific: caching policies");
}

#[test]
fn test_include_tag_within_if_statement() {
    assert_template_result!(
        "foo_if_true",
        "{% if true %}{% include 'foo_if_true' %}{% endif %}",
        v!({}),
        liquid()
    );
}

#[test]
#[should_panic]
fn test_custom_include_tag() {
    panic!("Implementation specific: API customization");
}

#[test]
#[should_panic]
fn test_custom_include_tag_within_if_statement() {
    panic!("Implementation specific: API customization");
}

#[test]
fn test_does_not_add_error_in_strict_mode_for_missing_variable() {
    let template = liquid()
        .parse(r#" {% include "nested_template" %}"#)
        .unwrap();
    template.render(v!({}).as_object().unwrap()).unwrap();
}

#[test]
#[should_panic]
fn test_passing_options_to_included_templates() {
    panic!("Implementation specific: API options");
}

#[test]
#[should_panic] // liquid-rust#275
fn test_render_raise_argument_error_when_template_is_undefined() {
    assert_parse_error!("{% include undefined_variable %}", liquid());
    assert_parse_error!("{% include nil %}", liquid());
}

#[test]
#[should_panic] // liquid-rust#275
fn test_including_via_variable_value() {
    assert_template_result!(
        "from TestFileSystem",
        "{% assign page = 'pick_a_source' %}{% include page %}",
        v!({}),
        liquid()
    );

    assert_template_result!(
        "Product: Draft 151cm ",
        "{% assign page = 'product' %}{% include page %}",
        v!({"product": { "title": "Draft 151cm" }}),
        liquid()
    );

    assert_template_result!(
        "Product: Draft 151cm ",
        "{% assign page = 'product' %}{% include page for foo %}",
        v!({"foo": { "title": "Draft 151cm" }}),
        liquid()
    );
}

#[test]
fn test_including_with_strict_variables() {
    let template = liquid().parse("{% include 'simple' %}").unwrap();
    template.render(v!({}).as_object().unwrap()).unwrap();
}
<|endoftext|>


<commit_before>use chattium_oxide_lib::json::{FromJsonnable, ToJsonnable};
use chattium_oxide_lib::ChatMessage;
use hyper::server::{Handler, Request, Response};
use hyper::header::{ContentLength, ContentType};
use hyper::status::StatusCode;
use hyper::method::Method;
use time::{strftime, Tm};
use std::sync::RwLock;
use std::io::{Read, Write, stderr};

pub struct ClientHandler {
	messages: RwLock<Vec<ChatMessage>>,
}

impl ClientHandler {
	pub fn new() -> ClientHandler {
		ClientHandler{
			messages: RwLock::new(Vec::new()),
		}
	}
}

impl Handler for ClientHandler {
	fn handle(&self, req: Request, mut res: Response) {
		let mut req = req;
		let mut body = "".to_string();

		let mut reqbody = String::new();
		*res.status_mut() = match req.read_to_string(&mut reqbody) {
			Ok(_) =>
				match req.method {
					Method::Post =>
						match ChatMessage::from_json_string(&reqbody) {
							Ok(mut message) => {
								message.sender.fill_ip(req.remote_addr);
								println!("{}: {} @ {}", message.sender.name, message.value, strftime("%T", &message.time_posted).unwrap());
								self.messages.write().unwrap().push(message);
								StatusCode::Ok
							},
							Err(error) => {
								let _ = stderr().write_fmt(format_args!("Couldn't process POSTed message from {}: {}\n", req.remote_addr, error));
								StatusCode::UnprocessableEntity
							},
						},
					Method::Get => {  // Web browser
						body = format!("{}, use chattium-oxide-client to connect to chat",
						               req.remote_addr);
						res.headers_mut().set(ContentType::html());
						StatusCode::Ok
					},
					Method::Trace => {
						match Tm::from_json_string(&reqbody) {
							Ok(ts) => {
								let messages = self.messages.read().unwrap();
								let msgs: Vec<ChatMessage> = messages.iter().rev().take_while(|&m| m.time_posted >= ts).collect::<Vec<&_>>().iter().rev().map(|&m| m.clone()).collect();
								match msgs.to_json_string() {
									Ok(msgs) => {
										body = msgs;
										StatusCode::Ok
									},
									Err(error) => {
										let _ = stderr().write_fmt(format_args!("Couldn't create a JSON response for {}: {}\n", req.remote_addr, error));
										body = "[]".to_string();  // Empty array
										StatusCode::Accepted
									},
								}
							},
							Err(error) => {
								let _ = stderr().write_fmt(format_args!("Couldn't process a TRACE timestamp ({:?}) {}: {}\n", reqbody, req.remote_addr, error));
								StatusCode::UnprocessableEntity
							},
						}
					},
				  _ => StatusCode::ImATeapot,
				},
			Err(error) => {
				let _ = stderr().write_fmt(format_args!("Failed reading request from {}: {}\n", req.remote_addr, error));
				StatusCode::UnsupportedMediaType  // non-UTF-8
			},
		};

		res.headers_mut().set(ContentLength(body.len() as u64));
		if let Err(error) = res.start().unwrap().write_all(body.as_bytes()) {
			let _ = stderr().write_fmt(format_args!("Failed to respond to {}: {}", req.remote_addr, error));
		}
	}
}
<commit_msg>Formatting<commit_after>use chattium_oxide_lib::json::{FromJsonnable, ToJsonnable};
use chattium_oxide_lib::ChatMessage;
use hyper::server::{Handler, Request, Response};
use hyper::header::{ContentLength, ContentType};
use hyper::status::StatusCode;
use hyper::method::Method;
use time::{strftime, Tm};
use std::sync::RwLock;
use std::io::{Read, Write, stderr};

pub struct ClientHandler {
	messages: RwLock<Vec<ChatMessage>>,
}

impl ClientHandler {
	pub fn new() -> ClientHandler {
		ClientHandler{
			messages: RwLock::new(Vec::new()),
		}
	}
}

impl Handler for ClientHandler {
	fn handle(&self, req: Request, mut res: Response) {
		let mut req = req;
		let mut body = "".to_string();

		let mut reqbody = String::new();
		*res.status_mut() = match req.read_to_string(&mut reqbody) {
			Ok(_) =>
				match req.method {
					Method::Post =>
						match ChatMessage::from_json_string(&reqbody) {
							Ok(mut message) => {
								message.sender.fill_ip(req.remote_addr);
								println!("{}: {} @ {}", message.sender.name, message.value, strftime("%T", &message.time_posted).unwrap());
								self.messages.write().unwrap().push(message);
								StatusCode::Ok
							},
							Err(error) => {
								let _ = stderr().write_fmt(format_args!("Couldn't process POSTed message from {}: {}\n", req.remote_addr, error));
								StatusCode::UnprocessableEntity
							},
						},
					Method::Get => {  // Web browser
						body = format!("{}, use chattium-oxide-client to connect to chat",
						               req.remote_addr);
						res.headers_mut().set(ContentType::html());
						StatusCode::Ok
					},
					Method::Trace => {
						match Tm::from_json_string(&reqbody) {
							Ok(ts) => {
								let messages = self.messages.read().unwrap();
								let msgs: Vec<ChatMessage> = messages.iter().rev().take_while(|&m| m.time_posted >= ts).collect::<Vec<&_>>()
								                                     .iter().rev().map(|&m| m.clone()).collect();
								match msgs.to_json_string() {
									Ok(msgs) => {
										body = msgs;
										StatusCode::Ok
									},
									Err(error) => {
										let _ = stderr().write_fmt(format_args!("Couldn't create a JSON response for {}: {}\n", req.remote_addr, error));
										body = "[]".to_string();  // Empty array
										StatusCode::Accepted
									},
								}
							},
							Err(error) => {
								let _ = stderr().write_fmt(format_args!("Couldn't process a TRACE timestamp ({:?}) {}: {}\n", reqbody, req.remote_addr, error));
								StatusCode::UnprocessableEntity
							},
						}
					},
				  _ => StatusCode::ImATeapot,
				},
			Err(error) => {
				let _ = stderr().write_fmt(format_args!("Failed reading request from {}: {}\n", req.remote_addr, error));
				StatusCode::UnsupportedMediaType  // non-UTF-8
			},
		};

		res.headers_mut().set(ContentLength(body.len() as u64));
		if let Err(error) = res.start().unwrap().write_all(body.as_bytes()) {
			let _ = stderr().write_fmt(format_args!("Failed to respond to {}: {}", req.remote_addr, error));
		}
	}
}
<|endoftext|>


<commit_before>// Copyright (C) 2019 O.S. Systems Sofware LTDA
//
// SPDX-License-Identifier: Apache-2.0

#[macro_use]
mod macros;

pub(crate) mod info;
pub(crate) mod installer;

pub(crate) use self::{info::Info, installer::Installer};
use derive_more::{Display, Error, From};

pub type Result<T> = std::result::Result<T, Error>;

#[derive(Debug, Display, Error, From)]
pub enum Error {
    #[display("Invalid path formed")]
    InvalidPath,
    #[display("'fw_setenv' does not support the --script command line option")]
    FwSetEnvNoScriptOption,
    #[display("Unsupported object model")]
    Unsupported,

    Utils(crate::utils::Error),
    Firmware(crate::firmware::Error),

    #[display(fmt = "Invalid target type {:?}", _0)]
    InvalidTargetType(#[error(not(source))] pkg_schema::definitions::TargetType),
    Io(std::io::Error),
    Process(easy_process::Error),
    Uncompress(compress_tools::Error),
}
<commit_msg>updatehub: object: Use lowercase error messages<commit_after>// Copyright (C) 2019 O.S. Systems Sofware LTDA
//
// SPDX-License-Identifier: Apache-2.0

#[macro_use]
mod macros;

pub(crate) mod info;
pub(crate) mod installer;

pub(crate) use self::{info::Info, installer::Installer};
use derive_more::{Display, Error, From};

pub type Result<T> = std::result::Result<T, Error>;

#[derive(Debug, Display, Error, From)]
pub enum Error {
    #[display("invalid path formed")]
    InvalidPath,
    #[display("'fw_setenv' does not support the --script command line option")]
    FwSetEnvNoScriptOption,
    #[display("unsupported object model")]
    Unsupported,

    Utils(crate::utils::Error),
    Firmware(crate::firmware::Error),

    #[display(fmt = "invalid target type {:?}", _0)]
    InvalidTargetType(#[error(not(source))] pkg_schema::definitions::TargetType),
    Io(std::io::Error),
    Process(easy_process::Error),
    Uncompress(compress_tools::Error),
}
<|endoftext|>


<commit_before>#![no_main]
use libfuzzer_sys::fuzz_target;
use std::io::{Error, Write};
use std::process::{Command, Stdio};

use jpeg_decoder::Decoder;

// Try to check the image, never panic.
fn soft_check(data: &[u8]) -> Result<(), Error> {
    let mut check = Command::new("convert")
        .arg("-verbose")
        .arg("-")
        .arg("/tmp/fail.png")
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .spawn()?;

    {
        let mut stdin = match check.stdin.take() {
            None => return Err(Error::from(std::io::ErrorKind::Other)),
            Some(stdin) => stdin,
        };

        stdin.write_all(data)?;
        stdin.flush()?;
    }

    let output = check.wait_with_output()?;
    if !output.status.success() {
        return Err(Error::from(std::io::ErrorKind::Other));
    }

    let mut iter = output.stdout.iter();
    // Should still contain JPEG somewhere.
    loop {
        if iter.as_slice().starts_with(b"JPEG") {
            break;
        }
        match iter.next() {
            None => return Err(Error::from(std::io::ErrorKind::Other)),
            Some(_) => {},
        }
    }

    let mut iter = output.stderr.iter();
    // But should not be marked corrupt.
    loop {
        if iter.as_slice().starts_with(b"Corrupt") {
            return Err(Error::from(std::io::ErrorKind::Other));
        }
        match iter.next() {
            None => break,
            Some(_) => {},
        }
    }

    Ok(())
}

fuzz_target!(|data: &[u8]| {
    match soft_check(data) {
        Ok(_) => {}, // Now crash.
        Err(_) => return, // Don't crash if it's not a jpeg.
    }

    let mut decoder = Decoder::new(data);
    let _ = decoder.decode().expect("");
});
<commit_msg>Switch to djpeg<commit_after>#![no_main]
use libfuzzer_sys::fuzz_target;
use std::io::{Error, Write};
use std::process::{Command, Stdio};

use jpeg_decoder::Decoder;

// Try to check the image, never panic.
fn soft_check(data: &[u8]) -> Result<(), Error> {
    let mut check = Command::new("djpeg")
        .arg("-fast")
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .spawn()?;

    {
        let mut stdin = match check.stdin.take() {
            None => return Err(Error::from(std::io::ErrorKind::Other)),
            Some(stdin) => stdin,
        };

        stdin.write_all(data)?;
        stdin.flush()?;
    }

    let output = check.wait_with_output()?;
    if !output.status.success() {
        return Err(Error::from(std::io::ErrorKind::Other));
    }

    Ok(())
}

fuzz_target!(|data: &[u8]| {
    match soft_check(data) {
        Ok(_) => {}, // Now crash.
        Err(_) => return, // Don't crash if it's not a jpeg.
    }

    let mut decoder = Decoder::new(data);
    let _ = decoder.decode().expect("");
});
<|endoftext|>


<commit_before>// `cargo test --benches` and `#[feature(test)]` work only in nightly
#![cfg(rustc_nightly)]
#![cfg(feature = "bytes")]
#![feature(test)]

extern crate bytes;
extern crate test;

extern crate protobuf;

extern crate perftest_bytes;

use std::fmt::Write;

use bytes::Bytes;

use perftest_bytes::messages;
use protobuf::Message;

fn make_string_of_len(len: usize) -> String {
    let mut s = String::new();
    for i in 0..len {
        write!(s, "{}", i % 10).expect("unreachable");
    }
    s
}

fn make_repeated(len: usize) -> Vec<u8> {
    let mut m = messages::TestMessage::new();

    for i in 0..100 {
        m.mut_sr().push(make_string_of_len(i % len));
        m.mut_br()
            .push(make_string_of_len((i + len / 2) % len).into_bytes());
    }

    m.write_to_bytes().expect("write")
}

#[bench]
fn parse_repeated_small_regular(b: &mut test::Bencher) {
    let bs = make_repeated(30);
    b.iter(|| protobuf::parse_from_bytes::<messages::TestMessage>(&bs).expect("parse"))
}

#[bench]
fn parse_repeated_small_bytes(b: &mut test::Bencher) {
    let bs = Bytes::from(make_repeated(30));
    b.iter(|| {
        protobuf::parse_from_carllerche_bytes::<messages::TestMessageWithBytes>(&bs).expect("parse")
    })
}

#[bench]
fn parse_repeated_medium_regular(b: &mut test::Bencher) {
    let bs = make_repeated(300);
    b.iter(|| protobuf::parse_from_bytes::<messages::TestMessage>(&bs).expect("parse"))
}

#[bench]
fn parse_repeated_medium_bytes(b: &mut test::Bencher) {
    let bs = Bytes::from(make_repeated(300));
    b.iter(|| {
        protobuf::parse_from_carllerche_bytes::<messages::TestMessageWithBytes>(&bs).expect("parse")
    })
}

#[bench]
fn parse_repeated_large_regular(b: &mut test::Bencher) {
    let bs = make_repeated(3000);
    b.iter(|| protobuf::parse_from_bytes::<messages::TestMessage>(&bs).expect("parse"))
}

#[bench]
fn parse_repeated_large_bytes(b: &mut test::Bencher) {
    let bs = Bytes::from(make_repeated(3000));
    b.iter(|| {
        protobuf::parse_from_carllerche_bytes::<messages::TestMessageWithBytes>(&bs).expect("parse")
    })
}

#[bench]
fn parse_repeated_huge_regular(b: &mut test::Bencher) {
    let bs = make_repeated(30000);
    b.iter(|| protobuf::parse_from_bytes::<messages::TestMessage>(&bs).expect("parse"))
}

#[bench]
fn parse_repeated_huge_bytes(b: &mut test::Bencher) {
    let bs = Bytes::from(make_repeated(30000));
    b.iter(|| {
        protobuf::parse_from_carllerche_bytes::<messages::TestMessageWithBytes>(&bs).expect("parse")
    })
}
<commit_msg>Fix bench<commit_after>// `cargo test --benches` and `#[feature(test)]` work only in nightly
#![cfg(rustc_nightly)]
#![cfg(feature = "bytes")]
#![feature(test)]

extern crate bytes;
extern crate test;

extern crate protobuf;

extern crate perftest_bytes;

use std::fmt::Write;

use bytes::Bytes;

use perftest_bytes::messages;
use protobuf::Message;

fn make_string_of_len(len: usize) -> String {
    let mut s = String::new();
    for i in 0..len {
        write!(s, "{}", i % 10).expect("unreachable");
    }
    s
}

fn make_repeated(len: usize) -> Vec<u8> {
    let mut m = messages::TestMessage::new();

    for i in 0..100 {
        m.sr.push(make_string_of_len(i % len));
        m.br.push(make_string_of_len((i + len / 2) % len).into_bytes());
    }

    m.write_to_bytes().expect("write")
}

#[bench]
fn parse_repeated_small_regular(b: &mut test::Bencher) {
    let bs = make_repeated(30);
    b.iter(|| protobuf::parse_from_bytes::<messages::TestMessage>(&bs).expect("parse"))
}

#[bench]
fn parse_repeated_small_bytes(b: &mut test::Bencher) {
    let bs = Bytes::from(make_repeated(30));
    b.iter(|| {
        protobuf::parse_from_carllerche_bytes::<messages::TestMessageWithBytes>(&bs).expect("parse")
    })
}

#[bench]
fn parse_repeated_medium_regular(b: &mut test::Bencher) {
    let bs = make_repeated(300);
    b.iter(|| protobuf::parse_from_bytes::<messages::TestMessage>(&bs).expect("parse"))
}

#[bench]
fn parse_repeated_medium_bytes(b: &mut test::Bencher) {
    let bs = Bytes::from(make_repeated(300));
    b.iter(|| {
        protobuf::parse_from_carllerche_bytes::<messages::TestMessageWithBytes>(&bs).expect("parse")
    })
}

#[bench]
fn parse_repeated_large_regular(b: &mut test::Bencher) {
    let bs = make_repeated(3000);
    b.iter(|| protobuf::parse_from_bytes::<messages::TestMessage>(&bs).expect("parse"))
}

#[bench]
fn parse_repeated_large_bytes(b: &mut test::Bencher) {
    let bs = Bytes::from(make_repeated(3000));
    b.iter(|| {
        protobuf::parse_from_carllerche_bytes::<messages::TestMessageWithBytes>(&bs).expect("parse")
    })
}

#[bench]
fn parse_repeated_huge_regular(b: &mut test::Bencher) {
    let bs = make_repeated(30000);
    b.iter(|| protobuf::parse_from_bytes::<messages::TestMessage>(&bs).expect("parse"))
}

#[bench]
fn parse_repeated_huge_bytes(b: &mut test::Bencher) {
    let bs = Bytes::from(make_repeated(30000));
    b.iter(|| {
        protobuf::parse_from_carllerche_bytes::<messages::TestMessageWithBytes>(&bs).expect("parse")
    })
}
<|endoftext|>


<commit_before>extern crate clap;
extern crate regex;

include!("../clap-test.rs");

use clap::{App, AppSettings, SubCommand, ErrorKind, Arg};

static HELP: &'static str = "clap-test v1.4.8
Kevin K. <kbknapp@gmail.com>
tests clap library

USAGE:
    clap-test [FLAGS] [OPTIONS] [ARGS] [SUBCOMMAND]

FLAGS:
    -f, --flag       tests flags
    -F               tests flags with exclusions
    -h, --help       Prints help information
    -V, --version    Prints version information

OPTIONS:
    -O, --Option <option3>           specific vals [values: fast, slow]
        --long-option-2 <option2>    tests long options with exclusions
        --maxvals3 <maxvals>...      Tests 3 max vals
        --minvals2 <minvals>...      Tests 2 min vals
        --multvals <one> <two>       Tests mutliple values, not mult occs
        --multvalsmo <one> <two>     Tests mutliple values, and mult occs
    -o, --option <opt>...            tests options

ARGS:
    <positional>        tests positionals
    <positional2>       tests positionals with exclusions
    <positional3>...    tests specific values [values: vi, emacs]

SUBCOMMANDS:
    help      Prints this message or the help of the given subcommand(s)
    subcmd    tests subcommands";

static AFTER_HELP: &'static str = "some text that comes before the help

clap-test v1.4.8
tests clap library

USAGE:
    clap-test

FLAGS:
    -h, --help       Prints help information
    -V, --version    Prints version information

some text that comes after the help";

static SC_HELP: &'static str = "subcmd 0.1
Kevin K. <kbknapp@gmail.com>
tests subcommands

USAGE:
    subcmd [FLAGS] [OPTIONS] [--] [scpositional]

FLAGS:
    -f, --flag    tests flags

OPTIONS:
    -o, --option <scoption>...    tests options

ARGS:
    <scpositional>    tests positionals";

static MULTI_SC_HELP: &'static str = "ctest-subcmd-multi 0.1
Kevin K. <kbknapp@gmail.com>
tests subcommands

USAGE:
    ctest subcmd multi [FLAGS] [OPTIONS]

FLAGS:
    -f, --flag       tests flags
    -h, --help       Prints help information
    -V, --version    Prints version information

OPTIONS:
    -o, --option <scoption>...    tests options";

static ISSUE_626_CUTOFF: &'static str = "ctest 0.1

USAGE:
    ctest [OPTIONS]

FLAGS:
    -h, --help       Prints help information
    -V, --version    Prints version information

OPTIONS:
    -c, --cafe <FILE>    A coffeehouse, coffee shop, or café is an
                         establishment which primarily serves hot
                         coffee, related coffee beverages (e.g., café
                         latte, cappuccino, espresso), tea, and other
                         hot beverages. Some coffeehouses also serve
                         cold beverages such as iced coffee and iced
                         tea. Many cafés also serve some type of
                         food, such as light snacks, muffins, or
                         pastries.";

static ISSUE_626_PANIC: &'static str = "ctest 0.1

USAGE:
    ctest [OPTIONS]

FLAGS:
    -h, --help       Prints help information
    -V, --version    Prints version information

OPTIONS:
    -c, --cafe <FILE>
            La culture du café est très développée
            dans de nombreux pays à climat chaud
            d\'Amérique, d\'Afrique et d\'Asie, dans
            des plantations qui sont cultivées pour
            les marchés d\'exportation. Le café est
            souvent une contribution majeure aux
            exportations des régions productrices.";

static HIDE_POS_VALS: &'static str = "ctest 0.1

USAGE:
    ctest [OPTIONS]

FLAGS:
    -h, --help       Prints help information
    -V, --version    Prints version information

OPTIONS:
    -c, --cafe <FILE>    A coffeehouse, coffee shop, or café.
    -p, --pos <VAL>      Some vals [values: fast, slow]";

static OLD_NEWLINE_CHARS: &'static str = "ctest 0.1

USAGE:
    ctest [FLAGS]

FLAGS:
    -h, --help       Prints help information
    -m               Some help with some wrapping
                     (Defaults to something)
    -V, --version    Prints version information";

static ISSUE_688: &'static str = "ctest 0.1

USAGE:
    ctest [OPTIONS]

FLAGS:
    -h, --help       Prints help information
    -V, --version    Prints version information

OPTIONS:
        --filter <filter>    Sets the filter, or sampling method, to use for interpolation when resizing the particle
                             images. The default is Linear (Bilinear). [values: Nearest, Linear, Cubic, Gaussian,
                             Lanczos3]";

#[test]
fn help_short() {
    let m = App::new("test")
        .author("Kevin K.")
        .about("tests stuff")
        .version("1.3")
        .get_matches_from_safe(vec!["myprog", "-h"]);

    assert!(m.is_err());
    assert_eq!(m.unwrap_err().kind, ErrorKind::HelpDisplayed);
}

#[test]
fn help_long() {
    let m = App::new("test")
        .author("Kevin K.")
        .about("tests stuff")
        .version("1.3")
        .get_matches_from_safe(vec!["myprog", "--help"]);

    assert!(m.is_err());
    assert_eq!(m.unwrap_err().kind, ErrorKind::HelpDisplayed);
}

#[test]
fn help_no_subcommand() {
    let m = App::new("test")
        .author("Kevin K.")
        .about("tests stuff")
        .version("1.3")
        .get_matches_from_safe(vec!["myprog", "help"]);

    assert!(m.is_err());
    assert_eq!(m.unwrap_err().kind, ErrorKind::UnknownArgument);
}

#[test]
fn help_subcommand() {
    let m = App::new("test")
        .author("Kevin K.")
        .about("tests stuff")
        .version("1.3")
        .subcommand(SubCommand::with_name("test")
            .about("tests things")
            .arg_from_usage("-v --verbose 'with verbosity'"))
        .get_matches_from_safe(vec!["myprog", "help"]);

    assert!(m.is_err());
    assert_eq!(m.unwrap_err().kind, ErrorKind::HelpDisplayed);
}

#[test]
fn subcommand_short_help() {
    let m = test::complex_app()
        .get_matches_from_safe(vec!["clap-test", "subcmd", "-h"]);

    assert!(m.is_err());
    assert_eq!(m.unwrap_err().kind, ErrorKind::HelpDisplayed);
}

#[test]
fn subcommand_long_help() {
    let m = test::complex_app()
        .get_matches_from_safe(vec!["clap-test", "subcmd", "--help"]);

    assert!(m.is_err());
    assert_eq!(m.unwrap_err().kind, ErrorKind::HelpDisplayed);
}

#[test]
fn subcommand_help_rev() {
    let m = test::complex_app()
        .get_matches_from_safe(vec!["clap-test", "help", "subcmd"]);

    assert!(m.is_err());
    assert_eq!(m.unwrap_err().kind, ErrorKind::HelpDisplayed);
}

#[test]
fn complex_help_output() {
    test::check_help(test::complex_app(), HELP);
}

#[test]
fn after_and_before_help_output() {
    let app = App::new("clap-test")
        .version("v1.4.8")
        .about("tests clap library")
        .before_help("some text that comes before the help")
        .after_help("some text that comes after the help");
    test::check_help(app, AFTER_HELP);
}

#[test]
fn multi_level_sc_help() {
    let app = App::new("ctest")
        .subcommand(SubCommand::with_name("subcmd")
            .subcommand(SubCommand::with_name("multi")
                .about("tests subcommands")
                .author("Kevin K. <kbknapp@gmail.com>")
                .version("0.1")
                .args_from_usage("
                    -f, --flag                    'tests flags'
                    -o, --option [scoption]...    'tests options'
                ")));
    test::check_err_output(app, "ctest help subcmd multi", MULTI_SC_HELP, false);
}

#[test]
fn no_wrap_help() {
    let app = App::new("ctest")
        .set_term_width(0)
        .help(MULTI_SC_HELP);
    test::check_err_output(app, "ctest --help", MULTI_SC_HELP, false);
}

#[test]
fn complex_subcommand_help_output() {
    let a = test::complex_app();
    test::check_subcommand_help(a, "subcmd", SC_HELP);
}

#[test]
fn issue_626_unicode_cutoff() {
    let app = App::new("ctest")
        .version("0.1")
        .set_term_width(70)
        .arg(Arg::with_name("cafe")
           .short("c")
           .long("cafe")
           .value_name("FILE")
           .help("A coffeehouse, coffee shop, or café is an establishment \
           which primarily serves hot coffee, related coffee beverages \
           (e.g., café latte, cappuccino, espresso), tea, and other hot \
           beverages. Some coffeehouses also serve cold beverages such as \
           iced coffee and iced tea. Many cafés also serve some type of \
           food, such as light snacks, muffins, or pastries.")
           .takes_value(true));
    test::check_err_output(app, "ctest --help", ISSUE_626_CUTOFF, false);
}

#[test]
fn hide_possible_vals() {
    let app = App::new("ctest")
        .version("0.1")
        .arg(Arg::with_name("pos")
           .short("p")
           .long("pos")
           .value_name("VAL")
           .possible_values(&["fast", "slow"])
           .help("Some vals")
           .takes_value(true))
        .arg(Arg::with_name("cafe")
           .short("c")
           .long("cafe")
           .value_name("FILE")
           .hide_possible_values(true)
           .possible_values(&["fast", "slow"])
           .help("A coffeehouse, coffee shop, or café.")
           .takes_value(true));
    test::check_err_output(app, "ctest --help", HIDE_POS_VALS, false);
}

#[test]
fn issue_626_panic() {
    let app = App::new("ctest")
        .version("0.1")
        .set_term_width(52)
        .arg(Arg::with_name("cafe")
           .short("c")
           .long("cafe")
           .value_name("FILE")
           .help("La culture du café est très développée dans de nombreux pays à climat chaud d'Amérique, \
           d'Afrique et d'Asie, dans des plantations qui sont cultivées pour les marchés d'exportation. \
           Le café est souvent une contribution majeure aux exportations des régions productrices.")
           .takes_value(true));
    test::check_err_output(app, "ctest --help", ISSUE_626_PANIC, false);
}

#[test]
fn issue_626_variable_panic() {
    for i in 10..320 {
        let _ = App::new("ctest")
            .version("0.1")
            .set_term_width(i)
            .arg(Arg::with_name("cafe")
               .short("c")
               .long("cafe")
               .value_name("FILE")
               .help("La culture du café est très développée dans de nombreux pays à climat chaud d'Amérique, \
               d'Afrique et d'Asie, dans des plantations qui sont cultivées pour les marchés d'exportation. \
               Le café est souvent une contribution majeure aux exportations des régions productrices.")
               .takes_value(true))
            .get_matches_from_safe(vec!["ctest", "--help"]);
    }
}

#[test]
fn old_newline_chars() {
    let app = App::new("ctest")
        .version("0.1")
        .arg(Arg::with_name("mode")
            .short("m")
            .help("Some help with some wrapping{n}(Defaults to something)"));
    test::check_err_output(app, "ctest --help", OLD_NEWLINE_CHARS, false);
}

#[test]
fn issue_688_hidden_pos_vals() {
	let filter_values = ["Nearest", "Linear", "Cubic", "Gaussian", "Lanczos3"];

	let app1 = App::new("ctest")
            .version("0.1")
			.set_term_width(120)
			.setting(AppSettings::HidePossibleValuesInHelp)
			.arg(Arg::with_name("filter")
				.help("Sets the filter, or sampling method, to use for interpolation when resizing the particle \
                images. The default is Linear (Bilinear). [values: Nearest, Linear, Cubic, Gaussian, Lanczos3]")
				.long("filter")
				.possible_values(&filter_values)
				.takes_value(true));
    test::check_err_output(app1, "ctest --help", ISSUE_688, false);

	let app2 = App::new("ctest")
            .version("0.1")
			.set_term_width(120)
			.arg(Arg::with_name("filter")
				.help("Sets the filter, or sampling method, to use for interpolation when resizing the particle \
                images. The default is Linear (Bilinear).")
				.long("filter")
				.possible_values(&filter_values)
				.takes_value(true));
    test::check_err_output(app2, "ctest --help", ISSUE_688, false);

	let app3 = App::new("ctest")
            .version("0.1")
			.set_term_width(120)
			.arg(Arg::with_name("filter")
				.help("Sets the filter, or sampling method, to use for interpolation when resizing the particle \
                images. The default is Linear (Bilinear). [values: Nearest, Linear, Cubic, Gaussian, Lanczos3]")
				.long("filter")
				.takes_value(true));
    test::check_err_output(app3, "ctest --help", ISSUE_688, false);
}<commit_msg>tests(Help Message): adds tests to guard aginst multiple values throwing off alignment<commit_after>extern crate clap;
extern crate regex;

include!("../clap-test.rs");

use clap::{App, AppSettings, SubCommand, ErrorKind, Arg};

static HELP: &'static str = "clap-test v1.4.8
Kevin K. <kbknapp@gmail.com>
tests clap library

USAGE:
    clap-test [FLAGS] [OPTIONS] [ARGS] [SUBCOMMAND]

FLAGS:
    -f, --flag       tests flags
    -F               tests flags with exclusions
    -h, --help       Prints help information
    -V, --version    Prints version information

OPTIONS:
    -O, --Option <option3>           specific vals [values: fast, slow]
        --long-option-2 <option2>    tests long options with exclusions
        --maxvals3 <maxvals>...      Tests 3 max vals
        --minvals2 <minvals>...      Tests 2 min vals
        --multvals <one> <two>       Tests mutliple values, not mult occs
        --multvalsmo <one> <two>     Tests mutliple values, and mult occs
    -o, --option <opt>...            tests options

ARGS:
    <positional>        tests positionals
    <positional2>       tests positionals with exclusions
    <positional3>...    tests specific values [values: vi, emacs]

SUBCOMMANDS:
    help      Prints this message or the help of the given subcommand(s)
    subcmd    tests subcommands";

static AFTER_HELP: &'static str = "some text that comes before the help

clap-test v1.4.8
tests clap library

USAGE:
    clap-test

FLAGS:
    -h, --help       Prints help information
    -V, --version    Prints version information

some text that comes after the help";

static SC_HELP: &'static str = "subcmd 0.1
Kevin K. <kbknapp@gmail.com>
tests subcommands

USAGE:
    subcmd [FLAGS] [OPTIONS] [--] [scpositional]

FLAGS:
    -f, --flag    tests flags

OPTIONS:
    -o, --option <scoption>...    tests options

ARGS:
    <scpositional>    tests positionals";

static MULTI_SC_HELP: &'static str = "ctest-subcmd-multi 0.1
Kevin K. <kbknapp@gmail.com>
tests subcommands

USAGE:
    ctest subcmd multi [FLAGS] [OPTIONS]

FLAGS:
    -f, --flag       tests flags
    -h, --help       Prints help information
    -V, --version    Prints version information

OPTIONS:
    -o, --option <scoption>...    tests options";

static ISSUE_626_CUTOFF: &'static str = "ctest 0.1

USAGE:
    ctest [OPTIONS]

FLAGS:
    -h, --help       Prints help information
    -V, --version    Prints version information

OPTIONS:
    -c, --cafe <FILE>    A coffeehouse, coffee shop, or café is an
                         establishment which primarily serves hot
                         coffee, related coffee beverages (e.g., café
                         latte, cappuccino, espresso), tea, and other
                         hot beverages. Some coffeehouses also serve
                         cold beverages such as iced coffee and iced
                         tea. Many cafés also serve some type of
                         food, such as light snacks, muffins, or
                         pastries.";

static ISSUE_626_PANIC: &'static str = "ctest 0.1

USAGE:
    ctest [OPTIONS]

FLAGS:
    -h, --help       Prints help information
    -V, --version    Prints version information

OPTIONS:
    -c, --cafe <FILE>
            La culture du café est très développée
            dans de nombreux pays à climat chaud
            d\'Amérique, d\'Afrique et d\'Asie, dans
            des plantations qui sont cultivées pour
            les marchés d\'exportation. Le café est
            souvent une contribution majeure aux
            exportations des régions productrices.";

static HIDE_POS_VALS: &'static str = "ctest 0.1

USAGE:
    ctest [OPTIONS]

FLAGS:
    -h, --help       Prints help information
    -V, --version    Prints version information

OPTIONS:
    -c, --cafe <FILE>    A coffeehouse, coffee shop, or café.
    -p, --pos <VAL>      Some vals [values: fast, slow]";

static OLD_NEWLINE_CHARS: &'static str = "ctest 0.1

USAGE:
    ctest [FLAGS]

FLAGS:
    -h, --help       Prints help information
    -m               Some help with some wrapping
                     (Defaults to something)
    -V, --version    Prints version information";

static ISSUE_688: &'static str = "ctest 0.1

USAGE:
    ctest [OPTIONS]

FLAGS:
    -h, --help       Prints help information
    -V, --version    Prints version information

OPTIONS:
        --filter <filter>    Sets the filter, or sampling method, to use for interpolation when resizing the particle
                             images. The default is Linear (Bilinear). [values: Nearest, Linear, Cubic, Gaussian,
                             Lanczos3]";

static ISSUE_702: &'static str = "myapp 1.0
foo
bar

USAGE:
    myapp [OPTIONS] [--] [ARGS]

FLAGS:
    -h, --help       Prints help information
    -V, --version    Prints version information

OPTIONS:
    -l, --label <label>...    a label
    -o, --other <other>       some other option
    -s, --some <some>         some option

ARGS:
    <arg1>       some option
    <arg2>...    some option";

#[test]
fn help_short() {
    let m = App::new("test")
        .author("Kevin K.")
        .about("tests stuff")
        .version("1.3")
        .get_matches_from_safe(vec!["myprog", "-h"]);

    assert!(m.is_err());
    assert_eq!(m.unwrap_err().kind, ErrorKind::HelpDisplayed);
}

#[test]
fn help_long() {
    let m = App::new("test")
        .author("Kevin K.")
        .about("tests stuff")
        .version("1.3")
        .get_matches_from_safe(vec!["myprog", "--help"]);

    assert!(m.is_err());
    assert_eq!(m.unwrap_err().kind, ErrorKind::HelpDisplayed);
}

#[test]
fn help_no_subcommand() {
    let m = App::new("test")
        .author("Kevin K.")
        .about("tests stuff")
        .version("1.3")
        .get_matches_from_safe(vec!["myprog", "help"]);

    assert!(m.is_err());
    assert_eq!(m.unwrap_err().kind, ErrorKind::UnknownArgument);
}

#[test]
fn help_subcommand() {
    let m = App::new("test")
        .author("Kevin K.")
        .about("tests stuff")
        .version("1.3")
        .subcommand(SubCommand::with_name("test")
            .about("tests things")
            .arg_from_usage("-v --verbose 'with verbosity'"))
        .get_matches_from_safe(vec!["myprog", "help"]);

    assert!(m.is_err());
    assert_eq!(m.unwrap_err().kind, ErrorKind::HelpDisplayed);
}

#[test]
fn subcommand_short_help() {
    let m = test::complex_app()
        .get_matches_from_safe(vec!["clap-test", "subcmd", "-h"]);

    assert!(m.is_err());
    assert_eq!(m.unwrap_err().kind, ErrorKind::HelpDisplayed);
}

#[test]
fn subcommand_long_help() {
    let m = test::complex_app()
        .get_matches_from_safe(vec!["clap-test", "subcmd", "--help"]);

    assert!(m.is_err());
    assert_eq!(m.unwrap_err().kind, ErrorKind::HelpDisplayed);
}

#[test]
fn subcommand_help_rev() {
    let m = test::complex_app()
        .get_matches_from_safe(vec!["clap-test", "help", "subcmd"]);

    assert!(m.is_err());
    assert_eq!(m.unwrap_err().kind, ErrorKind::HelpDisplayed);
}

#[test]
fn complex_help_output() {
    test::check_help(test::complex_app(), HELP);
}

#[test]
fn after_and_before_help_output() {
    let app = App::new("clap-test")
        .version("v1.4.8")
        .about("tests clap library")
        .before_help("some text that comes before the help")
        .after_help("some text that comes after the help");
    test::check_help(app, AFTER_HELP);
}

#[test]
fn multi_level_sc_help() {
    let app = App::new("ctest")
        .subcommand(SubCommand::with_name("subcmd")
            .subcommand(SubCommand::with_name("multi")
                .about("tests subcommands")
                .author("Kevin K. <kbknapp@gmail.com>")
                .version("0.1")
                .args_from_usage("
                    -f, --flag                    'tests flags'
                    -o, --option [scoption]...    'tests options'
                ")));
    test::check_err_output(app, "ctest help subcmd multi", MULTI_SC_HELP, false);
}

#[test]
fn no_wrap_help() {
    let app = App::new("ctest")
        .set_term_width(0)
        .help(MULTI_SC_HELP);
    test::check_err_output(app, "ctest --help", MULTI_SC_HELP, false);
}

#[test]
fn complex_subcommand_help_output() {
    let a = test::complex_app();
    test::check_subcommand_help(a, "subcmd", SC_HELP);
}

#[test]
fn issue_626_unicode_cutoff() {
    let app = App::new("ctest")
        .version("0.1")
        .set_term_width(70)
        .arg(Arg::with_name("cafe")
           .short("c")
           .long("cafe")
           .value_name("FILE")
           .help("A coffeehouse, coffee shop, or café is an establishment \
           which primarily serves hot coffee, related coffee beverages \
           (e.g., café latte, cappuccino, espresso), tea, and other hot \
           beverages. Some coffeehouses also serve cold beverages such as \
           iced coffee and iced tea. Many cafés also serve some type of \
           food, such as light snacks, muffins, or pastries.")
           .takes_value(true));
    test::check_err_output(app, "ctest --help", ISSUE_626_CUTOFF, false);
}

#[test]
fn hide_possible_vals() {
    let app = App::new("ctest")
        .version("0.1")
        .arg(Arg::with_name("pos")
           .short("p")
           .long("pos")
           .value_name("VAL")
           .possible_values(&["fast", "slow"])
           .help("Some vals")
           .takes_value(true))
        .arg(Arg::with_name("cafe")
           .short("c")
           .long("cafe")
           .value_name("FILE")
           .hide_possible_values(true)
           .possible_values(&["fast", "slow"])
           .help("A coffeehouse, coffee shop, or café.")
           .takes_value(true));
    test::check_err_output(app, "ctest --help", HIDE_POS_VALS, false);
}

#[test]
fn issue_626_panic() {
    let app = App::new("ctest")
        .version("0.1")
        .set_term_width(52)
        .arg(Arg::with_name("cafe")
           .short("c")
           .long("cafe")
           .value_name("FILE")
           .help("La culture du café est très développée dans de nombreux pays à climat chaud d'Amérique, \
           d'Afrique et d'Asie, dans des plantations qui sont cultivées pour les marchés d'exportation. \
           Le café est souvent une contribution majeure aux exportations des régions productrices.")
           .takes_value(true));
    test::check_err_output(app, "ctest --help", ISSUE_626_PANIC, false);
}

#[test]
fn issue_626_variable_panic() {
    for i in 10..320 {
        let _ = App::new("ctest")
            .version("0.1")
            .set_term_width(i)
            .arg(Arg::with_name("cafe")
               .short("c")
               .long("cafe")
               .value_name("FILE")
               .help("La culture du café est très développée dans de nombreux pays à climat chaud d'Amérique, \
               d'Afrique et d'Asie, dans des plantations qui sont cultivées pour les marchés d'exportation. \
               Le café est souvent une contribution majeure aux exportations des régions productrices.")
               .takes_value(true))
            .get_matches_from_safe(vec!["ctest", "--help"]);
    }
}

#[test]
fn old_newline_chars() {
    let app = App::new("ctest")
        .version("0.1")
        .arg(Arg::with_name("mode")
            .short("m")
            .help("Some help with some wrapping{n}(Defaults to something)"));
    test::check_err_output(app, "ctest --help", OLD_NEWLINE_CHARS, false);
}

#[test]
fn issue_688_hidden_pos_vals() {
	let filter_values = ["Nearest", "Linear", "Cubic", "Gaussian", "Lanczos3"];

	let app1 = App::new("ctest")
            .version("0.1")
			.set_term_width(120)
			.setting(AppSettings::HidePossibleValuesInHelp)
			.arg(Arg::with_name("filter")
				.help("Sets the filter, or sampling method, to use for interpolation when resizing the particle \
                images. The default is Linear (Bilinear). [values: Nearest, Linear, Cubic, Gaussian, Lanczos3]")
				.long("filter")
				.possible_values(&filter_values)
				.takes_value(true));
    test::check_err_output(app1, "ctest --help", ISSUE_688, false);

	let app2 = App::new("ctest")
            .version("0.1")
			.set_term_width(120)
			.arg(Arg::with_name("filter")
				.help("Sets the filter, or sampling method, to use for interpolation when resizing the particle \
                images. The default is Linear (Bilinear).")
				.long("filter")
				.possible_values(&filter_values)
				.takes_value(true));
    test::check_err_output(app2, "ctest --help", ISSUE_688, false);

	let app3 = App::new("ctest")
            .version("0.1")
			.set_term_width(120)
			.arg(Arg::with_name("filter")
				.help("Sets the filter, or sampling method, to use for interpolation when resizing the particle \
                images. The default is Linear (Bilinear). [values: Nearest, Linear, Cubic, Gaussian, Lanczos3]")
				.long("filter")
				.takes_value(true));
    test::check_err_output(app3, "ctest --help", ISSUE_688, false);
}

#[test]
fn issue_702_multiple_values() {
    let app = App::new("myapp")
        .version("1.0")
        .author("foo")
        .about("bar")
        .arg(Arg::with_name("arg1")
             .help("some option"))
        .arg(Arg::with_name("arg2")
             .multiple(true)
             .help("some option"))
        .arg(Arg::with_name("some")
             .help("some option")
             .short("s")
             .long("some")
             .takes_value(true))
        .arg(Arg::with_name("other")
             .help("some other option")
             .short("o")
             .long("other")
             .takes_value(true))
        .arg(Arg::with_name("label")
             .help("a label")
             .short("l")
             .long("label")
             .multiple(true)
             .takes_value(true));
    test::check_err_output(app, "myapp --help", ISSUE_702, false);
}<|endoftext|>


<commit_before>// Copyright 2017 Quentin Monnet <quentin.monnet@6wind.com>
//
// Licensed under the Apache License, Version 2.0 <http://www.apache.org/licenses/LICENSE-2.0> or
// the MIT license <http://opensource.org/licenses/MIT>, at your option. This file may not be
// copied, modified, or distributed except according to those terms.

#[macro_use]
extern crate json;

extern crate rbpf;
use rbpf::disassembler;

// Turn a program into a JSON string.
//
// Relies on `json` crate.
//
// You may copy this function and adapt it according to your needs. For instance, you may want to:
//
// * Remove the "desc" (description) attributes from the output.
// * Print integers as integers, and not as strings containing their hexadecimal representation
//   (just replace the relevant `format!()` calls by the commented values.
fn to_json(prog: &std::vec::Vec<u8>) -> String {

    // This call returns a high-level representation of the instructions, with the two parts of
    // `LD_DW_IMM` instructions merged, and name and descriptions of the instructions.
    // If you prefer to use a lower-level representation, use `ebpf::to_insn_vec()` function
    // instead.
    let insns = disassembler::to_insn_vec(&prog);
    let mut json_insns = vec![];
    for insn in insns {
        json_insns.push(object!(
                "opc"  => format!("{:#x}", insn.opc), // => insn.opc,
                "dst"  => format!("{:#x}", insn.dst), // => insn.dst,
                "src"  => format!("{:#x}", insn.src), // => insn.src,
                "off"  => format!("{:#x}", insn.off), // => insn.off,
                // Warning: for imm we use a i64 instead of a i32 (to have correct values for
                // `lddw` operation. If we print a number in the JSON this is not a problem, the
                // internal i64 has the same value with extended sign on 32 most significant bytes.
                // If we print the hexadecimal value as a string however, we want to cast as a i32
                // to prevent all other instructions to print spurious `ffffffff` prefix if the
                // number is negative. When values takes more than 32 bits with `lddw`, the cast
                // has no effect and the complete value is printed anyway.
                "imm"  => format!("{:#x}", insn.imm as i32), // => insn.imm,
                "desc" => format!("{}",    insn.desc)
            )
        );
    }
    json::stringify_pretty(object!(
        "size"  => json_insns.len(),
        "insns" => json_insns
        ), 4)
}

// Print a JSON string representing the program to standard output.
fn main() {
    let prog = vec![
        0xb7, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
        0x79, 0x12, 0x50, 0x00, 0x00, 0x00, 0x00, 0x00,
        0x79, 0x11, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00,
        0xbf, 0x13, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
        0x07, 0x03, 0x00, 0x00, 0x36, 0x00, 0x00, 0x00,
        0x2d, 0x23, 0x12, 0x00, 0x00, 0x00, 0x00, 0x00,
        0x69, 0x12, 0x0c, 0x00, 0x00, 0x00, 0x00, 0x00,
        0x55, 0x02, 0x10, 0x00, 0x08, 0x00, 0x00, 0x00,
        0x71, 0x12, 0x17, 0x00, 0x00, 0x00, 0x00, 0x00,
        0x55, 0x02, 0x0e, 0x00, 0x06, 0x00, 0x00, 0x00,
        0x18, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff,
        0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
        0x79, 0x11, 0x22, 0x00, 0x00, 0x00, 0x00, 0x00,
        0xbf, 0x12, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
        0x57, 0x02, 0x00, 0x00, 0xff, 0xff, 0x00, 0x00,
        0x15, 0x02, 0x08, 0x00, 0x99, 0x99, 0x00, 0x00,
        0x18, 0x02, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff,
        0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
        0x5f, 0x21, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
        0xb7, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff,
        0x18, 0x02, 0x00, 0x00, 0x00, 0x00, 0x99, 0x99,
        0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
        0x1d, 0x21, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00,
        0xb7, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
        0x95, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
    ];

    println!("{}", to_json(&prog));
}
<commit_msg>examples/to_json.rs: load program from ELF file instead of hardcoding it<commit_after>// Copyright 2017 Quentin Monnet <quentin.monnet@6wind.com>
//
// Licensed under the Apache License, Version 2.0 <http://www.apache.org/licenses/LICENSE-2.0> or
// the MIT license <http://opensource.org/licenses/MIT>, at your option. This file may not be
// copied, modified, or distributed except according to those terms.

#[macro_use]
extern crate json;

extern crate byteorder;
extern crate elf;
use std::path::PathBuf;

extern crate rbpf;
use rbpf::disassembler;

// Turn a program into a JSON string.
//
// Relies on `json` crate.
//
// You may copy this function and adapt it according to your needs. For instance, you may want to:
//
// * Remove the "desc" (description) attributes from the output.
// * Print integers as integers, and not as strings containing their hexadecimal representation
//   (just replace the relevant `format!()` calls by the commented values.
fn to_json(prog: &std::vec::Vec<u8>) -> String {

    // This call returns a high-level representation of the instructions, with the two parts of
    // `LD_DW_IMM` instructions merged, and name and descriptions of the instructions.
    // If you prefer to use a lower-level representation, use `ebpf::to_insn_vec()` function
    // instead.
    let insns = disassembler::to_insn_vec(&prog);
    let mut json_insns = vec![];
    for insn in insns {
        json_insns.push(object!(
                "opc"  => format!("{:#x}", insn.opc), // => insn.opc,
                "dst"  => format!("{:#x}", insn.dst), // => insn.dst,
                "src"  => format!("{:#x}", insn.src), // => insn.src,
                "off"  => format!("{:#x}", insn.off), // => insn.off,
                // Warning: for imm we use a i64 instead of a i32 (to have correct values for
                // `lddw` operation. If we print a number in the JSON this is not a problem, the
                // internal i64 has the same value with extended sign on 32 most significant bytes.
                // If we print the hexadecimal value as a string however, we want to cast as a i32
                // to prevent all other instructions to print spurious `ffffffff` prefix if the
                // number is negative. When values takes more than 32 bits with `lddw`, the cast
                // has no effect and the complete value is printed anyway.
                "imm"  => format!("{:#x}", insn.imm as i32), // => insn.imm,
                "desc" => format!("{}",    insn.desc)
            )
        );
    }
    json::stringify_pretty(object!(
        "size"  => json_insns.len(),
        "insns" => json_insns
        ), 4)
}

// Load a program from an object file, and prints it to standard output as a JSON string.
fn main() {

    // Let's reuse this file from `load_elf` example.
    let filename = "examples/load_elf__block_a_port.o";

    let path = PathBuf::from(filename);
    let file = match elf::File::open_path(&path) {
        Ok(f) => f,
        Err(e) => panic!("Error: {:?}", e),
    };

    let text_scn = match file.get_section(".classifier") {
        Some(s) => s,
        None => panic!("Failed to look up .classifier section"),
    };

    let ref prog = &text_scn.data;

    println!("{}", to_json(&prog));
}
<|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/. */

#![feature(as_unsafe_cell)]
#![feature(borrow_state)]
#![feature(box_syntax)]
#![feature(const_fn)]
#![feature(core_intrinsics)]
#![feature(custom_attribute)]
#![feature(custom_derive)]
#![feature(fnbox)]
#![feature(iter_arith)]
#![feature(mpsc_select)]
#![feature(nonzero)]
#![feature(on_unimplemented)]
#![feature(optin_builtin_traits)]
#![feature(plugin)]
#![feature(slice_patterns)]
#![feature(stmt_expr_attributes)]
#![feature(question_mark)]
#![feature(try_from)]

#![deny(unsafe_code)]
#![allow(non_snake_case)]

#![doc = "The script crate contains all matters DOM."]

#![plugin(heapsize_plugin)]
#![plugin(phf_macros)]
#![plugin(plugins)]

extern crate angle;
extern crate app_units;
#[allow(unused_extern_crates)]
#[macro_use]
extern crate bitflags;
extern crate canvas_traits;
extern crate caseless;
extern crate cookie as cookie_rs;
extern crate core;
#[macro_use]
extern crate cssparser;
extern crate devtools_traits;
extern crate encoding;
extern crate euclid;
extern crate fnv;
extern crate gfx_traits;
extern crate heapsize;
extern crate html5ever;
extern crate hyper;
extern crate image;
extern crate ipc_channel;
#[macro_use]
extern crate js;
extern crate libc;
#[macro_use]
extern crate log;
#[macro_use]
extern crate mime;
extern crate mime_guess;
extern crate msg;
extern crate net_traits;
extern crate num_traits;
extern crate offscreen_gl_context;
extern crate open;
extern crate phf;
#[macro_use]
extern crate profile_traits;
extern crate rand;
extern crate range;
extern crate ref_filter_map;
extern crate ref_slice;
extern crate regex;
extern crate rustc_serialize;
extern crate script_layout_interface;
extern crate script_traits;
extern crate selectors;
extern crate serde;
extern crate smallvec;
#[macro_use(atom, ns)] extern crate string_cache;
#[macro_use]
extern crate style;
extern crate time;
#[cfg(any(target_os = "macos", target_os = "linux", target_os = "windows"))]
extern crate tinyfiledialogs;
extern crate url;
#[macro_use]
extern crate util;
extern crate uuid;
extern crate webrender_traits;
extern crate websocket;
extern crate xml5ever;

pub mod bluetooth_blacklist;
pub mod clipboard_provider;
mod devtools;
pub mod document_loader;
#[macro_use]
pub mod dom;
pub mod layout_wrapper;
mod mem;
mod network_listener;
pub mod origin;
pub mod parse;
pub mod script_runtime;
#[allow(unsafe_code)]
pub mod script_thread;
mod serviceworker_manager;
mod task_source;
pub mod textinput;
mod timers;
mod unpremultiplytable;
mod webdriver_handlers;

use dom::bindings::codegen::RegisterBindings;
use js::jsapi::{Handle, JSContext, JSObject, SetDOMProxyInformation};
use script_traits::SWManagerSenders;
use serviceworker_manager::ServiceWorkerManager;
use std::ptr;
use util::opts;

#[cfg(target_os = "linux")]
#[allow(unsafe_code)]
fn perform_platform_specific_initialization() {
    use std::mem;
    // 4096 is default max on many linux systems
    const MAX_FILE_LIMIT: libc::rlim_t = 4096;

    // Bump up our number of file descriptors to save us from impending doom caused by an onslaught
    // of iframes.
    unsafe {
        let mut rlim: libc::rlimit = mem::uninitialized();
        match libc::getrlimit(libc::RLIMIT_NOFILE, &mut rlim) {
            0 => {
                if rlim.rlim_cur >= MAX_FILE_LIMIT {
                    // we have more than enough
                    return;
                }

                rlim.rlim_cur = match rlim.rlim_max {
                    libc::RLIM_INFINITY => MAX_FILE_LIMIT,
                    _ => {
                        if rlim.rlim_max < MAX_FILE_LIMIT {
                            rlim.rlim_max
                        } else {
                            MAX_FILE_LIMIT
                        }
                    }
                };
                match libc::setrlimit(libc::RLIMIT_NOFILE, &rlim) {
                    0 => (),
                    _ => warn!("Failed to set file count limit"),
                };
            },
            _ => warn!("Failed to get file count limit"),
        };
    }
}

#[cfg(not(target_os = "linux"))]
fn perform_platform_specific_initialization() {}

#[allow(unsafe_code)]
pub fn init(sw_senders: SWManagerSenders) {
    unsafe {
        SetDOMProxyInformation(ptr::null(), 0, Some(script_thread::shadow_check_callback));
    }

    // Spawn the service worker manager passing the constellation sender
    ServiceWorkerManager::spawn_manager(sw_senders);

    // Create the global vtables used by the (generated) DOM
    // bindings to implement JS proxies.
    RegisterBindings::RegisterProxyHandlers();

    perform_platform_specific_initialization();
}

/// FIXME(pcwalton): Currently WebRender cannot handle DOM-initiated scrolls. Remove this when it
/// can. See PR #11680 for details.
///
/// This function is only marked `unsafe` because the `[Func=foo]` WebIDL attribute requires it. It
/// shouldn't actually do anything unsafe.
#[allow(unsafe_code)]
pub unsafe fn script_can_initiate_scroll(_: *mut JSContext, _: Handle<*mut JSObject>) -> bool {
    !opts::get().use_webrender
}
<commit_msg>Remove the no longer necessary iter_arith feature gate.<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/. */

#![feature(as_unsafe_cell)]
#![feature(borrow_state)]
#![feature(box_syntax)]
#![feature(const_fn)]
#![feature(core_intrinsics)]
#![feature(custom_attribute)]
#![feature(custom_derive)]
#![feature(fnbox)]
#![feature(mpsc_select)]
#![feature(nonzero)]
#![feature(on_unimplemented)]
#![feature(optin_builtin_traits)]
#![feature(plugin)]
#![feature(slice_patterns)]
#![feature(stmt_expr_attributes)]
#![feature(question_mark)]
#![feature(try_from)]

#![deny(unsafe_code)]
#![allow(non_snake_case)]

#![doc = "The script crate contains all matters DOM."]

#![plugin(heapsize_plugin)]
#![plugin(phf_macros)]
#![plugin(plugins)]

extern crate angle;
extern crate app_units;
#[allow(unused_extern_crates)]
#[macro_use]
extern crate bitflags;
extern crate canvas_traits;
extern crate caseless;
extern crate cookie as cookie_rs;
extern crate core;
#[macro_use]
extern crate cssparser;
extern crate devtools_traits;
extern crate encoding;
extern crate euclid;
extern crate fnv;
extern crate gfx_traits;
extern crate heapsize;
extern crate html5ever;
extern crate hyper;
extern crate image;
extern crate ipc_channel;
#[macro_use]
extern crate js;
extern crate libc;
#[macro_use]
extern crate log;
#[macro_use]
extern crate mime;
extern crate mime_guess;
extern crate msg;
extern crate net_traits;
extern crate num_traits;
extern crate offscreen_gl_context;
extern crate open;
extern crate phf;
#[macro_use]
extern crate profile_traits;
extern crate rand;
extern crate range;
extern crate ref_filter_map;
extern crate ref_slice;
extern crate regex;
extern crate rustc_serialize;
extern crate script_layout_interface;
extern crate script_traits;
extern crate selectors;
extern crate serde;
extern crate smallvec;
#[macro_use(atom, ns)] extern crate string_cache;
#[macro_use]
extern crate style;
extern crate time;
#[cfg(any(target_os = "macos", target_os = "linux", target_os = "windows"))]
extern crate tinyfiledialogs;
extern crate url;
#[macro_use]
extern crate util;
extern crate uuid;
extern crate webrender_traits;
extern crate websocket;
extern crate xml5ever;

pub mod bluetooth_blacklist;
pub mod clipboard_provider;
mod devtools;
pub mod document_loader;
#[macro_use]
pub mod dom;
pub mod layout_wrapper;
mod mem;
mod network_listener;
pub mod origin;
pub mod parse;
pub mod script_runtime;
#[allow(unsafe_code)]
pub mod script_thread;
mod serviceworker_manager;
mod task_source;
pub mod textinput;
mod timers;
mod unpremultiplytable;
mod webdriver_handlers;

use dom::bindings::codegen::RegisterBindings;
use js::jsapi::{Handle, JSContext, JSObject, SetDOMProxyInformation};
use script_traits::SWManagerSenders;
use serviceworker_manager::ServiceWorkerManager;
use std::ptr;
use util::opts;

#[cfg(target_os = "linux")]
#[allow(unsafe_code)]
fn perform_platform_specific_initialization() {
    use std::mem;
    // 4096 is default max on many linux systems
    const MAX_FILE_LIMIT: libc::rlim_t = 4096;

    // Bump up our number of file descriptors to save us from impending doom caused by an onslaught
    // of iframes.
    unsafe {
        let mut rlim: libc::rlimit = mem::uninitialized();
        match libc::getrlimit(libc::RLIMIT_NOFILE, &mut rlim) {
            0 => {
                if rlim.rlim_cur >= MAX_FILE_LIMIT {
                    // we have more than enough
                    return;
                }

                rlim.rlim_cur = match rlim.rlim_max {
                    libc::RLIM_INFINITY => MAX_FILE_LIMIT,
                    _ => {
                        if rlim.rlim_max < MAX_FILE_LIMIT {
                            rlim.rlim_max
                        } else {
                            MAX_FILE_LIMIT
                        }
                    }
                };
                match libc::setrlimit(libc::RLIMIT_NOFILE, &rlim) {
                    0 => (),
                    _ => warn!("Failed to set file count limit"),
                };
            },
            _ => warn!("Failed to get file count limit"),
        };
    }
}

#[cfg(not(target_os = "linux"))]
fn perform_platform_specific_initialization() {}

#[allow(unsafe_code)]
pub fn init(sw_senders: SWManagerSenders) {
    unsafe {
        SetDOMProxyInformation(ptr::null(), 0, Some(script_thread::shadow_check_callback));
    }

    // Spawn the service worker manager passing the constellation sender
    ServiceWorkerManager::spawn_manager(sw_senders);

    // Create the global vtables used by the (generated) DOM
    // bindings to implement JS proxies.
    RegisterBindings::RegisterProxyHandlers();

    perform_platform_specific_initialization();
}

/// FIXME(pcwalton): Currently WebRender cannot handle DOM-initiated scrolls. Remove this when it
/// can. See PR #11680 for details.
///
/// This function is only marked `unsafe` because the `[Func=foo]` WebIDL attribute requires it. It
/// shouldn't actually do anything unsafe.
#[allow(unsafe_code)]
pub unsafe fn script_can_initiate_scroll(_: *mut JSContext, _: Handle<*mut JSObject>) -> bool {
    !opts::get().use_webrender
}
<|endoftext|>


<commit_before>/*!
Miscellaneous utilities grab-bag.

 */

#![crate_name="calx_util"]
#![allow(unstable)]

extern crate collections;
extern crate "rustc-serialize" as rustc_serialize;
extern crate time;
extern crate image;

pub use rgb::{Rgb, Rgba};
pub use geom::{Rect, V2, RectIter};
pub use img::{color_key};
pub use atlas::{AtlasBuilder, Atlas, AtlasItem};
pub use dijkstra::{DijkstraNode, Dijkstra};

mod atlas;
mod dijkstra;
mod geom;
mod img;
mod primitive;
mod rgb;

pub mod color;
pub mod text;
pub mod timing;
pub mod vorud;

pub trait Color {
    fn to_rgba(&self) -> [f32; 4];
}
<commit_msg>Numeric util functions<commit_after>/*!
Miscellaneous utilities grab-bag.

 */

#![crate_name="calx_util"]
#![allow(unstable)]

extern crate collections;
extern crate "rustc-serialize" as rustc_serialize;
extern crate time;
extern crate image;

pub use rgb::{Rgb, Rgba};
pub use geom::{Rect, V2, RectIter};
pub use img::{color_key};
pub use atlas::{AtlasBuilder, Atlas, AtlasItem};
pub use dijkstra::{DijkstraNode, Dijkstra};

mod atlas;
mod dijkstra;
mod geom;
mod img;
mod primitive;
mod rgb;

pub mod color;
pub mod text;
pub mod timing;
pub mod vorud;

pub trait Color {
    fn to_rgba(&self) -> [f32; 4];
}

/// Clamp a value to range.
pub fn clamp<C: PartialOrd+Copy>(mn: C, mx: C, x: C) -> C {
    if x < mn { mn }
    else if x > mx { mx }
    else { x }
}

/// Deterministic noise.
pub fn noise(n: i32) -> f32 {
    let n = (n << 13) ^ n;
    let m = (n * (n * n * 15731 + 789221) + 1376312589) & 0x7fffffff;
    1.0 - m as f32 / 1073741824.0
}
<|endoftext|>