<commit_before>// Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// https://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

use syn::ItemEnum;

use super::{
    api::{AnalysisPhase, Api, ApiName, FuncToConvert, StructDetails, TypedefKind},
    apivec::ApiVec,
    convert_error::{ConvertErrorWithContext, ErrorContext},
    ConvertError,
};
use crate::{
    conversion::convert_error::ErrorContextType,
    types::{Namespace, QualifiedName},
};

/// Run some code which may generate a ConvertError.
/// If it does, try to note the problem in our output APIs
/// such that users will see documentation of the error.
pub(crate) fn report_any_error<F, T>(
    ns: &Namespace,
    apis: &mut ApiVec<impl AnalysisPhase>,
    fun: F,
) -> Option<T>
where
    F: FnOnce() -> Result<T, ConvertErrorWithContext>,
{
    match fun() {
        Ok(result) => Some(result),
        Err(ConvertErrorWithContext(err, None)) => {
            eprintln!("Ignored item: {}", err);
            None
        }
        Err(ConvertErrorWithContext(err, Some(ctx))) => {
            eprintln!("Ignored item {}: {}", ctx, err);
            let id = match ctx.get_type() {
                ErrorContextType::Item(id) | ErrorContextType::SanitizedItem(id) => id,
                ErrorContextType::Method { self_ty, .. } => self_ty,
            };
            let api_name = ApiName::new_from_qualified_name(QualifiedName::new(ns, id.clone()));
            if let Some(item) = ignored_item(api_name, Some(ctx), err) {
                apis.push(item);
            }
            None
        }
    }
}

/// Run some code which generates an API. Add that API, or if
/// anything goes wrong, instead add a note of the problem in our
/// output API such that users will see documentation for the problem.
pub(crate) fn convert_apis<FF, SF, EF, TF, A, B: 'static>(
    in_apis: ApiVec<A>,
    out_apis: &mut ApiVec<B>,
    mut func_conversion: FF,
    mut struct_conversion: SF,
    mut enum_conversion: EF,
    mut typedef_conversion: TF,
) where
    A: AnalysisPhase,
    B: AnalysisPhase,
    FF: FnMut(
        ApiName,
        Box<FuncToConvert>,
        A::FunAnalysis,
    ) -> Result<Box<dyn Iterator<Item = Api<B>>>, ConvertErrorWithContext>,
    SF: FnMut(
        ApiName,
        Box<StructDetails>,
        A::StructAnalysis,
    ) -> Result<Box<dyn Iterator<Item = Api<B>>>, ConvertErrorWithContext>,
    EF: FnMut(
        ApiName,
        ItemEnum,
    ) -> Result<Box<dyn Iterator<Item = Api<B>>>, ConvertErrorWithContext>,
    TF: FnMut(
        ApiName,
        TypedefKind,
        Option<QualifiedName>,
        A::TypedefAnalysis,
    ) -> Result<Box<dyn Iterator<Item = Api<B>>>, ConvertErrorWithContext>,
{
    out_apis.extend(in_apis.into_iter().flat_map(|api| {
        let fullname = api.name_info().clone();
        let result: Result<Box<dyn Iterator<Item = Api<B>>>, ConvertErrorWithContext> = match api {
            // No changes to any of these...
            Api::ConcreteType {
                name,
                rs_definition,
                cpp_definition,
            } => Ok(Box::new(std::iter::once(Api::ConcreteType {
                name,
                rs_definition,
                cpp_definition,
            }))),
            Api::ForwardDeclaration { name } => {
                Ok(Box::new(std::iter::once(Api::ForwardDeclaration { name })))
            }
            Api::StringConstructor { name } => {
                Ok(Box::new(std::iter::once(Api::StringConstructor { name })))
            }
            Api::Const { name, const_item } => {
                Ok(Box::new(std::iter::once(Api::Const { name, const_item })))
            }
            Api::CType { name, typename } => {
                Ok(Box::new(std::iter::once(Api::CType { name, typename })))
            }
            Api::RustType { name, path } => {
                Ok(Box::new(std::iter::once(Api::RustType { name, path })))
            }
            Api::RustFn { name, sig, path } => {
                Ok(Box::new(std::iter::once(Api::RustFn { name, sig, path })))
            }
            Api::RustSubclassFn {
                name,
                subclass,
                details,
            } => Ok(Box::new(std::iter::once(Api::RustSubclassFn {
                name,
                subclass,
                details,
            }))),
            Api::Subclass { name, superclass } => Ok(Box::new(std::iter::once(Api::Subclass {
                name,
                superclass,
            }))),
            Api::IgnoredItem { name, err, ctx } => {
                Ok(Box::new(std::iter::once(Api::IgnoredItem {
                    name,
                    err,
                    ctx,
                })))
            }
            Api::SubclassTraitItem { name, details } => {
                Ok(Box::new(std::iter::once(Api::SubclassTraitItem {
                    name,
                    details,
                })))
            }
            // Apply a mapping to the following
            Api::Enum { name, item } => enum_conversion(name, item),
            Api::Typedef {
                name,
                item,
                old_tyname,
                analysis,
            } => typedef_conversion(name, item, old_tyname, analysis),
            Api::Function {
                name,
                fun,
                analysis,
            } => func_conversion(name, fun, analysis),
            Api::Struct {
                name,
                details,
                analysis,
            } => struct_conversion(name, details, analysis),
        };
        api_or_error(fullname, result)
    }))
}

fn api_or_error<T: AnalysisPhase + 'static>(
    name: ApiName,
    api_or_error: Result<Box<dyn Iterator<Item = Api<T>>>, ConvertErrorWithContext>,
) -> Box<dyn Iterator<Item = Api<T>>> {
    match api_or_error {
        Ok(opt) => opt,
        Err(ConvertErrorWithContext(err, ctx)) => {
            eprintln!("Ignored {}: {}", name.cpp_name(), err);
            Box::new(ignored_item(name, ctx, err).into_iter())
        }
    }
}

/// Run some code which generates an API for an item (as opposed to
/// a method). Add that API, or if
/// anything goes wrong, instead add a note of the problem in our
/// output API such that users will see documentation for the problem.
pub(crate) fn convert_item_apis<F, A, B: 'static>(
    in_apis: ApiVec<A>,
    out_apis: &mut ApiVec<B>,
    mut fun: F,
) where
    F: FnMut(Api<A>) -> Result<Box<dyn Iterator<Item = Api<B>>>, ConvertError>,
    A: AnalysisPhase,
    B: AnalysisPhase,
{
    out_apis.extend(in_apis.into_iter().flat_map(|api| {
        let fullname = api.name_info().clone();
        let tn = api.name().clone();
        let result = fun(api).map_err(|e| {
            ConvertErrorWithContext(e, Some(ErrorContext::new_for_item(tn.get_final_ident())))
        });
        api_or_error(fullname, result)
    }))
}

fn ignored_item<A: AnalysisPhase>(
    name: ApiName,
    ctx: Option<ErrorContext>,
    err: ConvertError,
) -> Option<Api<A>> {
    Some(Api::IgnoredItem { name, err, ctx })
}
<commit_msg>Inline.<commit_after>// Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// https://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

use syn::ItemEnum;

use super::{
    api::{AnalysisPhase, Api, ApiName, FuncToConvert, StructDetails, TypedefKind},
    apivec::ApiVec,
    convert_error::{ConvertErrorWithContext, ErrorContext},
    ConvertError,
};
use crate::{
    conversion::convert_error::ErrorContextType,
    types::{Namespace, QualifiedName},
};

/// Run some code which may generate a ConvertError.
/// If it does, try to note the problem in our output APIs
/// such that users will see documentation of the error.
pub(crate) fn report_any_error<F, T>(
    ns: &Namespace,
    apis: &mut ApiVec<impl AnalysisPhase>,
    fun: F,
) -> Option<T>
where
    F: FnOnce() -> Result<T, ConvertErrorWithContext>,
{
    match fun() {
        Ok(result) => Some(result),
        Err(ConvertErrorWithContext(err, None)) => {
            eprintln!("Ignored item: {}", err);
            None
        }
        Err(ConvertErrorWithContext(err, Some(ctx))) => {
            eprintln!("Ignored item {}: {}", ctx, err);
            let id = match ctx.get_type() {
                ErrorContextType::Item(id) | ErrorContextType::SanitizedItem(id) => id,
                ErrorContextType::Method { self_ty, .. } => self_ty,
            };
            let name = ApiName::new_from_qualified_name(QualifiedName::new(ns, id.clone()));
            apis.push(Api::IgnoredItem {
                name,
                err,
                ctx: Some(ctx),
            });
            None
        }
    }
}

/// Run some code which generates an API. Add that API, or if
/// anything goes wrong, instead add a note of the problem in our
/// output API such that users will see documentation for the problem.
pub(crate) fn convert_apis<FF, SF, EF, TF, A, B: 'static>(
    in_apis: ApiVec<A>,
    out_apis: &mut ApiVec<B>,
    mut func_conversion: FF,
    mut struct_conversion: SF,
    mut enum_conversion: EF,
    mut typedef_conversion: TF,
) where
    A: AnalysisPhase,
    B: AnalysisPhase,
    FF: FnMut(
        ApiName,
        Box<FuncToConvert>,
        A::FunAnalysis,
    ) -> Result<Box<dyn Iterator<Item = Api<B>>>, ConvertErrorWithContext>,
    SF: FnMut(
        ApiName,
        Box<StructDetails>,
        A::StructAnalysis,
    ) -> Result<Box<dyn Iterator<Item = Api<B>>>, ConvertErrorWithContext>,
    EF: FnMut(
        ApiName,
        ItemEnum,
    ) -> Result<Box<dyn Iterator<Item = Api<B>>>, ConvertErrorWithContext>,
    TF: FnMut(
        ApiName,
        TypedefKind,
        Option<QualifiedName>,
        A::TypedefAnalysis,
    ) -> Result<Box<dyn Iterator<Item = Api<B>>>, ConvertErrorWithContext>,
{
    out_apis.extend(in_apis.into_iter().flat_map(|api| {
        let fullname = api.name_info().clone();
        let result: Result<Box<dyn Iterator<Item = Api<B>>>, ConvertErrorWithContext> = match api {
            // No changes to any of these...
            Api::ConcreteType {
                name,
                rs_definition,
                cpp_definition,
            } => Ok(Box::new(std::iter::once(Api::ConcreteType {
                name,
                rs_definition,
                cpp_definition,
            }))),
            Api::ForwardDeclaration { name } => {
                Ok(Box::new(std::iter::once(Api::ForwardDeclaration { name })))
            }
            Api::StringConstructor { name } => {
                Ok(Box::new(std::iter::once(Api::StringConstructor { name })))
            }
            Api::Const { name, const_item } => {
                Ok(Box::new(std::iter::once(Api::Const { name, const_item })))
            }
            Api::CType { name, typename } => {
                Ok(Box::new(std::iter::once(Api::CType { name, typename })))
            }
            Api::RustType { name, path } => {
                Ok(Box::new(std::iter::once(Api::RustType { name, path })))
            }
            Api::RustFn { name, sig, path } => {
                Ok(Box::new(std::iter::once(Api::RustFn { name, sig, path })))
            }
            Api::RustSubclassFn {
                name,
                subclass,
                details,
            } => Ok(Box::new(std::iter::once(Api::RustSubclassFn {
                name,
                subclass,
                details,
            }))),
            Api::Subclass { name, superclass } => Ok(Box::new(std::iter::once(Api::Subclass {
                name,
                superclass,
            }))),
            Api::IgnoredItem { name, err, ctx } => {
                Ok(Box::new(std::iter::once(Api::IgnoredItem {
                    name,
                    err,
                    ctx,
                })))
            }
            Api::SubclassTraitItem { name, details } => {
                Ok(Box::new(std::iter::once(Api::SubclassTraitItem {
                    name,
                    details,
                })))
            }
            // Apply a mapping to the following
            Api::Enum { name, item } => enum_conversion(name, item),
            Api::Typedef {
                name,
                item,
                old_tyname,
                analysis,
            } => typedef_conversion(name, item, old_tyname, analysis),
            Api::Function {
                name,
                fun,
                analysis,
            } => func_conversion(name, fun, analysis),
            Api::Struct {
                name,
                details,
                analysis,
            } => struct_conversion(name, details, analysis),
        };
        api_or_error(fullname, result)
    }))
}

fn api_or_error<T: AnalysisPhase + 'static>(
    name: ApiName,
    api_or_error: Result<Box<dyn Iterator<Item = Api<T>>>, ConvertErrorWithContext>,
) -> Box<dyn Iterator<Item = Api<T>>> {
    match api_or_error {
        Ok(opt) => opt,
        Err(ConvertErrorWithContext(err, ctx)) => {
            eprintln!("Ignored {}: {}", name.cpp_name(), err);
            Box::new(std::iter::once(Api::IgnoredItem { name, err, ctx }))
        }
    }
}

/// Run some code which generates an API for an item (as opposed to
/// a method). Add that API, or if
/// anything goes wrong, instead add a note of the problem in our
/// output API such that users will see documentation for the problem.
pub(crate) fn convert_item_apis<F, A, B: 'static>(
    in_apis: ApiVec<A>,
    out_apis: &mut ApiVec<B>,
    mut fun: F,
) where
    F: FnMut(Api<A>) -> Result<Box<dyn Iterator<Item = Api<B>>>, ConvertError>,
    A: AnalysisPhase,
    B: AnalysisPhase,
{
    out_apis.extend(in_apis.into_iter().flat_map(|api| {
        let fullname = api.name_info().clone();
        let tn = api.name().clone();
        let result = fun(api).map_err(|e| {
            ConvertErrorWithContext(e, Some(ErrorContext::new_for_item(tn.get_final_ident())))
        });
        api_or_error(fullname, result)
    }))
}
<|endoftext|>


<commit_before>extern crate custom_set as set;

use set::*;

#[test]
fn sets_with_no_elements_are_empty() {
    let set: CustomSet<()> = CustomSet::new(vec![]);
    assert!(set.is_empty());
}

#[test]
#[ignore]
fn sets_with_elements_are_not_empty() {
    let set = CustomSet::new(vec![1]);
    assert!(!set.is_empty());
}

#[test]
#[ignore]
fn nothing_is_contained_in_an_empty_set() {
    let set = CustomSet::new(vec![]);
    assert!(!set.contains(&1));
}

#[test]
#[ignore]
fn true_when_the_element_is_in_the_set() {
    let set = CustomSet::new(vec![1, 2, 3]);
    assert!(set.contains(&1));
}

#[test]
#[ignore]
fn false_when_the_element_is_not_in_the_set() {
    let set = CustomSet::new(vec![1, 2, 3]);
    assert!(!set.contains(&4));
}

#[test]
#[ignore]
fn add_to_empty_set() {
    let mut set = CustomSet::new(vec![]);
    set.add(3);
    assert_eq!(set, CustomSet::new(vec![3]));
}

#[test]
#[ignore]
fn add_to_non_empty_set() {
    let mut set = CustomSet::new(vec![1, 2, 4]);
    set.add(3);
    assert_eq!(set, CustomSet::new(vec![1, 2, 3, 4]));
}

#[test]
#[ignore]
fn add_existing_element() {
    let mut set = CustomSet::new(vec![1, 2, 3]);
    set.add(3);
    assert_eq!(set, CustomSet::new(vec![1, 2, 3]));
}

#[test]
#[ignore]
fn empty_sets_are_subsets_of_each_other() {
    let set1: CustomSet<()> = CustomSet::new(vec![]);
    let set2: CustomSet<()> = CustomSet::new(vec![]);
    assert!(set1.is_subset(&set2));
    assert!(set2.is_subset(&set1));
}

#[test]
#[ignore]
fn empty_set_is_subset_of_non_empty_set() {
    let set1 = CustomSet::new(vec![]);
    let set2 = CustomSet::new(vec![1]);
    assert!(set1.is_subset(&set2));
}

#[test]
#[ignore]
fn non_empty_set_is_not_subset_of_empty_set() {
    let set1 = CustomSet::new(vec![1]);
    let set2 = CustomSet::new(vec![]);
    assert!(!set1.is_subset(&set2));
}

#[test]
#[ignore]
fn sets_with_same_elements_are_subsets() {
    let set1 = CustomSet::new(vec![1, 2, 3]);
    let set2 = CustomSet::new(vec![1, 2, 3]);
    assert!(set1.is_subset(&set2));
    assert!(set2.is_subset(&set1));
}

#[test]
#[ignore]
fn set_contained_in_other_set_is_a_subset() {
    let set1 = CustomSet::new(vec![1, 2, 3]);
    let set2 = CustomSet::new(vec![4, 1, 2, 3]);
    assert!(set1.is_subset(&set2));
}

#[test]
#[ignore]
fn set_not_contained_in_other_set_is_not_a_subset_one() {
    let set1 = CustomSet::new(vec![1, 2, 3]);
    let set2 = CustomSet::new(vec![4, 1, 3]);
    assert!(!set1.is_subset(&set2));
}

#[test]
#[ignore]
fn empty_sets_are_disjoint_with_each_other() {
    let set1: CustomSet<()> = CustomSet::new(vec![]);
    let set2: CustomSet<()> = CustomSet::new(vec![]);
    assert!(set1.is_disjoint(&set2));
    assert!(set2.is_disjoint(&set1));
}

#[test]
#[ignore]
fn empty_set_disjoint_with_non_empty_set() {
    let set1 = CustomSet::new(vec![]);
    let set2 = CustomSet::new(vec![1]);
    assert!(set1.is_disjoint(&set2));
}

#[test]
#[ignore]
fn non_empty_set_disjoint_with_empty_set() {
    let set1 = CustomSet::new(vec![1]);
    let set2 = CustomSet::new(vec![]);
    assert!(set1.is_disjoint(&set2));
}

#[test]
#[ignore]
fn sets_with_one_element_in_common_are_not_disjoint() {
    let set1 = CustomSet::new(vec![1, 2]);
    let set2 = CustomSet::new(vec![2, 3]);
    assert!(!set1.is_disjoint(&set2));
    assert!(!set2.is_disjoint(&set1));
}

#[test]
#[ignore]
fn sets_with_no_elements_in_common_are_disjoint() {
    let set1 = CustomSet::new(vec![1, 2]);
    let set2 = CustomSet::new(vec![3, 4]);
    assert!(set1.is_disjoint(&set2));
    assert!(set2.is_disjoint(&set1));
}

#[test]
#[ignore]
fn intersecting_empty_sets_return_empty_set() {
    let set1: CustomSet<()> = CustomSet::new(vec![]);
    let set2: CustomSet<()> = CustomSet::new(vec![]);
    assert_eq!(set1.intersection(&set2), CustomSet::new(vec![]));
}

#[test]
#[ignore]
fn intersecting_empty_set_with_non_empty_returns_empty_set() {
    let set1 = CustomSet::new(vec![]);
    let set2 = CustomSet::new(vec![3, 2, 5]);
    assert_eq!(set1.intersection(&set2), CustomSet::new(vec![]));
}

#[test]
#[ignore]
fn intersecting_non_empty_set_with_empty_returns_empty_set() {
    let set1 = CustomSet::new(vec![1, 2, 3, 4]);
    let set2 = CustomSet::new(vec![]);
    assert_eq!(set1.intersection(&set2), CustomSet::new(vec![]));
}

#[test]
#[ignore]
fn intersection_of_two_sets_with_no_shared_elements_is_an_empty_set() {
    let set1 = CustomSet::new(vec![1, 2, 3]);
    let set2 = CustomSet::new(vec![4, 5, 6]);
    assert_eq!(set1.intersection(&set2), CustomSet::new(vec![]));
    assert_eq!(set2.intersection(&set1), CustomSet::new(vec![]));
}

#[test]
#[ignore]
fn intersection_of_two_sets_with_shared_elements_is_a_set_of_the_shared_elements() {
    let set1 = CustomSet::new(vec![1, 2, 3, 4]);
    let set2 = CustomSet::new(vec![3, 2, 5]);
    assert_eq!(set1.intersection(&set2), CustomSet::new(vec![2, 3]));
    assert_eq!(set2.intersection(&set1), CustomSet::new(vec![2, 3]));
}

#[test]
#[ignore]
fn difference_of_two_empty_sets_is_empty_set() {
    let set1: CustomSet<()> = CustomSet::new(vec![]);
    let set2: CustomSet<()> = CustomSet::new(vec![]);
    assert_eq!(set1.difference(&set2), CustomSet::new(vec![]));
}

#[test]
#[ignore]
fn difference_of_an_empty_and_non_empty_set_is_an_empty_set() {
    let set1 = CustomSet::new(vec![]);
    let set2 = CustomSet::new(vec![3, 2, 5]);
    assert_eq!(set1.difference(&set2), CustomSet::new(vec![]));
}

#[test]
#[ignore]
fn difference_of_a_non_empty_set_and_empty_set_is_the_non_empty_set() {
    let set1 = CustomSet::new(vec![1, 2, 3, 4]);
    let set2 = CustomSet::new(vec![]);
    assert_eq!(set1.difference(&set2), CustomSet::new(vec![1, 2, 3, 4]));
}

#[test]
#[ignore]
fn difference_of_two_non_empty_sets_is_elements_only_in_first_set_one() {
    let set1 = CustomSet::new(vec![3, 2, 1]);
    let set2 = CustomSet::new(vec![2, 4]);
    assert_eq!(set1.difference(&set2), CustomSet::new(vec![1, 3]));
}

#[test]
#[ignore]
fn empty_sets_are_equal() {
    let set1: CustomSet<()> = CustomSet::new(vec![]);
    let set2: CustomSet<()> = CustomSet::new(vec![]);
    assert_eq!(set1, set2);
}

#[test]
#[ignore]
fn empty_set_is_not_equal_to_a_non_empty_set() {
    let set1 = CustomSet::new(vec![]);
    let set2 = CustomSet::new(vec![1, 2, 3]);
    assert!(set1 != set2);
}

#[test]
#[ignore]
fn non_empty_set_is_not_equal_to_an_empty_set() {
    let set1 = CustomSet::new(vec![1, 2, 3]);
    let set2 = CustomSet::new(vec![]);
    assert!(set1 != set2);
}

#[test]
#[ignore]
fn sets_with_the_same_elements_are_equal() {
    let set1 = CustomSet::new(vec![1, 2]);
    let set2 = CustomSet::new(vec![2, 1]);
    assert_eq!(set1, set2);
}

#[test]
#[ignore]
fn sets_with_different_elements_are_not_equal() {
    let set1 = CustomSet::new(vec![1, 2, 3]);
    let set2 = CustomSet::new(vec![2, 1, 4]);
    assert!(set1 != set2);
}

#[test]
#[ignore]
fn union_of_two_empty_sets_is_empty_set() {
    let set1: CustomSet<()> = CustomSet::new(vec![]);
    let set2: CustomSet<()> = CustomSet::new(vec![]);
    assert_eq!(set1.union(&set2), CustomSet::new(vec![]));
}

#[test]
#[ignore]
fn union_of_empty_set_and_non_empty_set_is_all_elements() {
    let set1 = CustomSet::new(vec![]);
    let set2 = CustomSet::new(vec![2]);
    assert_eq!(set1.union(&set2), CustomSet::new(vec![2]));
}

#[test]
#[ignore]
fn union_of_non_empty_set_and_empty_set_is_the_non_empty_set() {
    let set1 = CustomSet::new(vec![1, 3]);
    let set2 = CustomSet::new(vec![]);
    assert_eq!(set1.union(&set2), CustomSet::new(vec![1, 3]));
}

#[test]
#[ignore]
fn union_of_non_empty_sets_contains_all_unique_elements() {
    let set1 = CustomSet::new(vec![1, 3]);
    let set2 = CustomSet::new(vec![2, 3]);
    assert_eq!(set1.union(&set2), CustomSet::new(vec![3, 2, 1]));
}
<commit_msg>Update custom-set test order<commit_after>extern crate custom_set as set;

use set::*;

#[test]
fn sets_with_no_elements_are_empty() {
    let set: CustomSet<()> = CustomSet::new(vec![]);
    assert!(set.is_empty());
}

#[test]
#[ignore]
fn sets_with_elements_are_not_empty() {
    let set = CustomSet::new(vec![1]);
    assert!(!set.is_empty());
}

#[test]
#[ignore]
fn nothing_is_contained_in_an_empty_set() {
    let set = CustomSet::new(vec![]);
    assert!(!set.contains(&1));
}

#[test]
#[ignore]
fn true_when_the_element_is_in_the_set() {
    let set = CustomSet::new(vec![1, 2, 3]);
    assert!(set.contains(&1));
}

#[test]
#[ignore]
fn false_when_the_element_is_not_in_the_set() {
    let set = CustomSet::new(vec![1, 2, 3]);
    assert!(!set.contains(&4));
}

#[test]
#[ignore]
fn empty_sets_are_subsets_of_each_other() {
    let set1: CustomSet<()> = CustomSet::new(vec![]);
    let set2: CustomSet<()> = CustomSet::new(vec![]);
    assert!(set1.is_subset(&set2));
    assert!(set2.is_subset(&set1));
}

#[test]
#[ignore]
fn empty_set_is_subset_of_non_empty_set() {
    let set1 = CustomSet::new(vec![]);
    let set2 = CustomSet::new(vec![1]);
    assert!(set1.is_subset(&set2));
}

#[test]
#[ignore]
fn non_empty_set_is_not_subset_of_empty_set() {
    let set1 = CustomSet::new(vec![1]);
    let set2 = CustomSet::new(vec![]);
    assert!(!set1.is_subset(&set2));
}

#[test]
#[ignore]
fn sets_with_same_elements_are_subsets() {
    let set1 = CustomSet::new(vec![1, 2, 3]);
    let set2 = CustomSet::new(vec![1, 2, 3]);
    assert!(set1.is_subset(&set2));
    assert!(set2.is_subset(&set1));
}

#[test]
#[ignore]
fn set_contained_in_other_set_is_a_subset() {
    let set1 = CustomSet::new(vec![1, 2, 3]);
    let set2 = CustomSet::new(vec![4, 1, 2, 3]);
    assert!(set1.is_subset(&set2));
}

#[test]
#[ignore]
fn set_not_contained_in_other_set_is_not_a_subset_one() {
    let set1 = CustomSet::new(vec![1, 2, 3]);
    let set2 = CustomSet::new(vec![4, 1, 3]);
    assert!(!set1.is_subset(&set2));
}

#[test]
#[ignore]
fn empty_sets_are_disjoint_with_each_other() {
    let set1: CustomSet<()> = CustomSet::new(vec![]);
    let set2: CustomSet<()> = CustomSet::new(vec![]);
    assert!(set1.is_disjoint(&set2));
    assert!(set2.is_disjoint(&set1));
}

#[test]
#[ignore]
fn empty_set_disjoint_with_non_empty_set() {
    let set1 = CustomSet::new(vec![]);
    let set2 = CustomSet::new(vec![1]);
    assert!(set1.is_disjoint(&set2));
}

#[test]
#[ignore]
fn non_empty_set_disjoint_with_empty_set() {
    let set1 = CustomSet::new(vec![1]);
    let set2 = CustomSet::new(vec![]);
    assert!(set1.is_disjoint(&set2));
}

#[test]
#[ignore]
fn sets_with_one_element_in_common_are_not_disjoint() {
    let set1 = CustomSet::new(vec![1, 2]);
    let set2 = CustomSet::new(vec![2, 3]);
    assert!(!set1.is_disjoint(&set2));
    assert!(!set2.is_disjoint(&set1));
}

#[test]
#[ignore]
fn sets_with_no_elements_in_common_are_disjoint() {
    let set1 = CustomSet::new(vec![1, 2]);
    let set2 = CustomSet::new(vec![3, 4]);
    assert!(set1.is_disjoint(&set2));
    assert!(set2.is_disjoint(&set1));
}

#[test]
#[ignore]
fn empty_sets_are_equal() {
    let set1: CustomSet<()> = CustomSet::new(vec![]);
    let set2: CustomSet<()> = CustomSet::new(vec![]);
    assert_eq!(set1, set2);
}

#[test]
#[ignore]
fn empty_set_is_not_equal_to_a_non_empty_set() {
    let set1 = CustomSet::new(vec![]);
    let set2 = CustomSet::new(vec![1, 2, 3]);
    assert!(set1 != set2);
}

#[test]
#[ignore]
fn non_empty_set_is_not_equal_to_an_empty_set() {
    let set1 = CustomSet::new(vec![1, 2, 3]);
    let set2 = CustomSet::new(vec![]);
    assert!(set1 != set2);
}

#[test]
#[ignore]
fn sets_with_the_same_elements_are_equal() {
    let set1 = CustomSet::new(vec![1, 2]);
    let set2 = CustomSet::new(vec![2, 1]);
    assert_eq!(set1, set2);
}

#[test]
#[ignore]
fn sets_with_different_elements_are_not_equal() {
    let set1 = CustomSet::new(vec![1, 2, 3]);
    let set2 = CustomSet::new(vec![2, 1, 4]);
    assert!(set1 != set2);
}

#[test]
#[ignore]
fn add_to_empty_set() {
    let mut set = CustomSet::new(vec![]);
    set.add(3);
    assert_eq!(set, CustomSet::new(vec![3]));
}

#[test]
#[ignore]
fn add_to_non_empty_set() {
    let mut set = CustomSet::new(vec![1, 2, 4]);
    set.add(3);
    assert_eq!(set, CustomSet::new(vec![1, 2, 3, 4]));
}

#[test]
#[ignore]
fn add_existing_element() {
    let mut set = CustomSet::new(vec![1, 2, 3]);
    set.add(3);
    assert_eq!(set, CustomSet::new(vec![1, 2, 3]));
}

#[test]
#[ignore]
fn intersecting_empty_sets_return_empty_set() {
    let set1: CustomSet<()> = CustomSet::new(vec![]);
    let set2: CustomSet<()> = CustomSet::new(vec![]);
    assert_eq!(set1.intersection(&set2), CustomSet::new(vec![]));
}

#[test]
#[ignore]
fn intersecting_empty_set_with_non_empty_returns_empty_set() {
    let set1 = CustomSet::new(vec![]);
    let set2 = CustomSet::new(vec![3, 2, 5]);
    assert_eq!(set1.intersection(&set2), CustomSet::new(vec![]));
}

#[test]
#[ignore]
fn intersecting_non_empty_set_with_empty_returns_empty_set() {
    let set1 = CustomSet::new(vec![1, 2, 3, 4]);
    let set2 = CustomSet::new(vec![]);
    assert_eq!(set1.intersection(&set2), CustomSet::new(vec![]));
}

#[test]
#[ignore]
fn intersection_of_two_sets_with_no_shared_elements_is_an_empty_set() {
    let set1 = CustomSet::new(vec![1, 2, 3]);
    let set2 = CustomSet::new(vec![4, 5, 6]);
    assert_eq!(set1.intersection(&set2), CustomSet::new(vec![]));
    assert_eq!(set2.intersection(&set1), CustomSet::new(vec![]));
}

#[test]
#[ignore]
fn intersection_of_two_sets_with_shared_elements_is_a_set_of_the_shared_elements() {
    let set1 = CustomSet::new(vec![1, 2, 3, 4]);
    let set2 = CustomSet::new(vec![3, 2, 5]);
    assert_eq!(set1.intersection(&set2), CustomSet::new(vec![2, 3]));
    assert_eq!(set2.intersection(&set1), CustomSet::new(vec![2, 3]));
}

#[test]
#[ignore]
fn difference_of_two_empty_sets_is_empty_set() {
    let set1: CustomSet<()> = CustomSet::new(vec![]);
    let set2: CustomSet<()> = CustomSet::new(vec![]);
    assert_eq!(set1.difference(&set2), CustomSet::new(vec![]));
}

#[test]
#[ignore]
fn difference_of_an_empty_and_non_empty_set_is_an_empty_set() {
    let set1 = CustomSet::new(vec![]);
    let set2 = CustomSet::new(vec![3, 2, 5]);
    assert_eq!(set1.difference(&set2), CustomSet::new(vec![]));
}

#[test]
#[ignore]
fn difference_of_a_non_empty_set_and_empty_set_is_the_non_empty_set() {
    let set1 = CustomSet::new(vec![1, 2, 3, 4]);
    let set2 = CustomSet::new(vec![]);
    assert_eq!(set1.difference(&set2), CustomSet::new(vec![1, 2, 3, 4]));
}

#[test]
#[ignore]
fn difference_of_two_non_empty_sets_is_elements_only_in_first_set_one() {
    let set1 = CustomSet::new(vec![3, 2, 1]);
    let set2 = CustomSet::new(vec![2, 4]);
    assert_eq!(set1.difference(&set2), CustomSet::new(vec![1, 3]));
}

#[test]
#[ignore]
fn union_of_two_empty_sets_is_empty_set() {
    let set1: CustomSet<()> = CustomSet::new(vec![]);
    let set2: CustomSet<()> = CustomSet::new(vec![]);
    assert_eq!(set1.union(&set2), CustomSet::new(vec![]));
}

#[test]
#[ignore]
fn union_of_empty_set_and_non_empty_set_is_all_elements() {
    let set1 = CustomSet::new(vec![]);
    let set2 = CustomSet::new(vec![2]);
    assert_eq!(set1.union(&set2), CustomSet::new(vec![2]));
}

#[test]
#[ignore]
fn union_of_non_empty_set_and_empty_set_is_the_non_empty_set() {
    let set1 = CustomSet::new(vec![1, 3]);
    let set2 = CustomSet::new(vec![]);
    assert_eq!(set1.union(&set2), CustomSet::new(vec![1, 3]));
}

#[test]
#[ignore]
fn union_of_non_empty_sets_contains_all_unique_elements() {
    let set1 = CustomSet::new(vec![1, 3]);
    let set2 = CustomSet::new(vec![2, 3]);
    assert_eq!(set1.union(&set2), CustomSet::new(vec![3, 2, 1]));
}
<|endoftext|>


<commit_before>use crate::future::{FutureObj, LocalFutureObj};
use core::fmt;

/// The `Spawn` trait allows for pushing futures onto an executor that will
/// run them to completion.
pub trait Spawn {
    /// Spawns a future that will be run to completion.
    ///
    /// # Errors
    ///
    /// The executor may be unable to spawn tasks. Spawn errors should
    /// represent relatively rare scenarios, such as the executor
    /// having been shut down so that it is no longer able to accept
    /// tasks.
    fn spawn_obj(&mut self, future: FutureObj<'static, ()>)
        -> Result<(), SpawnError>;

    /// Determines whether the executor is able to spawn new tasks.
    ///
    /// This method will return `Ok` when the executor is *likely*
    /// (but not guaranteed) to accept a subsequent spawn attempt.
    /// Likewise, an `Err` return means that `spawn` is likely, but
    /// not guaranteed, to yield an error.
    #[inline]
    fn status(&self) -> Result<(), SpawnError> {
        Ok(())
    }
}

/// The `LocalSpawn` is similar to [`Spawn`], but allows spawning futures
/// that don't implement `Send`.
pub trait LocalSpawn {
    /// Spawns a future that will be run to completion.
    ///
    /// # Errors
    ///
    /// The executor may be unable to spawn tasks. Spawn errors should
    /// represent relatively rare scenarios, such as the executor
    /// having been shut down so that it is no longer able to accept
    /// tasks.
    fn spawn_local_obj(&mut self, future: LocalFutureObj<'static, ()>)
        -> Result<(), SpawnError>;

    /// Determines whether the executor is able to spawn new tasks.
    ///
    /// This method will return `Ok` when the executor is *likely*
    /// (but not guaranteed) to accept a subsequent spawn attempt.
    /// Likewise, an `Err` return means that `spawn` is likely, but
    /// not guaranteed, to yield an error.
    #[inline]
    fn status_local(&self) -> Result<(), SpawnError> {
        Ok(())
    }
}

/// An error that occurred during spawning.
pub struct SpawnError {
    _hidden: (),
}

impl fmt::Debug for SpawnError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_tuple("SpawnError")
            .field(&"shutdown")
            .finish()
    }
}

impl SpawnError {
    /// Spawning failed because the executor has been shut down.
    pub fn shutdown() -> Self {
        Self { _hidden: () }
    }

    /// Check whether spawning failed to the executor being shut down.
    pub fn is_shutdown(&self) -> bool {
        true
    }
}

impl<Sp: ?Sized + Spawn> Spawn for &mut Sp {
    fn spawn_obj(&mut self, future: FutureObj<'static, ()>)
    -> Result<(), SpawnError> {
        Sp::spawn_obj(self, future)
    }

    fn status(&self) -> Result<(), SpawnError> {
        Sp::status(self)
    }
}

impl<Sp: ?Sized + LocalSpawn> LocalSpawn for &mut Sp {
    fn spawn_local_obj(&mut self, future: LocalFutureObj<'static, ()>)
    -> Result<(), SpawnError> {
        Sp::spawn_local_obj(self, future)
    }

    fn status_local(&self) -> Result<(), SpawnError> {
        Sp::status_local(self)
    }
}

#[cfg(feature = "alloc")]
mod if_alloc {
    use alloc::boxed::Box;
    use super::*;

    impl<Sp: ?Sized + Spawn> Spawn for Box<Sp> {
        fn spawn_obj(&mut self, future: FutureObj<'static, ()>)
        -> Result<(), SpawnError> {
            (**self).spawn_obj(future)
        }

        fn status(&self) -> Result<(), SpawnError> {
            (**self).status()
        }
    }

    impl<Sp: ?Sized + LocalSpawn> LocalSpawn for Box<Sp> {
        fn spawn_local_obj(&mut self, future: LocalFutureObj<'static, ()>)
        -> Result<(), SpawnError> {
            (**self).spawn_local_obj(future)
        }

        fn status_local(&self) -> Result<(), SpawnError> {
            (**self).status_local()
        }
    }
}
<commit_msg>Implement std::error::Error for SpawnError (#1604)<commit_after>use crate::future::{FutureObj, LocalFutureObj};
use core::fmt;

/// The `Spawn` trait allows for pushing futures onto an executor that will
/// run them to completion.
pub trait Spawn {
    /// Spawns a future that will be run to completion.
    ///
    /// # Errors
    ///
    /// The executor may be unable to spawn tasks. Spawn errors should
    /// represent relatively rare scenarios, such as the executor
    /// having been shut down so that it is no longer able to accept
    /// tasks.
    fn spawn_obj(&mut self, future: FutureObj<'static, ()>)
        -> Result<(), SpawnError>;

    /// Determines whether the executor is able to spawn new tasks.
    ///
    /// This method will return `Ok` when the executor is *likely*
    /// (but not guaranteed) to accept a subsequent spawn attempt.
    /// Likewise, an `Err` return means that `spawn` is likely, but
    /// not guaranteed, to yield an error.
    #[inline]
    fn status(&self) -> Result<(), SpawnError> {
        Ok(())
    }
}

/// The `LocalSpawn` is similar to [`Spawn`], but allows spawning futures
/// that don't implement `Send`.
pub trait LocalSpawn {
    /// Spawns a future that will be run to completion.
    ///
    /// # Errors
    ///
    /// The executor may be unable to spawn tasks. Spawn errors should
    /// represent relatively rare scenarios, such as the executor
    /// having been shut down so that it is no longer able to accept
    /// tasks.
    fn spawn_local_obj(&mut self, future: LocalFutureObj<'static, ()>)
        -> Result<(), SpawnError>;

    /// Determines whether the executor is able to spawn new tasks.
    ///
    /// This method will return `Ok` when the executor is *likely*
    /// (but not guaranteed) to accept a subsequent spawn attempt.
    /// Likewise, an `Err` return means that `spawn` is likely, but
    /// not guaranteed, to yield an error.
    #[inline]
    fn status_local(&self) -> Result<(), SpawnError> {
        Ok(())
    }
}

/// An error that occurred during spawning.
pub struct SpawnError {
    _hidden: (),
}

impl fmt::Debug for SpawnError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_tuple("SpawnError")
            .field(&"shutdown")
            .finish()
    }
}

impl fmt::Display for SpawnError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "Executor is shutdown")
    }
}

#[cfg(feature = "std")]
impl std::error::Error for SpawnError {}

impl SpawnError {
    /// Spawning failed because the executor has been shut down.
    pub fn shutdown() -> Self {
        Self { _hidden: () }
    }

    /// Check whether spawning failed to the executor being shut down.
    pub fn is_shutdown(&self) -> bool {
        true
    }
}

impl<Sp: ?Sized + Spawn> Spawn for &mut Sp {
    fn spawn_obj(&mut self, future: FutureObj<'static, ()>)
    -> Result<(), SpawnError> {
        Sp::spawn_obj(self, future)
    }

    fn status(&self) -> Result<(), SpawnError> {
        Sp::status(self)
    }
}

impl<Sp: ?Sized + LocalSpawn> LocalSpawn for &mut Sp {
    fn spawn_local_obj(&mut self, future: LocalFutureObj<'static, ()>)
    -> Result<(), SpawnError> {
        Sp::spawn_local_obj(self, future)
    }

    fn status_local(&self) -> Result<(), SpawnError> {
        Sp::status_local(self)
    }
}

#[cfg(feature = "alloc")]
mod if_alloc {
    use alloc::boxed::Box;
    use super::*;

    impl<Sp: ?Sized + Spawn> Spawn for Box<Sp> {
        fn spawn_obj(&mut self, future: FutureObj<'static, ()>)
        -> Result<(), SpawnError> {
            (**self).spawn_obj(future)
        }

        fn status(&self) -> Result<(), SpawnError> {
            (**self).status()
        }
    }

    impl<Sp: ?Sized + LocalSpawn> LocalSpawn for Box<Sp> {
        fn spawn_local_obj(&mut self, future: LocalFutureObj<'static, ()>)
        -> Result<(), SpawnError> {
            (**self).spawn_local_obj(future)
        }

        fn status_local(&self) -> Result<(), SpawnError> {
            (**self).status_local()
        }
    }
}
<|endoftext|>


<commit_before>// xfail-fast #7103 `extern mod` does not work on windows

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

extern mod extra; // {En,De}codable
mod submod {
    // if any of these are implemented without global calls for any
    // function calls, then being in a submodule will (correctly)
    // cause errors about unrecognised module `std` (or `extra`)
    #[deriving(Eq, Ord, TotalEq, TotalOrd,
               IterBytes,
               Clone, DeepClone,
               ToStr, Rand,
               Encodable, Decodable)]
    enum A { A1(uint), A2(int) }

    #[deriving(Eq, Ord, TotalEq, TotalOrd,
               IterBytes,
               Clone, DeepClone,
               ToStr, Rand,
               Encodable, Decodable)]
    struct B { x: uint, y: int }

    #[deriving(Eq, Ord, TotalEq, TotalOrd,
               IterBytes,
               Clone, DeepClone,
               ToStr, Rand,
               Encodable, Decodable)]
    struct C(uint, int);

}

fn main() {}
<commit_msg>xfail-pretty on un-xfailed test<commit_after>// xfail-fast #7103 `extern mod` does not work on windows
// xfail-pretty - does not converge

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

extern mod extra; // {En,De}codable
mod submod {
    // if any of these are implemented without global calls for any
    // function calls, then being in a submodule will (correctly)
    // cause errors about unrecognised module `std` (or `extra`)
    #[deriving(Eq, Ord, TotalEq, TotalOrd,
               IterBytes,
               Clone, DeepClone,
               ToStr, Rand,
               Encodable, Decodable)]
    enum A { A1(uint), A2(int) }

    #[deriving(Eq, Ord, TotalEq, TotalOrd,
               IterBytes,
               Clone, DeepClone,
               ToStr, Rand,
               Encodable, Decodable)]
    struct B { x: uint, y: int }

    #[deriving(Eq, Ord, TotalEq, TotalOrd,
               IterBytes,
               Clone, DeepClone,
               ToStr, Rand,
               Encodable, Decodable)]
    struct C(uint, int);

}

fn main() {}
<|endoftext|>


<commit_before>use std::ptr;
use std::mem;
use x11::xlib;
use x11::keysym;

use super::config::Config;
use super::handler;

pub struct WindowManager {
    display: *mut xlib::Display,
    root:    xlib::Window,

    config: Config
}

impl WindowManager {
    pub fn new() -> WindowManager {
	unsafe {
	    let display = xlib::XOpenDisplay(ptr::null());
            if display == ptr::null_mut() {
                panic!("can't open display")
            }
	    let screen  = xlib::XDefaultScreenOfDisplay(display);
	    let root    = xlib::XRootWindowOfScreen(screen);

	    WindowManager {
	        display: display,
	        root:    root,

                config: Config::load(),
	    }
	}
    }

    pub fn run(&mut self) {
        let mask = xlib::SubstructureRedirectMask | xlib::SubstructureNotifyMask;
        let keymask = xlib::KeyPressMask | xlib::KeyReleaseMask;
        unsafe{
            xlib::XSelectInput(self.display, self.root,
                               mask | keymask);
            xlib::XSync(self.display, 0);
        }

        loop {
            //handle events here
            let mut e = xlib::XEvent{
                pad: [0; 24],
            };

            unsafe {
                xlib::XNextEvent(self.display, &mut e);
                let t = e.get_type();

                match t {
                    xlib::CreateNotify => {
                        debug!("create notify");
                        let event = mem::transmute_copy::<xlib::XEvent, xlib::XCreateWindowEvent>(&e);

                        // chance attributes before display
                        let mut attrs: xlib::XSetWindowAttributes = mem::zeroed();
                        attrs.event_mask = xlib::KeyReleaseMask;
                        let valuemask = xlib::CWEventMask;
                        xlib::XChangeWindowAttributes(self.display, event.window, valuemask, &mut attrs);

                        // display window
                        xlib::XMapWindow(self.display, event.window);
                    }
                    xlib::DestroyNotify => {
                        debug!("destroy notify");
                        let event = mem::transmute_copy::<xlib::XEvent, xlib::XDestroyWindowEvent>(&e);

                    }
                    xlib::KeyRelease => {
                        debug!("key release");
                        let mut event = mem::transmute_copy::<xlib::XEvent, xlib::XKeyEvent>(&e);

                        if event.state > 0 {
                            let mut sym: xlib::KeySym = 0;
                            let status: *mut xlib::XComposeStatus = ptr::null_mut();
                            xlib::XLookupString(&mut event, ptr::null_mut(), 0, &mut sym, status);

                            let b = handler::KeyBind {
                                key: sym,
                                mask: event.state,
                            };
                            debug!("key {} {}", event.state, sym);
                            match self.config.bindsyms.get_mut(&b) {
                                Some(handler) => {
                                    handler.handle();
                                }
                                None => {
                                    println!("no bind")
                                }
                            }
                        }
                    }
                    _ => {

                    }
                }
            }
        }
    }
}
<commit_msg>use workspace and layout<commit_after>extern crate libc;
use std::ptr;
use std::mem;
use std::slice::from_raw_parts;
use std::string::String;
use std::collections::HashMap;
use x11::xlib;
use x11::keysym;

use super::config::Config;
use super::workspace::Workspace;
use super::handler;

fn cast_event<T>(e: &xlib::XEvent) -> T {
    unsafe{
        mem::transmute_copy::<xlib::XEvent, T>(e)
    }
}

fn get_text_property(display: *mut xlib::Display, window: xlib::Window, atom: xlib::Atom) -> Option<String>{
    unsafe{
        let mut prop: xlib::XTextProperty = mem::zeroed();
        let r = xlib::XGetTextProperty(display, window, &mut prop, atom);
        if r == 0 {
            None
        }else{
            Some(String::from_raw_parts(prop.value, prop.nitems as usize, prop.nitems as usize + 1 ))
        }
    }
}

pub struct WindowManager {
    pub display: *mut xlib::Display,
    pub screen_num: libc::c_int,
    pub root:    xlib::Window,

    pub workspaces: HashMap<char, Workspace>,
    pub workspace: Workspace,
    config: Config
}

impl WindowManager {
    pub fn new() -> WindowManager {
	unsafe {
	    let display = xlib::XOpenDisplay(ptr::null());
            if display == ptr::null_mut() {
                panic!("can't open display")
            }
	    let screen_num  = xlib::XDefaultScreen(display);
	    let root    = xlib::XRootWindow(display, screen_num);

	    let mut wm = WindowManager {
	        display: display,
                screen_num: screen_num,
	        root:    root,

                config: Config::load(),
                workspaces: HashMap::new(),
                workspace: Workspace::new(),
            };
            let space = Workspace::new();
            wm.workspaces.insert('1', space);
            wm
	}
    }

    pub fn run(&mut self) {
        let mask = xlib::SubstructureRedirectMask | xlib::SubstructureNotifyMask;
        let keymask = xlib::KeyPressMask | xlib::KeyReleaseMask;
        unsafe{
            xlib::XSelectInput(self.display, self.root,
                               mask | keymask);
            xlib::XSync(self.display, 0);
        }

        let mut workspace = Workspace::new();
        loop {
            //handle events here
            let mut e = xlib::XEvent{
                pad: [0; 24],
            };

            unsafe {
                xlib::XNextEvent(self.display, &mut e);
                let t = e.get_type();
                match t {
                    xlib::CreateNotify => {
                        let event = cast_event::<xlib::XCreateWindowEvent>(&e);

                        if event.override_redirect != 0 {
                            continue;
                        }

                        // change attributes before display
                        let mut attrs: xlib::XSetWindowAttributes = mem::zeroed();
                        attrs.event_mask = xlib::KeyReleaseMask;
                        let valuemask = xlib::CWEventMask;
                        xlib::XChangeWindowAttributes(self.display, event.window, valuemask, &mut attrs);

                        // add to workspace
                        // let mut w = self.workspaces.get_mut(&'1');
                        // match w {
                        //     Some(workspace) => {
                        //         workspace.add(event.window);
                        //         workspace.config(self);
                        //     }
                        //     None => {}
                        // }

                        // get window property
                        let n = get_text_property(self.display, event.window, xlib::XA_WM_NAME);
                        match n {
                            Some(s) => {debug!("create window {} for {}", event.window, s);}
                            None => {}
                        }

                        // let mut actual_type_return: u64 = 0;
                        // let mut actual_format_return: i32 = 0;
                        // let mut nitem_return: libc::c_ulong = 0;
                        // let mut bytes_after_return: libc::c_ulong = 0;
                        // let mut prop_return: *mut libc::c_uchar = mem::zeroed();
                        // let r = xlib::XGetWindowProperty(self.display, event.window, xlib::XA_WM_NAME,
                        //                          0, 0xFFFFFFFF, 0, 0,
                        //                          &mut actual_type_return,
                        //                          &mut actual_format_return,
                        //                          &mut nitem_return,
                        //                          &mut bytes_after_return,
                        //                          &mut prop_return);

                        // debug!("result get wp {}", r);
                        // if r == 0 {

                        // }else{
                        //     debug!("actual format return {}", actual_format_return);
                        //     if actual_format_return == 0 {

                        //     }
                        //     else {
                        //         // let s = from_raw_parts(prop_return as *const libc::c_ulong, nitems_return as usize).iter()
                        //         //     .map(|&c| c as u64)
                        //         //     .collect();
                        //         let s = String::from_raw_parts(prop_return, nitem_return as usize, nitem_return as usize + 1 );
                        //         println!("{}", s);

                        //     }
                        // }

                    }
                    xlib::DestroyNotify => {
                        debug!("destroy notify");
                        let event = cast_event::<xlib::XDestroyWindowEvent>(&e);
                    }
                    xlib::MapNotify => {
                        debug!("map notify");
                        let event = cast_event::<xlib::XMapEvent>(&e);
                        println!("event {}", event.event);
                        println!("w {}", event.window);
                    }
                    xlib::UnmapNotify => {
                        debug!("unmap notify");
                        let event = cast_event::<xlib::XUnmapEvent>(&e);

                        match workspace.contain(event.window) {
                            Some(index) => {
                                workspace.remove(event.window);
                                workspace.config(self);                                             }
                            None => {}
                        }
                    }
                    xlib::MapRequest => {
                        debug!("map request");
                        let event = cast_event::<xlib::XMapRequestEvent>(&e);
                        println!("w {}", event.window);
                        xlib::XMapWindow(self.display, event.window);

                        // add app top-level window to workspace
                        let mut attrs: xlib::XWindowAttributes = mem::zeroed();
                        xlib::XGetWindowAttributes(self.display, event.window, &mut attrs);

                        if attrs.override_redirect == 0{
                            debug!("top level window");

                            if workspace.contain(event.window).is_none() {
                                workspace.add(event.window);
                                workspace.config(self);
                            }
                        }

                    }
                    xlib::ClientMessage => {
                        debug!("client message");
                        let event = cast_event::<xlib::XClientMessageEvent>(&e);

                    }
                    xlib::KeyRelease => {
                        debug!("key release");
                        let mut event = cast_event::<xlib::XKeyEvent>(&e);

                        if event.state > 0 {
                            let mut sym: xlib::KeySym = 0;
                            let status: *mut xlib::XComposeStatus = ptr::null_mut();
                            xlib::XLookupString(&mut event, ptr::null_mut(), 0, &mut sym, status);

                            let b = handler::KeyBind {
                                key: sym,
                                mask: event.state,
                            };
                            debug!("key {} {}", event.state, sym);
                            match self.config.bindsyms.get_mut(&b) {
                                Some(handler) => {
                                    handler.handle();
                                }
                                None => {
                                    println!("no bind")
                                }
                            }
                        }
                    }
                    xlib::ConfigureNotify => {
                        debug!("configure notify");
                    }
                    xlib::ConfigureRequest =>{
                        debug!("configure request");
                        let mut event = cast_event::<xlib::XConfigureRequestEvent>(&e);

                        // let mut change = xlib::XWindowChanges {
                        //     x: event.x,
                        //     y: event.y,
                        //     width: event.width,
                        //     height: event.height,
                        //     border_width: event.border_width,
                        //     sibling: event.above,
                        //     stack_mode: event.detail
                        // };
                        // debug!("config x: {}, y: {}, width: {}, height: {}",
                        //        change.x, change.y, change.width, change.height);
                        // xlib::XConfigureWindow(event.display, event.window, event.value_mask as u32, &mut change);

                    }
                    _ => {
                        debug!("unhandled event {}", t);
                    }
                }
            }
        }
    }
}
<|endoftext|>


<commit_before>use proc_macro2::{Span, TokenStream};
use quote::quote;
use syn::{Data, DeriveInput, Ident};

use crate::helpers::{non_enum_error, HasStrumVariantProperties, HasTypeProperties};

pub fn enum_iter_inner(ast: &DeriveInput) -> syn::Result<TokenStream> {
    let name = &ast.ident;
    let gen = &ast.generics;
    let (impl_generics, ty_generics, where_clause) = gen.split_for_impl();
    let vis = &ast.vis;
    let type_properties = ast.get_type_properties()?;
    let strum_module_path = type_properties.crate_module_path();

    if gen.lifetimes().count() > 0 {
        return Err(syn::Error::new(
            Span::call_site(),
            "This macro doesn't support enums with lifetimes. \
             The resulting enums would be unbounded.",
        ));
    }

    let phantom_data = if gen.type_params().count() > 0 {
        let g = gen.type_params().map(|param| &param.ident);
        quote! { < ( #(#g),* ) > }
    } else {
        quote! { < () > }
    };

    let variants = match &ast.data {
        Data::Enum(v) => &v.variants,
        _ => return Err(non_enum_error()),
    };

    let mut arms = Vec::new();
    let mut idx = 0usize;
    for variant in variants {
        use syn::Fields::*;

        if variant.get_variant_properties()?.disabled.is_some() {
            continue;
        }

        let ident = &variant.ident;
        let params = match &variant.fields {
            Unit => quote! {},
            Unnamed(fields) => {
                let defaults = ::std::iter::repeat(quote!(::core::default::Default::default()))
                    .take(fields.unnamed.len());
                quote! { (#(#defaults),*) }
            }
            Named(fields) => {
                let fields = fields
                    .named
                    .iter()
                    .map(|field| field.ident.as_ref().unwrap());
                quote! { {#(#fields: ::core::default::Default::default()),*} }
            }
        };

        arms.push(quote! {#idx => ::core::option::Option::Some(#name::#ident #params)});
        idx += 1;
    }

    let variant_count = arms.len();
    arms.push(quote! { _ => ::core::option::Option::None });
    let iter_name = syn::parse_str::<Ident>(&format!("{}Iter", name)).unwrap();

    Ok(quote! {
        #[allow(missing_docs)]
        #vis struct #iter_name #ty_generics {
            idx: usize,
            back_idx: usize,
            marker: ::core::marker::PhantomData #phantom_data,
        }

        impl #impl_generics #iter_name #ty_generics #where_clause {
            fn get(&self, idx: usize) -> Option<#name #ty_generics> {
                match idx {
                    #(#arms),*
                }
            }
        }

        impl #impl_generics #strum_module_path::IntoEnumIterator for #name #ty_generics #where_clause {
            type Iterator = #iter_name #ty_generics;
            fn iter() -> #iter_name #ty_generics {
                #iter_name {
                    idx: 0,
                    back_idx: 0,
                    marker: ::core::marker::PhantomData,
                }
            }
        }

        impl #impl_generics Iterator for #iter_name #ty_generics #where_clause {
            type Item = #name #ty_generics;

            fn next(&mut self) -> Option<<Self as Iterator>::Item> {
                self.nth(0)
            }

            fn size_hint(&self) -> (usize, Option<usize>) {
                let t = if self.idx + self.back_idx >= #variant_count { 0 } else { #variant_count - self.idx - self.back_idx };
                (t, Some(t))
            }

            fn nth(&mut self, n: usize) -> Option<<Self as Iterator>::Item> {
                let idx = self.idx + n + 1;
                if idx + self.back_idx > #variant_count {
                    // We went past the end of the iterator. Freeze idx at #variant_count
                    // so that it doesn't overflow if the user calls this repeatedly.
                    // See PR #76 for context.
                    self.idx = #variant_count;
                    None
                } else {
                    self.idx = idx;
                    self.get(idx - 1)
                }
            }
        }

        impl #impl_generics ExactSizeIterator for #iter_name #ty_generics #where_clause {
            fn len(&self) -> usize {
                self.size_hint().0
            }
        }

        impl #impl_generics DoubleEndedIterator for #iter_name #ty_generics #where_clause {
            fn next_back(&mut self) -> Option<<Self as Iterator>::Item> {
                let back_idx = self.back_idx + 1;

                if self.idx + back_idx > #variant_count {
                    // We went past the end of the iterator. Freeze back_idx at #variant_count
                    // so that it doesn't overflow if the user calls this repeatedly.
                    // See PR #76 for context.
                    self.back_idx = #variant_count;
                    None
                } else {
                    self.back_idx = back_idx;
                    self.get(#variant_count - self.back_idx)
                }
            }
        }

        impl #impl_generics Clone for #iter_name #ty_generics #where_clause {
            fn clone(&self) -> #iter_name #ty_generics {
                #iter_name {
                    idx: self.idx,
                    back_idx: self.back_idx,
                    marker: self.marker.clone(),
                }
            }
        }
    })
}
<commit_msg>Peternator7/enum iter doc comment (#204)<commit_after>use proc_macro2::{Span, TokenStream};
use quote::quote;
use syn::{Data, DeriveInput, Ident};

use crate::helpers::{non_enum_error, HasStrumVariantProperties, HasTypeProperties};

pub fn enum_iter_inner(ast: &DeriveInput) -> syn::Result<TokenStream> {
    let name = &ast.ident;
    let gen = &ast.generics;
    let (impl_generics, ty_generics, where_clause) = gen.split_for_impl();
    let vis = &ast.vis;
    let type_properties = ast.get_type_properties()?;
    let strum_module_path = type_properties.crate_module_path();

    if gen.lifetimes().count() > 0 {
        return Err(syn::Error::new(
            Span::call_site(),
            "This macro doesn't support enums with lifetimes. \
             The resulting enums would be unbounded.",
        ));
    }

    let phantom_data = if gen.type_params().count() > 0 {
        let g = gen.type_params().map(|param| &param.ident);
        quote! { < ( #(#g),* ) > }
    } else {
        quote! { < () > }
    };

    let variants = match &ast.data {
        Data::Enum(v) => &v.variants,
        _ => return Err(non_enum_error()),
    };

    let mut arms = Vec::new();
    let mut idx = 0usize;
    for variant in variants {
        use syn::Fields::*;

        if variant.get_variant_properties()?.disabled.is_some() {
            continue;
        }

        let ident = &variant.ident;
        let params = match &variant.fields {
            Unit => quote! {},
            Unnamed(fields) => {
                let defaults = ::std::iter::repeat(quote!(::core::default::Default::default()))
                    .take(fields.unnamed.len());
                quote! { (#(#defaults),*) }
            }
            Named(fields) => {
                let fields = fields
                    .named
                    .iter()
                    .map(|field| field.ident.as_ref().unwrap());
                quote! { {#(#fields: ::core::default::Default::default()),*} }
            }
        };

        arms.push(quote! {#idx => ::core::option::Option::Some(#name::#ident #params)});
        idx += 1;
    }

    let variant_count = arms.len();
    arms.push(quote! { _ => ::core::option::Option::None });
    let iter_name = syn::parse_str::<Ident>(&format!("{}Iter", name)).unwrap();

    Ok(quote! {
        #[doc = "An iterator over the variants of [Self]"]
        #vis struct #iter_name #ty_generics {
            idx: usize,
            back_idx: usize,
            marker: ::core::marker::PhantomData #phantom_data,
        }

        impl #impl_generics #iter_name #ty_generics #where_clause {
            fn get(&self, idx: usize) -> Option<#name #ty_generics> {
                match idx {
                    #(#arms),*
                }
            }
        }

        impl #impl_generics #strum_module_path::IntoEnumIterator for #name #ty_generics #where_clause {
            type Iterator = #iter_name #ty_generics;
            fn iter() -> #iter_name #ty_generics {
                #iter_name {
                    idx: 0,
                    back_idx: 0,
                    marker: ::core::marker::PhantomData,
                }
            }
        }

        impl #impl_generics Iterator for #iter_name #ty_generics #where_clause {
            type Item = #name #ty_generics;

            fn next(&mut self) -> Option<<Self as Iterator>::Item> {
                self.nth(0)
            }

            fn size_hint(&self) -> (usize, Option<usize>) {
                let t = if self.idx + self.back_idx >= #variant_count { 0 } else { #variant_count - self.idx - self.back_idx };
                (t, Some(t))
            }

            fn nth(&mut self, n: usize) -> Option<<Self as Iterator>::Item> {
                let idx = self.idx + n + 1;
                if idx + self.back_idx > #variant_count {
                    // We went past the end of the iterator. Freeze idx at #variant_count
                    // so that it doesn't overflow if the user calls this repeatedly.
                    // See PR #76 for context.
                    self.idx = #variant_count;
                    None
                } else {
                    self.idx = idx;
                    self.get(idx - 1)
                }
            }
        }

        impl #impl_generics ExactSizeIterator for #iter_name #ty_generics #where_clause {
            fn len(&self) -> usize {
                self.size_hint().0
            }
        }

        impl #impl_generics DoubleEndedIterator for #iter_name #ty_generics #where_clause {
            fn next_back(&mut self) -> Option<<Self as Iterator>::Item> {
                let back_idx = self.back_idx + 1;

                if self.idx + back_idx > #variant_count {
                    // We went past the end of the iterator. Freeze back_idx at #variant_count
                    // so that it doesn't overflow if the user calls this repeatedly.
                    // See PR #76 for context.
                    self.back_idx = #variant_count;
                    None
                } else {
                    self.back_idx = back_idx;
                    self.get(#variant_count - self.back_idx)
                }
            }
        }

        impl #impl_generics Clone for #iter_name #ty_generics #where_clause {
            fn clone(&self) -> #iter_name #ty_generics {
                #iter_name {
                    idx: self.idx,
                    back_idx: self.back_idx,
                    marker: self.marker.clone(),
                }
            }
        }
    })
}
<|endoftext|>


<commit_before>// return Some(x) where x is the number of steps required to reach 1
pub fn collatz(n: u64) -> Option<u64> {
    unimplemented!()
}
<commit_msg>collatz-conjecture: eliminate stub warnings<commit_after>pub fn collatz(n: u64) -> Option<u64> {
    unimplemented!(
        "return Some(x) where x is the number of steps required to reach 1 starting with {}",
        n,
    )
}
<|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/. */

//! A simple LRU cache.

#![deny(missing_docs)]

use std::{iter, slice};

/// A LRU cache used to store a set of at most `n` elements at the same time.
///
/// Currently used for the style sharing candidate cache.
pub struct LRUCache<K> {
    entries: Vec<K>,
    cache_size: usize,
}

/// A iterator over the items of the LRU cache.
pub type LRUCacheIterator<'a, K> = iter::Rev<slice::Iter<'a, K>>;

/// A iterator over the mutable items of the LRU cache.
pub type LRUCacheMutIterator<'a, K> = iter::Rev<slice::IterMut<'a, K>>;

impl<K: PartialEq> LRUCache<K> {
    /// Create a new LRU cache with `size` elements at most.
    pub fn new(size: usize) -> Self {
        LRUCache {
          entries: vec![],
          cache_size: size,
        }
    }

    /// Returns the number of elements in the cache.
    pub fn num_entries(&self) -> usize {
        self.entries.len()
    }

    #[inline]
    /// Touch a given position, and put it in the last item on the list.
    pub fn touch(&mut self, pos: usize) {
        let last_index = self.entries.len() - 1;
        if pos != last_index {
            let entry = self.entries.remove(pos);
            self.entries.push(entry);
        }
    }

    /// Iterate over the contents of this cache, from more to less recently
    /// used.
    pub fn iter(&self) -> LRUCacheIterator<K> {
        self.entries.iter().rev()
    }

    /// Iterate mutably over the contents of this cache.
    pub fn iter_mut(&mut self) -> LRUCacheMutIterator<K> {
        self.entries.iter_mut().rev()
    }

    /// Insert a given key in the cache.
    pub fn insert(&mut self, key: K) {
        if self.entries.len() == self.cache_size {
            self.entries.remove(0);
        }
        self.entries.push(key);
    }

    /// Evict all elements from the cache.
    pub fn evict_all(&mut self) {
        self.entries.clear();
    }
}
<commit_msg>Optimize LRUCache by using a VecDeque.<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/. */

//! A simple LRU cache.

#![deny(missing_docs)]

use std::collections::VecDeque;
use std::collections::vec_deque;

/// A LRU cache used to store a set of at most `n` elements at the same time.
///
/// The most-recently-used entry is at index zero.
pub struct LRUCache<K> {
    entries: VecDeque<K>,
    cache_size: usize,
}

/// A iterator over the items of the LRU cache.
pub type LRUCacheIterator<'a, K> = vec_deque::Iter<'a, K>;

/// A iterator over the mutable items of the LRU cache.
pub type LRUCacheMutIterator<'a, K> = vec_deque::IterMut<'a, K>;

impl<K: PartialEq> LRUCache<K> {
    /// Create a new LRU cache with `size` elements at most.
    pub fn new(size: usize) -> Self {
        LRUCache {
          entries: VecDeque::with_capacity(size),
          cache_size: size,
        }
    }

    /// Returns the number of elements in the cache.
    pub fn num_entries(&self) -> usize {
        self.entries.len()
    }

    #[inline]
    /// Touch a given entry, putting it first in the list.
    pub fn touch(&mut self, pos: usize) {
        let last_index = self.entries.len() - 1;
        if pos != last_index {
            let entry = self.entries.remove(pos).unwrap();
            self.entries.push_front(entry);
        }
    }

    /// Iterate over the contents of this cache, from more to less recently
    /// used.
    pub fn iter(&self) -> vec_deque::Iter<K> {
        self.entries.iter()
    }

    /// Iterate mutably over the contents of this cache.
    pub fn iter_mut(&mut self) -> vec_deque::IterMut<K> {
        self.entries.iter_mut()
    }

    /// Insert a given key in the cache.
    pub fn insert(&mut self, key: K) {
        if self.entries.len() == self.cache_size {
            self.entries.pop_back();
        }
        self.entries.push_front(key);
        debug_assert!(self.entries.len() <= self.cache_size);
    }

    /// Evict all elements from the cache.
    pub fn evict_all(&mut self) {
        self.entries.clear();
    }
}
<|endoftext|>


<commit_before>use moqt_core::{BaseClass1, DerivedClass1, DerivedClass2, AbstractBaseClass1, DerivedClass3};
use cpp_utils::*;

#[test]
fn casts() {
    unsafe {
        let mut derived = DerivedClass1::new();
        assert_eq!(derived.base_function(), 1);

        let mut base: Ptr<BaseClass1> = derived.static_upcast_mut();
        assert_eq!(base.base_function(), 2);

        let base_const: ConstPtr<BaseClass1> = derived.static_upcast();
        assert_eq!(base_const.base_const_function(), 2);

        let mut derived1: Ptr<DerivedClass1> = base.dynamic_cast_mut().unwrap();
        assert_eq!(derived1.base_function(), 3);

        let derived1: ConstPtr<DerivedClass1> = base.dynamic_cast().unwrap();
        assert_eq!(derived1.base_const_function(), 3);

        let derived2: Option<Ptr<DerivedClass2>> = base.dynamic_cast_mut();
        assert!(derived2.is_none());

        let mut derived1: Ptr<DerivedClass1> = base.static_downcast_mut();
        assert_eq!(derived1.base_function(), 4);

        let derived1: ConstPtr<DerivedClass1> = base.static_downcast();
        assert_eq!(derived1.base_const_function(), 4);
    }
}

#[test]
fn virtual_functions() {
    unsafe {
        let derived = DerivedClass1::new();
        assert_eq!(derived.virtual_function(), 43);

        let base: ConstPtr<BaseClass1> = derived.static_upcast();
        assert_eq!(base.virtual_function(), 43);

        let base = BaseClass1::new();
        assert_eq!(base.virtual_function(), 42);

        let derived = DerivedClass2::new();
        assert_eq!(derived.virtual_function(), 44);

        let base: ConstPtr<BaseClass1> = derived.static_upcast();
        assert_eq!(base.virtual_function(), 44);
    }
}

#[test]
fn pure_virtual_functions() {
    unsafe {
        let mut derived = DerivedClass3::new();
        assert_eq!(*derived.virtual_function(), 45);

        let mut base: Ptr<AbstractBaseClass1> = derived.static_upcast_mut();
        assert_eq!(*base.virtual_function(), 45);
    }
}<commit_msg>explicit CppBox in tests<commit_after>use moqt_core::{BaseClass1, DerivedClass1, DerivedClass2, AbstractBaseClass1, DerivedClass3};
use cpp_utils::*;

#[test]
fn casts() {
    unsafe {
        let mut derived: CppBox<DerivedClass1> = DerivedClass1::new();
        assert_eq!(derived.base_function(), 1);

        let mut base: Ptr<BaseClass1> = derived.static_upcast_mut();
        assert_eq!(base.base_function(), 2);

        let base_const: ConstPtr<BaseClass1> = derived.static_upcast();
        assert_eq!(base_const.base_const_function(), 2);

        let mut derived1: Ptr<DerivedClass1> = base.dynamic_cast_mut().unwrap();
        assert_eq!(derived1.base_function(), 3);

        let derived1: ConstPtr<DerivedClass1> = base.dynamic_cast().unwrap();
        assert_eq!(derived1.base_const_function(), 3);

        let derived2: Option<Ptr<DerivedClass2>> = base.dynamic_cast_mut();
        assert!(derived2.is_none());

        let mut derived1: Ptr<DerivedClass1> = base.static_downcast_mut();
        assert_eq!(derived1.base_function(), 4);

        let derived1: ConstPtr<DerivedClass1> = base.static_downcast();
        assert_eq!(derived1.base_const_function(), 4);
    }
}

#[test]
fn virtual_functions() {
    unsafe {
        let derived: CppBox<DerivedClass1> = DerivedClass1::new();
        assert_eq!(derived.virtual_function(), 43);

        let base: ConstPtr<BaseClass1> = derived.static_upcast();
        assert_eq!(base.virtual_function(), 43);

        let base: CppBox<BaseClass1> = BaseClass1::new();
        assert_eq!(base.virtual_function(), 42);

        let derived: CppBox<DerivedClass2> = DerivedClass2::new();
        assert_eq!(derived.virtual_function(), 44);

        let base: ConstPtr<BaseClass1> = derived.static_upcast();
        assert_eq!(base.virtual_function(), 44);
    }
}

#[test]
fn pure_virtual_functions() {
    unsafe {
        let mut derived: CppBox<DerivedClass3> = DerivedClass3::new();
        assert_eq!(*derived.virtual_function(), 45);

        let mut base: Ptr<AbstractBaseClass1> = derived.static_upcast_mut();
        assert_eq!(*base.virtual_function(), 45);
    }
}<|endoftext|>


<commit_before>//! TODO Fill in

use std::fmt::{self, Display, Formatter};
use std::default::Default;
use super::object;
use rlua::{self, Table, Lua, UserData, ToLua, Value, UserDataMethods, MetaMethod};
use rustwlc::input;

const INDEX_MISS_FUNCTION: &'static str = "__index_miss_function";
const NEWINDEX_MISS_FUNCTION: &'static str = "__newindex_miss_function";

#[derive(Clone, Debug)]
pub struct MouseState {
    // TODO Fill in
    dummy: i32
}

impl Default for MouseState {
    fn default() -> Self {
        MouseState {
            dummy: 0
        }
    }
}

impl Display for MouseState {
    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
        write!(f, "Mouse: {:p}", self)
    }
}

impl UserData for MouseState {
    fn add_methods(methods: &mut UserDataMethods<Self>) {
        methods.add_meta_function(MetaMethod::Index, object::default_index);
        methods.add_meta_function(MetaMethod::NewIndex, object::default_newindex);
    }
}

pub fn init(lua: &Lua) -> rlua::Result<()> {
    let mouse_table = lua.create_table()?;
    state_setup(lua, &mouse_table)?;
    meta_setup(lua, &mouse_table)?;
    method_setup(lua, &mouse_table)?;
    let globals = lua.globals();
    globals.set("mouse", mouse_table)
}

fn state_setup(lua: &Lua, mouse_table: &Table) -> rlua::Result<()> {
    mouse_table.set("__data", MouseState::default().to_lua(lua)?)
}

fn meta_setup(lua: &Lua, mouse_table: &Table) -> rlua::Result<()> {
    let meta_table = lua.create_table()?;
    meta_table.set("__tostring", lua.create_function(|_, val: Table| {
        Ok(format!("{}", val.get::<_, MouseState>("__data")?))
    })?)?;
    meta_table.set("__index", lua.create_function(index)?)?;
    mouse_table.set_metatable(Some(meta_table));
    Ok(())
}

fn method_setup(lua: &Lua, mouse_table: &Table) -> rlua::Result<()> {
    mouse_table.set("coords", lua.create_function(coords)?)?;
    mouse_table.set("set_index_miss_handler", lua.create_function(set_index_miss)?)?;
    mouse_table.set("set_newindex_miss_handler", lua.create_function(set_newindex_miss)?)?;
    Ok(())
}

fn coords<'lua>(lua: &'lua Lua, (coords, _ignore_enter): (rlua::Value<'lua>, rlua::Value<'lua>))
                -> rlua::Result<Table<'lua>> {
    match coords {
        rlua::Value::Table(coords) => {
            let (x, y) = (coords.get("x")?, coords.get("y")?);
            // TODO The ignore_enter is supposed to not send a send event to the client
            // That's not possible, at least until wlroots is complete.
            input::pointer::set_position_v2(x, y);
            Ok(coords)
        },
        _ => {
            // get the coords
            let coords = lua.create_table()?;
            let (x, y) = input::pointer::get_position_v2();
            coords.set("x", x as i32)?;
            coords.set("y", y as i32)?;
            // TODO It expects a table of what buttons were pressed.
            coords.set("buttons", lua.create_table()?)?;
            Ok(coords)
        }
    }
}

fn set_index_miss(lua: &Lua, func: rlua::Function) -> rlua::Result<()> {
    lua.globals().get::<_, Table>("button")?.set(INDEX_MISS_FUNCTION, func)
}

fn set_newindex_miss(lua: &Lua, func: rlua::Function) -> rlua::Result<()> {
    lua.globals().get::<_, Table>("button")?.set(NEWINDEX_MISS_FUNCTION, func)
}

fn index<'lua>(lua: &'lua Lua,
               (obj_table, index): (Table<'lua>, Value<'lua>))
               -> rlua::Result<Value<'lua>> {
    use rustwlc::WlcOutput;
    use super::screen::SCREENS_HANDLE;
    match index {
        Value::String(ref string) => {
            let string = string.to_str()?;
            if string != "screen" {
                // TODO call miss index handler if it exists
            }
            // TODO Might need a more robust way to get the current output...
            // E.g they look at where the cursor is, I don't think we need to do that.
            let index = WlcOutput::list().iter()
                .position(|&output| output == WlcOutput::focused())
                // NOTE Best to just lie because no one handles nil screens properly
                .unwrap_or(0);
            let screens = lua.globals().get::<_, Vec<Table>>(SCREENS_HANDLE)?;
            if index < screens.len() {
                return screens[index].clone().to_lua(lua)
            }
            // TODO Return screen even in bad case, see how awesome does it for maximal compatibility
        },
        _ => {}
    }
    let meta = obj_table.get_metatable().unwrap();
    meta.get(index)
}
<commit_msg>Missed an AnyUserData in mouse<commit_after>//! TODO Fill in

use std::fmt::{self, Display, Formatter};
use std::default::Default;
use super::object;
use rlua::{self, Table, Lua, UserData, ToLua, Value, UserDataMethods, MetaMethod, AnyUserData};
use rustwlc::input;

const INDEX_MISS_FUNCTION: &'static str = "__index_miss_function";
const NEWINDEX_MISS_FUNCTION: &'static str = "__newindex_miss_function";

#[derive(Clone, Debug)]
pub struct MouseState {
    // TODO Fill in
    dummy: i32
}

impl Default for MouseState {
    fn default() -> Self {
        MouseState {
            dummy: 0
        }
    }
}

impl Display for MouseState {
    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
        write!(f, "Mouse: {:p}", self)
    }
}

impl UserData for MouseState {
    fn add_methods(methods: &mut UserDataMethods<Self>) {
        methods.add_meta_function(MetaMethod::Index, object::default_index);
        methods.add_meta_function(MetaMethod::NewIndex, object::default_newindex);
    }
}

pub fn init(lua: &Lua) -> rlua::Result<()> {
    let mouse_table = lua.create_table()?;
    state_setup(lua, &mouse_table)?;
    meta_setup(lua, &mouse_table)?;
    method_setup(lua, &mouse_table)?;
    let globals = lua.globals();
    globals.set("mouse", mouse_table)
}

fn state_setup(lua: &Lua, mouse_table: &Table) -> rlua::Result<()> {
    mouse_table.set("__data", MouseState::default().to_lua(lua)?)
}

fn meta_setup(lua: &Lua, mouse_table: &Table) -> rlua::Result<()> {
    let meta_table = lua.create_table()?;
    meta_table.set("__tostring", lua.create_function(|_, val: Table| {
        Ok(format!("{}", val.get::<_, MouseState>("__data")?))
    })?)?;
    meta_table.set("__index", lua.create_function(index)?)?;
    mouse_table.set_metatable(Some(meta_table));
    Ok(())
}

fn method_setup(lua: &Lua, mouse_table: &Table) -> rlua::Result<()> {
    mouse_table.set("coords", lua.create_function(coords)?)?;
    mouse_table.set("set_index_miss_handler", lua.create_function(set_index_miss)?)?;
    mouse_table.set("set_newindex_miss_handler", lua.create_function(set_newindex_miss)?)?;
    Ok(())
}

fn coords<'lua>(lua: &'lua Lua, (coords, _ignore_enter): (rlua::Value<'lua>, rlua::Value<'lua>))
                -> rlua::Result<Table<'lua>> {
    match coords {
        rlua::Value::Table(coords) => {
            let (x, y) = (coords.get("x")?, coords.get("y")?);
            // TODO The ignore_enter is supposed to not send a send event to the client
            // That's not possible, at least until wlroots is complete.
            input::pointer::set_position_v2(x, y);
            Ok(coords)
        },
        _ => {
            // get the coords
            let coords = lua.create_table()?;
            let (x, y) = input::pointer::get_position_v2();
            coords.set("x", x as i32)?;
            coords.set("y", y as i32)?;
            // TODO It expects a table of what buttons were pressed.
            coords.set("buttons", lua.create_table()?)?;
            Ok(coords)
        }
    }
}

fn set_index_miss(lua: &Lua, func: rlua::Function) -> rlua::Result<()> {
    lua.globals().get::<_, Table>("button")?.set(INDEX_MISS_FUNCTION, func)
}

fn set_newindex_miss(lua: &Lua, func: rlua::Function) -> rlua::Result<()> {
    lua.globals().get::<_, Table>("button")?.set(NEWINDEX_MISS_FUNCTION, func)
}

fn index<'lua>(lua: &'lua Lua,
               (obj_table, index): (Table<'lua>, Value<'lua>))
               -> rlua::Result<Value<'lua>> {
    use rustwlc::WlcOutput;
    use super::screen::SCREENS_HANDLE;
    match index {
        Value::String(ref string) => {
            let string = string.to_str()?;
            if string != "screen" {
                // TODO call miss index handler if it exists
            }
            // TODO Might need a more robust way to get the current output...
            // E.g they look at where the cursor is, I don't think we need to do that.
            let index = WlcOutput::list().iter()
                .position(|&output| output == WlcOutput::focused())
                // NOTE Best to just lie because no one handles nil screens properly
                .unwrap_or(0);
            let screens = lua.globals().get::<_, Vec<AnyUserData>>(SCREENS_HANDLE)?;
            if index < screens.len() {
                return screens[index].clone().to_lua(lua)
            }
            // TODO Return screen even in bad case, see how awesome does it for maximal compatibility
        },
        _ => {}
    }
    let meta = obj_table.get_metatable().unwrap();
    meta.get(index)
}
<|endoftext|>