<commit_before>#![cfg(any(target_os = "linux", target_os = "dragonfly", target_os = "freebsd", target_os = "openbsd"))]

use {Api, ContextError, CreationError, GlAttributes, PixelFormat, PixelFormatRequirements};

use api::osmesa::OsMesaContext;
use wayland_client;
use winit;

mod wayland;
mod x11;

pub enum Context {
    X(x11::Context),
    Wayland(wayland::Context)
}

impl Context {
    #[inline]
    pub fn new(
        window_builder: winit::WindowBuilder,
        events_loop: &winit::EventsLoop,
        pf_reqs: &PixelFormatRequirements,
        gl_attr: &GlAttributes<&Context>,
    ) -> Result<(winit::Window, Self), CreationError>
    {
        match wayland_client::default_connect() {
            Ok(_) => {
                if let Some(&Context::X(_)) = gl_attr.sharing {
                    let msg = "Cannot share a wayland context with an X11 context";
                    return Err(CreationError::PlatformSpecific(msg.into()));
                }
                let gl_attr = gl_attr.clone().map_sharing(|ctxt| match ctxt {
                    &Context::X(_) => unreachable!(),
                    &Context::Wayland(ref ctxt) => ctxt,
                });
                wayland::Context::new(window_builder, events_loop, pf_reqs, &gl_attr)
                    .map(|(window, context)| (window, Context::Wayland(context)))
            },
            Err(_) => {
                if let Some(&Context::Wayland(_)) = gl_attr.sharing {
                    let msg = "Cannot share a X11 context with an wayland context";
                    return Err(CreationError::PlatformSpecific(msg.into()));
                }
                let gl_attr = gl_attr.clone().map_sharing(|ctxt| match ctxt {
                    &Context::Wayland(_) => unreachable!(),
                    &Context::X(ref ctxt) => ctxt,
                });
                x11::Context::new(window_builder, events_loop, pf_reqs, &gl_attr)
                    .map(|(window, context)| (window, Context::X(context)))
            }
        }
    }

    pub fn resize(&self, width: u32, height: u32) {
        match *self {
            Context::X(ref _ctxt) => (),
            Context::Wayland(ref ctxt) => ctxt.resize(width, height),
        }
    }

    #[inline]
    pub unsafe fn make_current(&self) -> Result<(), ContextError> {
        match *self {
            Context::X(ref ctxt) => ctxt.make_current(),
            Context::Wayland(ref ctxt) => ctxt.make_current()
        }
    }

    #[inline]
    pub fn is_current(&self) -> bool {
        match *self {
            Context::X(ref ctxt) => ctxt.is_current(),
            Context::Wayland(ref ctxt) => ctxt.is_current()
        }
    }

    #[inline]
    pub fn get_proc_address(&self, addr: &str) -> *const () {
        match *self {
            Context::X(ref ctxt) => ctxt.get_proc_address(addr),
            Context::Wayland(ref ctxt) => ctxt.get_proc_address(addr)
        }
    }

    #[inline]
    pub fn swap_buffers(&self) -> Result<(), ContextError> {
        match *self {
            Context::X(ref ctxt) => ctxt.swap_buffers(),
            Context::Wayland(ref ctxt) => ctxt.swap_buffers()
        }
    }

    #[inline]
    pub fn get_api(&self) -> ::Api {
        match *self {
            Context::X(ref ctxt) => ctxt.get_api(),
            Context::Wayland(ref ctxt) => ctxt.get_api()
        }
    }

    #[inline]
    pub fn get_pixel_format(&self) -> PixelFormat {
        match *self {
            Context::X(ref ctxt) => ctxt.get_pixel_format(),
            Context::Wayland(ref ctxt) => ctxt.get_pixel_format()
        }
    }
}

#[derive(Clone, Default)]
pub struct PlatformSpecificHeadlessBuilderAttributes;

pub struct HeadlessContext(OsMesaContext);

impl HeadlessContext {
    fn from(mesa: OsMesaContext) -> Self {
        HeadlessContext(mesa)
    }
}

impl HeadlessContext {
    pub fn new(dimensions: (u32, u32), pf_reqs: &PixelFormatRequirements,
               opengl: &GlAttributes<&HeadlessContext>,
               _: &PlatformSpecificHeadlessBuilderAttributes)
               -> Result<HeadlessContext, CreationError>
    {
        let opengl = opengl.clone().map_sharing(|c| &c.0);

        OsMesaContext::new(dimensions, pf_reqs, &opengl).map(HeadlessContext::from)
    }

    #[inline]
    pub unsafe fn make_current(&self) -> Result<(), ContextError> {
        self.0.make_current()
    }

    #[inline]
    pub fn is_current(&self) -> bool {
        self.0.is_current()
    }

    #[inline]
    pub fn get_proc_address(&self, addr: &str) -> *const () {
        self.0.get_proc_address(addr)
    }

    #[inline]
    pub fn swap_buffers(&self) -> Result<(), ContextError> {
        self.0.swap_buffers()
    }

    #[inline]
    pub fn get_api(&self) -> Api {
        self.0.get_api()
    }

    #[inline]
    pub fn get_pixel_format(&self) -> PixelFormat {
        self.0.get_pixel_format()
    }
}
<commit_msg>Add support for winit choice of XWayland<commit_after>#![cfg(any(target_os = "linux", target_os = "dragonfly", target_os = "freebsd", target_os = "openbsd"))]

use {Api, ContextError, CreationError, GlAttributes, PixelFormat, PixelFormatRequirements};

use api::osmesa::OsMesaContext;
use wayland_client;
use winit;

mod wayland;
mod x11;

pub enum Context {
    X(x11::Context),
    Wayland(wayland::Context)
}

impl Context {
    #[inline]
    pub fn new(
        window_builder: winit::WindowBuilder,
        events_loop: &winit::EventsLoop,
        pf_reqs: &PixelFormatRequirements,
        gl_attr: &GlAttributes<&Context>,
    ) -> Result<(winit::Window, Self), CreationError>
    {
        // winit allows use of XWayland, in which case will use an X11 backend
        // even if a wayland connection is available
        let use_wayland = winit::os::unix::get_x11_xconnection().is_none() &&
             wayland_client::default_connect().is_ok();

        if use_wayland {
            if let Some(&Context::X(_)) = gl_attr.sharing {
                let msg = "Cannot share a wayland context with an X11 context";
                return Err(CreationError::PlatformSpecific(msg.into()));
            }
            let gl_attr = gl_attr.clone().map_sharing(|ctxt| match ctxt {
                &Context::X(_) => unreachable!(),
                &Context::Wayland(ref ctxt) => ctxt,
            });
            wayland::Context::new(window_builder, events_loop, pf_reqs, &gl_attr)
                .map(|(window, context)| (window, Context::Wayland(context)))
        }
        else {
            if let Some(&Context::Wayland(_)) = gl_attr.sharing {
                let msg = "Cannot share a X11 context with an wayland context";
                return Err(CreationError::PlatformSpecific(msg.into()));
            }
            let gl_attr = gl_attr.clone().map_sharing(|ctxt| match ctxt {
                &Context::Wayland(_) => unreachable!(),
                &Context::X(ref ctxt) => ctxt,
            });
            x11::Context::new(window_builder, events_loop, pf_reqs, &gl_attr)
                .map(|(window, context)| (window, Context::X(context)))
        }
    }

    pub fn resize(&self, width: u32, height: u32) {
        match *self {
            Context::X(ref _ctxt) => (),
            Context::Wayland(ref ctxt) => ctxt.resize(width, height),
        }
    }

    #[inline]
    pub unsafe fn make_current(&self) -> Result<(), ContextError> {
        match *self {
            Context::X(ref ctxt) => ctxt.make_current(),
            Context::Wayland(ref ctxt) => ctxt.make_current()
        }
    }

    #[inline]
    pub fn is_current(&self) -> bool {
        match *self {
            Context::X(ref ctxt) => ctxt.is_current(),
            Context::Wayland(ref ctxt) => ctxt.is_current()
        }
    }

    #[inline]
    pub fn get_proc_address(&self, addr: &str) -> *const () {
        match *self {
            Context::X(ref ctxt) => ctxt.get_proc_address(addr),
            Context::Wayland(ref ctxt) => ctxt.get_proc_address(addr)
        }
    }

    #[inline]
    pub fn swap_buffers(&self) -> Result<(), ContextError> {
        match *self {
            Context::X(ref ctxt) => ctxt.swap_buffers(),
            Context::Wayland(ref ctxt) => ctxt.swap_buffers()
        }
    }

    #[inline]
    pub fn get_api(&self) -> ::Api {
        match *self {
            Context::X(ref ctxt) => ctxt.get_api(),
            Context::Wayland(ref ctxt) => ctxt.get_api()
        }
    }

    #[inline]
    pub fn get_pixel_format(&self) -> PixelFormat {
        match *self {
            Context::X(ref ctxt) => ctxt.get_pixel_format(),
            Context::Wayland(ref ctxt) => ctxt.get_pixel_format()
        }
    }
}

#[derive(Clone, Default)]
pub struct PlatformSpecificHeadlessBuilderAttributes;

pub struct HeadlessContext(OsMesaContext);

impl HeadlessContext {
    fn from(mesa: OsMesaContext) -> Self {
        HeadlessContext(mesa)
    }
}

impl HeadlessContext {
    pub fn new(dimensions: (u32, u32), pf_reqs: &PixelFormatRequirements,
               opengl: &GlAttributes<&HeadlessContext>,
               _: &PlatformSpecificHeadlessBuilderAttributes)
               -> Result<HeadlessContext, CreationError>
    {
        let opengl = opengl.clone().map_sharing(|c| &c.0);

        OsMesaContext::new(dimensions, pf_reqs, &opengl).map(HeadlessContext::from)
    }

    #[inline]
    pub unsafe fn make_current(&self) -> Result<(), ContextError> {
        self.0.make_current()
    }

    #[inline]
    pub fn is_current(&self) -> bool {
        self.0.is_current()
    }

    #[inline]
    pub fn get_proc_address(&self, addr: &str) -> *const () {
        self.0.get_proc_address(addr)
    }

    #[inline]
    pub fn swap_buffers(&self) -> Result<(), ContextError> {
        self.0.swap_buffers()
    }

    #[inline]
    pub fn get_api(&self) -> Api {
        self.0.get_api()
    }

    #[inline]
    pub fn get_pixel_format(&self) -> PixelFormat {
        self.0.get_pixel_format()
    }
}
<|endoftext|>


<commit_before>//! Create new `Streams` connected to external inputs.

use std::rc::Rc;
use std::cell::RefCell;
use std::default::Default;

use progress::frontier::{MutableAntichain, Antichain};
use progress::{Operate, Timestamp};
use progress::nested::subgraph::Source;
use progress::count_map::CountMap;
use progress::timestamp::RootTimestamp;
use progress::nested::product::Product;

use timely_communication::Allocate;
use {Data, Push};
use dataflow::channels::Content;
use dataflow::channels::pushers::{Tee, Counter};

use dataflow::{Stream, Scope};
use dataflow::scopes::{Child, Root};

// TODO : This is an exogenous input, but it would be nice to wrap a Subgraph in something
// TODO : more like a harness, with direct access to its inputs.

// NOTE : This only takes a &self, not a &mut self, which works but is a bit weird.
// NOTE : Experiments with &mut indicate that the borrow of 'a lives for too long.
// NOTE : Might be able to fix with another lifetime parameter, say 'c: 'a.

/// Create a new `Stream` and `Handle` through which to supply input.
pub trait Input<A: Allocate, T: Timestamp+Ord> {
    /// Create a new `Stream` and `Handle` through which to supply input.
    ///
    /// The `new_input` method returns a pair `(Handle, Stream)` where the `Stream` can be used
    /// immediately for timely dataflow construction, and the `Handle` is later used to introduce
    /// data into the timely dataflow computation.
    ///
    /// The `Handle` also provides a means to indicate
    /// to timely dataflow that the input has advanced beyond certain timestamps, allowing timely
    /// to issue progress notifications.
    ///
    /// #Examples
    /// ```
    /// use timely::*;
    /// use timely::dataflow::Scope;
    /// use timely::dataflow::operators::{Input, Inspect};
    ///
    /// // construct and execute a timely dataflow
    /// timely::execute(Configuration::Thread, |root| {
    ///
    ///     // add an input and base computation off of it
    ///     let mut input = root.scoped(|scope| {
    ///         let (input, stream) = scope.new_input();
    ///         stream.inspect(|x| println!("hello {:?}", x));
    ///         input
    ///     });
    ///
    ///     // introduce input, advance computation
    ///     for round in 0..10 {
    ///         input.send(round);
    ///         input.advance_to(round + 1);
    ///         root.step();
    ///     }
    /// });
    /// ```
    fn new_input<D:Data>(&mut self) -> (Handle<T, D>, Stream<Child<Root<A>, T>, D>);
}

impl<A: Allocate, T: Timestamp+Ord> Input<A, T> for Child<Root<A>, T> {
    fn new_input<D:Data>(&mut self) -> (Handle<T, D>, Stream<Child<Root<A>, T>, D>) {

        let (output, registrar) = Tee::<Product<RootTimestamp, T>, D>::new();
        let produced = Rc::new(RefCell::new(CountMap::new()));
        let helper = Handle::new(Counter::new(output, produced.clone()));
        let copies = self.peers();

        let index = self.add_operator(Operator {
            frontier: helper.frontier.clone(),
            progress: helper.progress.clone(),
            messages: produced.clone(),
            copies:   copies,
        });

        (helper, Stream::new(Source { index: index, port: 0 }, registrar, self.clone()))
    }
}

struct Operator<T:Timestamp+Ord> {
    frontier:   Rc<RefCell<MutableAntichain<Product<RootTimestamp, T>>>>,   // times available for sending
    progress:   Rc<RefCell<CountMap<Product<RootTimestamp, T>>>>,           // times closed since last asked
    messages:   Rc<RefCell<CountMap<Product<RootTimestamp, T>>>>,           // messages sent since last asked
    copies:     usize,
}

impl<T:Timestamp+Ord> Operate<Product<RootTimestamp, T>> for Operator<T> {
    fn name(&self) -> String { "Input".to_owned() }
    fn inputs(&self) -> usize { 0 }
    fn outputs(&self) -> usize { 1 }

    fn get_internal_summary(&mut self) -> (Vec<Vec<Antichain<<Product<RootTimestamp, T> as Timestamp>::Summary>>>,
                                           Vec<CountMap<Product<RootTimestamp, T>>>) {
        let mut map = CountMap::new();
        for x in self.frontier.borrow().elements().iter() {
            map.update(x, self.copies as i64);
        }
        (Vec::new(), vec![map])
    }

    fn pull_internal_progress(&mut self,_messages_consumed: &mut [CountMap<Product<RootTimestamp, T>>],
                                         frontier_progress: &mut [CountMap<Product<RootTimestamp, T>>],
                                         messages_produced: &mut [CountMap<Product<RootTimestamp, T>>]) -> bool
    {
        self.messages.borrow_mut().drain_into(&mut messages_produced[0]);
        self.progress.borrow_mut().drain_into(&mut frontier_progress[0]);
        false
    }

    fn notify_me(&self) -> bool { false }
}

/// A handle to an input `Stream`, used to introduce data to a timely dataflow computation.
pub struct Handle<T: Timestamp+Ord, D: Data> {
    frontier: Rc<RefCell<MutableAntichain<Product<RootTimestamp, T>>>>,   // times available for sending
    progress: Rc<RefCell<CountMap<Product<RootTimestamp, T>>>>,           // times closed since last asked
    pusher: Counter<Product<RootTimestamp, T>, D, Tee<Product<RootTimestamp, T>, D>>,
    buffer: Vec<D>,
    now_at: Product<RootTimestamp, T>,
}

// an input helper's state is either uninitialized, with now_at == None, or at some specific time.
// if now_at == None it has a hold on Default::default(), else it has a hold on the specific time.
// if now_at == None the pusher has not been opened, else it is open with the specific time.

impl<T:Timestamp+Ord, D: Data> Handle<T, D> {
    fn new(pusher: Counter<Product<RootTimestamp, T>, D, Tee<Product<RootTimestamp, T>, D>>) -> Handle<T, D> {
        Handle {
            frontier: Rc::new(RefCell::new(MutableAntichain::new_bottom(Default::default()))),
            progress: Rc::new(RefCell::new(CountMap::new())),
            pusher: pusher,
            buffer: Vec::with_capacity(Content::<D>::default_length()),
            now_at: Default::default(),
        }
    }

    // flushes any data we are sitting on. may need to initialize self.now_at if no one has yet.
    fn flush(&mut self) {
        Content::push_at(&mut self.buffer, self.now_at, &mut self.pusher);
    }

    // closes the current epoch, flushing if needed, shutting if needed, and updating the frontier.
    fn close_epoch(&mut self) {
        if !self.buffer.is_empty() { self.flush(); }
        self.pusher.done();
        self.frontier.borrow_mut().update_weight(&self.now_at, -1, &mut (*self.progress.borrow_mut()));
    }

    #[inline(always)]
    /// Sends one record into the corresponding timely dataflow `Stream`, at the current epoch.
    pub fn send(&mut self, data: D) {
        // assert!(self.buffer.capacity() == Content::<D>::default_length());
        self.buffer.push(data);
        if self.buffer.len() == self.buffer.capacity() {
            self.flush();
        }
    }

    /// Advances the current epoch to `next`.
    ///
    /// This method allows timely dataflow to issue progress notifications as it can now determine
    /// that this input can no longer produce data at earlier timestamps.
    pub fn advance_to(&mut self, next: T) {
        assert!(next > self.now_at.inner);
        self.close_epoch();
        self.now_at = RootTimestamp::new(next);
        self.frontier.borrow_mut().update_weight(&self.now_at,  1, &mut (*self.progress.borrow_mut()));
    }

    /// Closes the input.
    ///
    /// This method allows timely dataflow to issue all progress notifications blocked by this input
    /// and to begin to shut down operators, as this input can no longer produce data.
    pub fn close(self) { }

    /// Reports the current epoch.
    pub fn epoch(&mut self) -> &T {
        &self.now_at.inner
    }
}

impl<T:Timestamp+Ord, D: Data> Drop for Handle<T, D> {
    fn drop(&mut self) {
        self.close_epoch();
    }
}
<commit_msg>added time() method to access current timestamp<commit_after>//! Create new `Streams` connected to external inputs.

use std::rc::Rc;
use std::cell::RefCell;
use std::default::Default;

use progress::frontier::{MutableAntichain, Antichain};
use progress::{Operate, Timestamp};
use progress::nested::subgraph::Source;
use progress::count_map::CountMap;
use progress::timestamp::RootTimestamp;
use progress::nested::product::Product;

use timely_communication::Allocate;
use {Data, Push};
use dataflow::channels::Content;
use dataflow::channels::pushers::{Tee, Counter};

use dataflow::{Stream, Scope};
use dataflow::scopes::{Child, Root};

// TODO : This is an exogenous input, but it would be nice to wrap a Subgraph in something
// TODO : more like a harness, with direct access to its inputs.

// NOTE : This only takes a &self, not a &mut self, which works but is a bit weird.
// NOTE : Experiments with &mut indicate that the borrow of 'a lives for too long.
// NOTE : Might be able to fix with another lifetime parameter, say 'c: 'a.

/// Create a new `Stream` and `Handle` through which to supply input.
pub trait Input<A: Allocate, T: Timestamp+Ord> {
    /// Create a new `Stream` and `Handle` through which to supply input.
    ///
    /// The `new_input` method returns a pair `(Handle, Stream)` where the `Stream` can be used
    /// immediately for timely dataflow construction, and the `Handle` is later used to introduce
    /// data into the timely dataflow computation.
    ///
    /// The `Handle` also provides a means to indicate
    /// to timely dataflow that the input has advanced beyond certain timestamps, allowing timely
    /// to issue progress notifications.
    ///
    /// #Examples
    /// ```
    /// use timely::*;
    /// use timely::dataflow::Scope;
    /// use timely::dataflow::operators::{Input, Inspect};
    ///
    /// // construct and execute a timely dataflow
    /// timely::execute(Configuration::Thread, |root| {
    ///
    ///     // add an input and base computation off of it
    ///     let mut input = root.scoped(|scope| {
    ///         let (input, stream) = scope.new_input();
    ///         stream.inspect(|x| println!("hello {:?}", x));
    ///         input
    ///     });
    ///
    ///     // introduce input, advance computation
    ///     for round in 0..10 {
    ///         input.send(round);
    ///         input.advance_to(round + 1);
    ///         root.step();
    ///     }
    /// });
    /// ```
    fn new_input<D:Data>(&mut self) -> (Handle<T, D>, Stream<Child<Root<A>, T>, D>);
}

impl<A: Allocate, T: Timestamp+Ord> Input<A, T> for Child<Root<A>, T> {
    fn new_input<D:Data>(&mut self) -> (Handle<T, D>, Stream<Child<Root<A>, T>, D>) {

        let (output, registrar) = Tee::<Product<RootTimestamp, T>, D>::new();
        let produced = Rc::new(RefCell::new(CountMap::new()));
        let helper = Handle::new(Counter::new(output, produced.clone()));
        let copies = self.peers();

        let index = self.add_operator(Operator {
            frontier: helper.frontier.clone(),
            progress: helper.progress.clone(),
            messages: produced.clone(),
            copies:   copies,
        });

        (helper, Stream::new(Source { index: index, port: 0 }, registrar, self.clone()))
    }
}

struct Operator<T:Timestamp+Ord> {
    frontier:   Rc<RefCell<MutableAntichain<Product<RootTimestamp, T>>>>,   // times available for sending
    progress:   Rc<RefCell<CountMap<Product<RootTimestamp, T>>>>,           // times closed since last asked
    messages:   Rc<RefCell<CountMap<Product<RootTimestamp, T>>>>,           // messages sent since last asked
    copies:     usize,
}

impl<T:Timestamp+Ord> Operate<Product<RootTimestamp, T>> for Operator<T> {
    fn name(&self) -> String { "Input".to_owned() }
    fn inputs(&self) -> usize { 0 }
    fn outputs(&self) -> usize { 1 }

    fn get_internal_summary(&mut self) -> (Vec<Vec<Antichain<<Product<RootTimestamp, T> as Timestamp>::Summary>>>,
                                           Vec<CountMap<Product<RootTimestamp, T>>>) {
        let mut map = CountMap::new();
        for x in self.frontier.borrow().elements().iter() {
            map.update(x, self.copies as i64);
        }
        (Vec::new(), vec![map])
    }

    fn pull_internal_progress(&mut self,_messages_consumed: &mut [CountMap<Product<RootTimestamp, T>>],
                                         frontier_progress: &mut [CountMap<Product<RootTimestamp, T>>],
                                         messages_produced: &mut [CountMap<Product<RootTimestamp, T>>]) -> bool
    {
        self.messages.borrow_mut().drain_into(&mut messages_produced[0]);
        self.progress.borrow_mut().drain_into(&mut frontier_progress[0]);
        false
    }

    fn notify_me(&self) -> bool { false }
}

/// A handle to an input `Stream`, used to introduce data to a timely dataflow computation.
pub struct Handle<T: Timestamp+Ord, D: Data> {
    frontier: Rc<RefCell<MutableAntichain<Product<RootTimestamp, T>>>>,   // times available for sending
    progress: Rc<RefCell<CountMap<Product<RootTimestamp, T>>>>,           // times closed since last asked
    pusher: Counter<Product<RootTimestamp, T>, D, Tee<Product<RootTimestamp, T>, D>>,
    buffer: Vec<D>,
    now_at: Product<RootTimestamp, T>,
}

// an input helper's state is either uninitialized, with now_at == None, or at some specific time.
// if now_at == None it has a hold on Default::default(), else it has a hold on the specific time.
// if now_at == None the pusher has not been opened, else it is open with the specific time.

impl<T:Timestamp+Ord, D: Data> Handle<T, D> {
    fn new(pusher: Counter<Product<RootTimestamp, T>, D, Tee<Product<RootTimestamp, T>, D>>) -> Handle<T, D> {
        Handle {
            frontier: Rc::new(RefCell::new(MutableAntichain::new_bottom(Default::default()))),
            progress: Rc::new(RefCell::new(CountMap::new())),
            pusher: pusher,
            buffer: Vec::with_capacity(Content::<D>::default_length()),
            now_at: Default::default(),
        }
    }

    // flushes any data we are sitting on. may need to initialize self.now_at if no one has yet.
    fn flush(&mut self) {
        Content::push_at(&mut self.buffer, self.now_at, &mut self.pusher);
    }

    // closes the current epoch, flushing if needed, shutting if needed, and updating the frontier.
    fn close_epoch(&mut self) {
        if !self.buffer.is_empty() { self.flush(); }
        self.pusher.done();
        self.frontier.borrow_mut().update_weight(&self.now_at, -1, &mut (*self.progress.borrow_mut()));
    }

    #[inline(always)]
    /// Sends one record into the corresponding timely dataflow `Stream`, at the current epoch.
    pub fn send(&mut self, data: D) {
        // assert!(self.buffer.capacity() == Content::<D>::default_length());
        self.buffer.push(data);
        if self.buffer.len() == self.buffer.capacity() {
            self.flush();
        }
    }

    /// Advances the current epoch to `next`.
    ///
    /// This method allows timely dataflow to issue progress notifications as it can now determine
    /// that this input can no longer produce data at earlier timestamps.
    pub fn advance_to(&mut self, next: T) {
        assert!(next > self.now_at.inner);
        self.close_epoch();
        self.now_at = RootTimestamp::new(next);
        self.frontier.borrow_mut().update_weight(&self.now_at,  1, &mut (*self.progress.borrow_mut()));
    }

    /// Closes the input.
    ///
    /// This method allows timely dataflow to issue all progress notifications blocked by this input
    /// and to begin to shut down operators, as this input can no longer produce data.
    pub fn close(self) { }

    /// Reports the current epoch.
    pub fn epoch(&self) -> &T {
        &self.now_at.inner
    }

    /// Reports the current timestamp.
    pub fn time(&self) -> &Product<RootTimestamp, T> {
        &self.now_at
    }
}

impl<T:Timestamp+Ord, D: Data> Drop for Handle<T, D> {
    fn drop(&mut self) {
        self.close_epoch();
    }
}
<|endoftext|>


<commit_before>// This is actually a test that runs on the HOST (!). I had to hack things around quite a bit to
// make this work; that's way this ended up in this directory :-).

extern crate f3;

use f3::peripheral;

macro_rules! offset {
    ($register:expr, $offset:expr) => {
        if $offset != &$register as *const _ as usize {
            panic!("{}: expected 0x{:x}, got 0x{:x}. Off by {}",
                   stringify!($register), $offset, &$register as *const _ as usize,
                   (&$register as *const _ as isize - $offset).abs())
        }
    }
}

fn main() {
    let dbgmcu = unsafe { &*(0x0 as *const peripheral::dbgmcu::Dbgmcu) };

    offset!(dbgmcu.idcode, 0x0);
    offset!(dbgmcu.cr, 0x4);
    offset!(dbgmcu.apb1fz, 0x8);
    offset!(dbgmcu.apb2fz, 0xc);

    let gpio = unsafe { &*(0x0 as *const peripheral::gpio::Gpio) };

    offset!(gpio.moder, 0x0);
    offset!(gpio.otyper, 0x4);
    offset!(gpio.ospeedr, 0x8);
    offset!(gpio.pupdr, 0xc);
    offset!(gpio.idr, 0x10);
    offset!(gpio.odr, 0x14);
    offset!(gpio.bsrr, 0x18);
    offset!(gpio.lckr, 0x1c);
    offset!(gpio.afrl, 0x20);
    offset!(gpio.afrh, 0x24);
    offset!(gpio.brr, 0x28);

    let i2c = unsafe { &*(0x0 as *const peripheral::i2c::I2C) };

    offset!(i2c.cr1, 0x0);
    offset!(i2c.cr2, 0x4);
    offset!(i2c.oar1, 0x8);
    offset!(i2c.oar2, 0xc);
    offset!(i2c.timingr, 0x10);
    offset!(i2c.timeoutr, 0x14);
    offset!(i2c.isr, 0x18);
    offset!(i2c.icr, 0x1c);
    offset!(i2c.pecr, 0x20);
    offset!(i2c.rxdr, 0x24);
    offset!(i2c.txdr, 0x28);

    let rcc = unsafe { &*(0x0 as *const peripheral::rcc::Rcc) };

    offset!(rcc.cr, 0x0);
    offset!(rcc.cfgr, 0x4);
    offset!(rcc.cir, 0x8);
    offset!(rcc.apb2rstr, 0xc);
    offset!(rcc.apb1rstr, 0x10);
    offset!(rcc.ahbenr, 0x14);
    offset!(rcc.apb2enr, 0x18);
    offset!(rcc.apb1enr, 0x1c);
    offset!(rcc.bdcr, 0x20);
    offset!(rcc.csr, 0x24);
    offset!(rcc.ahbrstr, 0x28);
    offset!(rcc.cfgr2, 0x2c);
    offset!(rcc.cfgr3, 0x30);

    let tim = unsafe { &*(0x0 as *const peripheral::tim::Tim) };

    offset!(tim.cr1, 0x0);
    offset!(tim.cr2, 0x4);
    offset!(tim.dier, 0xc);
    offset!(tim.sr, 0x10);
    offset!(tim.egr, 0x14);
    offset!(tim.cnt, 0x24);
    offset!(tim.psc, 0x28);
    offset!(tim.arr, 0x2c);

    let usart = unsafe { &*(0x0 as *const peripheral::usart::Usart) };

    offset!(usart.cr1, 0x0);
    offset!(usart.cr2, 0x4);
    offset!(usart.cr3, 0x8);
    offset!(usart.brr, 0xc);
    offset!(usart.gtpr, 0x10);
    offset!(usart.rtor, 0x14);
    offset!(usart.rqr, 0x18);
    offset!(usart.isr, 0x1c);
    offset!(usart.icr, 0x20);
    offset!(usart.rdr, 0x24);
    offset!(usart.tdr, 0x28);
}
<commit_msg>fix typo in examples/_test.rs<commit_after>// This is actually a test that runs on the HOST (!). I had to hack things around quite a bit to
// make this work; that's way this ended up in this directory :-).

extern crate f3;

use f3::peripheral;

macro_rules! offset {
    ($register:expr, $offset:expr) => {
        if $offset != &$register as *const _ as usize {
            panic!("{}: expected 0x{:x}, got 0x{:x}. Off by {}",
                   stringify!($register), $offset, &$register as *const _ as usize,
                   (&$register as *const _ as isize - $offset).abs())
        }
    }
}

fn main() {
    let dbgmcu = unsafe { &*(0x0 as *const peripheral::dbgmcu::Dbgmcu) };

    offset!(dbgmcu.idcode, 0x0);
    offset!(dbgmcu.cr, 0x4);
    offset!(dbgmcu.apb1fz, 0x8);
    offset!(dbgmcu.apb2fz, 0xc);

    let gpio = unsafe { &*(0x0 as *const peripheral::gpio::Gpio) };

    offset!(gpio.moder, 0x0);
    offset!(gpio.otyper, 0x4);
    offset!(gpio.ospeedr, 0x8);
    offset!(gpio.pupdr, 0xc);
    offset!(gpio.idr, 0x10);
    offset!(gpio.odr, 0x14);
    offset!(gpio.bsrr, 0x18);
    offset!(gpio.lckr, 0x1c);
    offset!(gpio.afrl, 0x20);
    offset!(gpio.afrh, 0x24);
    offset!(gpio.brr, 0x28);

    let i2c = unsafe { &*(0x0 as *const peripheral::i2c::I2c) };

    offset!(i2c.cr1, 0x0);
    offset!(i2c.cr2, 0x4);
    offset!(i2c.oar1, 0x8);
    offset!(i2c.oar2, 0xc);
    offset!(i2c.timingr, 0x10);
    offset!(i2c.timeoutr, 0x14);
    offset!(i2c.isr, 0x18);
    offset!(i2c.icr, 0x1c);
    offset!(i2c.pecr, 0x20);
    offset!(i2c.rxdr, 0x24);
    offset!(i2c.txdr, 0x28);

    let rcc = unsafe { &*(0x0 as *const peripheral::rcc::Rcc) };

    offset!(rcc.cr, 0x0);
    offset!(rcc.cfgr, 0x4);
    offset!(rcc.cir, 0x8);
    offset!(rcc.apb2rstr, 0xc);
    offset!(rcc.apb1rstr, 0x10);
    offset!(rcc.ahbenr, 0x14);
    offset!(rcc.apb2enr, 0x18);
    offset!(rcc.apb1enr, 0x1c);
    offset!(rcc.bdcr, 0x20);
    offset!(rcc.csr, 0x24);
    offset!(rcc.ahbrstr, 0x28);
    offset!(rcc.cfgr2, 0x2c);
    offset!(rcc.cfgr3, 0x30);

    let tim = unsafe { &*(0x0 as *const peripheral::tim::Tim) };

    offset!(tim.cr1, 0x0);
    offset!(tim.cr2, 0x4);
    offset!(tim.dier, 0xc);
    offset!(tim.sr, 0x10);
    offset!(tim.egr, 0x14);
    offset!(tim.cnt, 0x24);
    offset!(tim.psc, 0x28);
    offset!(tim.arr, 0x2c);

    let usart = unsafe { &*(0x0 as *const peripheral::usart::Usart) };

    offset!(usart.cr1, 0x0);
    offset!(usart.cr2, 0x4);
    offset!(usart.cr3, 0x8);
    offset!(usart.brr, 0xc);
    offset!(usart.gtpr, 0x10);
    offset!(usart.rtor, 0x14);
    offset!(usart.rqr, 0x18);
    offset!(usart.isr, 0x1c);
    offset!(usart.icr, 0x20);
    offset!(usart.rdr, 0x24);
    offset!(usart.tdr, 0x28);
}
<|endoftext|>


<commit_before>// Copyright 2012 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.

/*!

Module that constructs a control-flow graph representing an item.
Uses `Graph` as the underlying representation.

*/

use middle::graph;
use middle::ty;
use middle::typeck;
use syntax::ast;
use util::nodemap::NodeMap;

mod construct;

pub struct CFG {
    exit_map: NodeMap<CFGIndex>,
    graph: CFGGraph,
    entry: CFGIndex,
    exit: CFGIndex,
}

pub struct CFGNodeData {
    id: ast::NodeId
}

pub struct CFGEdgeData {
    exiting_scopes: Vec<ast::NodeId>
}

pub type CFGIndex = graph::NodeIndex;

pub type CFGGraph = graph::Graph<CFGNodeData, CFGEdgeData>;

pub type CFGNode = graph::Node<CFGNodeData>;

pub type CFGEdge = graph::Edge<CFGEdgeData>;

pub struct CFGIndices {
    entry: CFGIndex,
    exit: CFGIndex,
}

impl CFG {
    pub fn new(tcx: &ty::ctxt,
               method_map: typeck::MethodMap,
               blk: &ast::Block) -> CFG {
        construct::construct(tcx, method_map, blk)
    }
}
<commit_msg>middle: cfg: allow dead code<commit_after>// Copyright 2012 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.

/*!

Module that constructs a control-flow graph representing an item.
Uses `Graph` as the underlying representation.

*/

#![allow(dead_code)] // still a WIP, #6298

use middle::graph;
use middle::ty;
use middle::typeck;
use syntax::ast;
use util::nodemap::NodeMap;

mod construct;

pub struct CFG {
    exit_map: NodeMap<CFGIndex>,
    graph: CFGGraph,
    entry: CFGIndex,
    exit: CFGIndex,
}

pub struct CFGNodeData {
    id: ast::NodeId
}

pub struct CFGEdgeData {
    exiting_scopes: Vec<ast::NodeId>
}

pub type CFGIndex = graph::NodeIndex;

pub type CFGGraph = graph::Graph<CFGNodeData, CFGEdgeData>;

pub type CFGNode = graph::Node<CFGNodeData>;

pub type CFGEdge = graph::Edge<CFGEdgeData>;

pub struct CFGIndices {
    entry: CFGIndex,
    exit: CFGIndex,
}

impl CFG {
    pub fn new(tcx: &ty::ctxt,
               method_map: typeck::MethodMap,
               blk: &ast::Block) -> CFG {
        construct::construct(tcx, method_map, blk)
    }
}
<|endoftext|>


<commit_before>use super::scope::{CowScope};
use super::CompileError;
use super::parser::{Parser, TokenStream};
use super::expr::Expression;
use super::function::Function;
use super::lexer::{Token, Symbol};
use super::identifier::{Identifier, IdMap};
use std::collections::VecMap;
use std::borrow::Cow;

/// Represents a function call written in synthizer
#[derive(Show)]
pub struct FunctionCall {
	pub func: Identifier, // the function the call refers to as a scope id
	args: VecMap<Expression>,
}
impl<'a> Parser<'a> for FunctionCall {
	/// Parse a function call from a token stream. Scope is used to find function definitions
	fn parse(tokens: TokenStream<'a>, scope: CowScope<'a>) -> Result<FunctionCall, CompileError> {
		let mut tokens = tokens;
		let mut args = VecMap::new();

		// Opening bracket
		try!(expect!(tokens.next(), Token::Symbol(Symbol::LeftBracket), "expected `[`, got `{}`"));

		// Function name
		let fn_ident = try!(expect_value!(tokens.next(),
			Token::Ident, "expected function name, got `{}`"));

		// Parse arguments
		'outer: loop {
			let token = tokens.next();
			if let Ok(_) = expect!(token, Token::Symbol(Symbol::RightParen)) {
				// Got closing paren, end of list
				break;
			} else {
				// Argument name
				let arg_ident = try!(expect_value!(token, Token::Ident, "expected `)` or argument name, got `{}`"));

				// Equals
				try!(expect!(tokens.next(), Token::Symbol(Symbol::Equals), "expected `=`, got `{}`"));

				// Mark the position of the start of the expression so we can later extract a slice
				let expr_start = tokens.pos();

				loop {
					let token = tokens.next();

					// Adds all the tokens we have scanned so far in the inner loop to the args
					// list
					let mut write_arg = |&mut:| -> Result<(), CompileError> {
						let slice = tokens.slice(expr_start, tokens.pos() - 1);
						let expr = try!(Parser::parse(slice, scope.clone()));
						match args.get(&arg_ident) {
							Some(_) => {
								return Err(CompileError::new(format!("argument {} has already been defined", arg_ident)));
							}
							None => {
								args.insert(arg_ident, expr);
							}
						}
						Ok(())
					};

					match token.map(|x| x.token) {
						// Advance to next argument
						Some(Token::Symbol(Symbol::Comma)) => {
							try!(write_arg());
							break;
						}

						// End of function call
						Some(Token::Symbol(Symbol::RightBracket)) => {
							try!(write_arg());
							break 'outer;
						}

						// We need to handle nested parens so we can include parens in the argument
						// expressions
						Some(Token::Symbol(Symbol::LeftBracket)) => {
							//TODO borrowing issues with the closure above, need to rewrite it out.
							//tokens = try!(parser::match_paren(tokens, Token::Symbol(Symbol::LeftBracket), Token::Symbol(Symbol::RightBracket)));
						}

						None => {
							return Err(CompileError::new_static("Expected expression, got EOF"));
						}

						_ => { }
					}
				}
			}
		}

		Ok(FunctionCall {
			func: fn_ident,
			args: args,
		})
	}
}

impl Function for FunctionCall {
	fn call(&self, scope: CowScope, idmap: &IdMap) -> Result<f32, CompileError> {
		let mut inner = scope.clone().into_owned();
		match scope.get_func(self.func) {
			Some(f) => {
				for (n, a) in self.args.iter() {
					inner.set_var(n, try!(a.call(scope.clone(), idmap)));
				}
				f.call(Cow::Owned(inner), idmap)
			}
			None => panic!("internal error: function id is invalid!"),
		}
	}
}
<commit_msg>One thing that wasn't updated with the rest of the syntax changes<commit_after>use super::scope::{CowScope};
use super::CompileError;
use super::parser::{Parser, TokenStream};
use super::expr::Expression;
use super::function::Function;
use super::lexer::{Token, Symbol};
use super::identifier::{Identifier, IdMap};
use std::collections::VecMap;
use std::borrow::Cow;

/// Represents a function call written in synthizer
#[derive(Show)]
pub struct FunctionCall {
	pub func: Identifier, // the function the call refers to as a scope id
	args: VecMap<Expression>,
}
impl<'a> Parser<'a> for FunctionCall {
	/// Parse a function call from a token stream. Scope is used to find function definitions
	fn parse(tokens: TokenStream<'a>, scope: CowScope<'a>) -> Result<FunctionCall, CompileError> {
		let mut tokens = tokens;
		let mut args = VecMap::new();

		// Opening bracket
		try!(expect!(tokens.next(), Token::Symbol(Symbol::LeftBracket), "expected `[`, got `{}`"));

		// Function name
		let fn_ident = try!(expect_value!(tokens.next(),
			Token::Ident, "expected function name, got `{}`"));

		// Parse arguments
		'outer: loop {
			let token = tokens.next();
			if let Ok(_) = expect!(token, Token::Symbol(Symbol::RightBracket)) {
				// Got closing paren, end of list
				break;
			} else {
				// Argument name
				let arg_ident = try!(expect_value!(token, Token::Ident, "expected `]` or argument name, got `{}`"));

				// Equals
				try!(expect!(tokens.next(), Token::Symbol(Symbol::Equals), "expected `=`, got `{}`"));

				// Mark the position of the start of the expression so we can later extract a slice
				let expr_start = tokens.pos();

				loop {
					let token = tokens.next();

					// Adds all the tokens we have scanned so far in the inner loop to the args
					// list
					let mut write_arg = |&mut:| -> Result<(), CompileError> {
						let slice = tokens.slice(expr_start, tokens.pos() - 1);
						let expr = try!(Parser::parse(slice, scope.clone()));
						match args.get(&arg_ident) {
							Some(_) => {
								return Err(CompileError::new(format!("argument {} has already been defined", arg_ident)));
							}
							None => {
								args.insert(arg_ident, expr);
							}
						}
						Ok(())
					};

					match token.map(|x| x.token) {
						// Advance to next argument
						Some(Token::Symbol(Symbol::Comma)) => {
							try!(write_arg());
							break;
						}

						// End of function call
						Some(Token::Symbol(Symbol::RightBracket)) => {
							try!(write_arg());
							break 'outer;
						}

						// We need to handle nested parens so we can include parens in the argument
						// expressions
						Some(Token::Symbol(Symbol::LeftBracket)) => {
							//TODO borrowing issues with the closure above, need to rewrite it out.
							//tokens = try!(parser::match_paren(tokens, Token::Symbol(Symbol::LeftBracket), Token::Symbol(Symbol::RightBracket)));
						}

						None => {
							return Err(CompileError::new_static("Expected expression, got EOF"));
						}

						_ => { }
					}
				}
			}
		}

		Ok(FunctionCall {
			func: fn_ident,
			args: args,
		})
	}
}

impl Function for FunctionCall {
	fn call(&self, scope: CowScope, idmap: &IdMap) -> Result<f32, CompileError> {
		let mut inner = scope.clone().into_owned();
		match scope.get_func(self.func) {
			Some(f) => {
				for (n, a) in self.args.iter() {
					inner.set_var(n, try!(a.call(scope.clone(), idmap)));
				}
				f.call(Cow::Owned(inner), idmap)
			}
			None => panic!("internal error: function id is invalid!"),
		}
	}
}
<|endoftext|>


<commit_before>/*
Copyright (c) 2016-2017, Robert Ou <rqou@robertou.com>
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

1. Redistributions of source code must retain the above copyright notice,
   this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
   this list of conditions and the following disclaimer in the documentation
   and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

use std::hash::{Hash, Hasher};

use analyzer::objpools::*;
use analyzer::util::*;

#[derive(Copy, Clone, Eq, Debug)]
pub struct Identifier {
    pub orig_name: StringPoolIndexLatin1,
    pub canonical_name: StringPoolIndexLatin1,
    pub is_extended_id: bool,
}

impl PartialEq for Identifier {
    fn eq(&self, other: &Identifier) -> bool {
        (self.is_extended_id == other.is_extended_id) &&
        (self.canonical_name == other.canonical_name)
    }
}

impl Hash for Identifier {
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.canonical_name.hash(state);
        self.is_extended_id.hash(state);
    }
}

impl Identifier {
    pub fn new_latin1(
        sp: &mut StringPool, name: StringPoolIndexLatin1, ext: bool)
        -> Result<Identifier, &'static str> {

        let canonical_name_vec = {
            // Borrow the name because we're going to need to look at it
            let name_ = sp.retrieve_latin1_str(name);

            // Validation
            if ext && !name_.valid_for_ext_id() {
                return Err("name is unacceptable as an identifier");
            }
            if !ext && !name_.valid_for_basic_id() {
                return Err("name is unacceptable as an identifier");
            }

            // Possibly lowercase canonical name for basic identifiers
            if ext {
                None
            } else {
                let mut lcase_name = Vec::<u8>::new();
                for c in name_.raw_name() {
                    lcase_name.push(LATIN1_LCASE_TABLE[*c as usize]);
                }
                Some(lcase_name)
            }
        };

        // We needed to make name_ out of scope before we can actually try
        // to add the new canonical name
        let mut canonical_name = name;
        if let Some(lcase_name) = canonical_name_vec {
            canonical_name = sp.add_latin1_str(&lcase_name);
        }

        Ok(Identifier {
            orig_name: name,
            canonical_name: canonical_name,
            is_extended_id: ext,
        })
    }

    pub fn new_unicode(sp: &mut StringPool, name: &str, ext: bool)
        -> Result<Identifier, &'static str> {

        let mut latin1_name = Vec::<u8>::new();
        for c in name.chars() {
            if c >= '\u{0100}' {
                return Err("name contains characters outside Latin-1 range");
            }

            latin1_name.push(c as u8);
        }

        let sp_idx = sp.add_latin1_str(&latin1_name);
        Identifier::new_latin1(sp, sp_idx, ext)
    }

    pub fn debug_print(&self, sp: &StringPool) -> String {
        if self.is_extended_id {
            format!("\"\\\\{}\\\\\"", sp.retrieve_latin1_str(
                self.orig_name).debug_escaped_name())
        } else {
            format!("\"{}\"", sp.retrieve_latin1_str(
                self.orig_name).debug_escaped_name())
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::hash::SipHasher;

    #[test]
    fn identifier_basic() {
        let mut sp = StringPool::new();

        let sp_idx = sp.add_latin1_str(b"foo");
        let test1 = Identifier::new_latin1(&mut sp, sp_idx, false).unwrap();
        assert_eq!(sp.retrieve_latin1_str(
            test1.orig_name).raw_name(), b"foo");
        assert_eq!(sp.retrieve_latin1_str(
            test1.canonical_name).raw_name(), b"foo");
        assert_eq!(sp.retrieve_latin1_str(
            test1.orig_name).pretty_name(), "foo");
        assert!(!test1.is_extended_id);

        let sp_idx = sp.add_latin1_str(b"FoO");
        let test2 = Identifier::new_latin1(&mut sp, sp_idx, false).unwrap();
        assert_eq!(sp.retrieve_latin1_str(
            test2.orig_name).raw_name(), b"FoO");
        assert_eq!(sp.retrieve_latin1_str(
            test2.canonical_name).raw_name(), b"foo");
        assert_eq!(sp.retrieve_latin1_str(
            test2.orig_name).pretty_name(), "FoO");
        assert!(!test2.is_extended_id);

        let sp_idx = sp.add_latin1_str(b"foo_");
        let test3 = Identifier::new_latin1(&mut sp, sp_idx, false);
        assert!(test3.is_err());

        let sp_idx = sp.add_latin1_str(b"FoO");
        let test4 = Identifier::new_latin1(&mut sp, sp_idx, true).unwrap();
        assert_eq!(sp.retrieve_latin1_str(
            test4.orig_name).raw_name(), b"FoO");
        assert_eq!(sp.retrieve_latin1_str(
            test4.canonical_name).raw_name(), b"FoO");
        assert_eq!(sp.retrieve_latin1_str(
            test4.orig_name).pretty_name(), "FoO");
        assert!(test4.is_extended_id);
    }

    #[test]
    fn identifier_latin1_unusual() {
        let mut sp = StringPool::new();

        let sp_idx = sp.add_latin1_str(b"f\xD6o");
        let test1 = Identifier::new_latin1(&mut sp, sp_idx, false).unwrap();
        assert_eq!(sp.retrieve_latin1_str(
            test1.orig_name).raw_name(), b"f\xD6o");
        assert_eq!(sp.retrieve_latin1_str(
            test1.canonical_name).raw_name(), b"f\xF6o");
        assert_eq!(sp.retrieve_latin1_str(
            test1.orig_name).pretty_name(), "fÖo");
        assert!(!test1.is_extended_id);

        let sp_idx = sp.add_latin1_str(b"foo\xD7");
        let test2 = Identifier::new_latin1(&mut sp, sp_idx, false);
        assert!(test2.is_err());

        let sp_idx = sp.add_latin1_str(b"f\xD6o\xD7\xBC");
        let test3 = Identifier::new_latin1(&mut sp, sp_idx, true).unwrap();
        assert_eq!(sp.retrieve_latin1_str(
            test3.orig_name).raw_name(), b"f\xD6o\xD7\xBC");
        assert_eq!(sp.retrieve_latin1_str(
            test3.canonical_name).raw_name(), b"f\xD6o\xD7\xBC");
        assert_eq!(sp.retrieve_latin1_str(
            test3.orig_name).pretty_name(), "fÖo×¼");
        assert!(test3.is_extended_id);
    }

    #[test]
    fn identifier_unicode() {
        let mut sp = StringPool::new();

        let test1 = Identifier::new_unicode(&mut sp, "FoO", false).unwrap();
        assert_eq!(sp.retrieve_latin1_str(
            test1.orig_name).raw_name(), b"FoO");
        assert_eq!(sp.retrieve_latin1_str(
            test1.canonical_name).raw_name(), b"foo");
        assert_eq!(sp.retrieve_latin1_str(
            test1.orig_name).pretty_name(), "FoO");
        assert!(!test1.is_extended_id);

        let test2 = Identifier::new_unicode(&mut sp, "fÖo", false).unwrap();
        assert_eq!(sp.retrieve_latin1_str(
            test2.orig_name).raw_name(), b"f\xD6o");
        assert_eq!(sp.retrieve_latin1_str(
            test2.canonical_name).raw_name(), b"f\xF6o");
        assert_eq!(sp.retrieve_latin1_str(
            test2.orig_name).pretty_name(), "fÖo");
        assert!(!test2.is_extended_id);

        let test3 = Identifier::new_unicode(&mut sp, "fooĀ", false);
        assert!(test3.is_err());

        let test4 = Identifier::new_unicode(&mut sp, "f😀oo", false);
        assert!(test4.is_err());
    }

    fn hash<T: Hash>(t: &T) -> u64 {
        let mut s = SipHasher::new();
        t.hash(&mut s);
        s.finish()
    }

    #[test]
    fn identifier_eq_and_hash() {
        let mut sp = StringPool::new();

        let test1 = Identifier::new_unicode(&mut sp, "foo", false).unwrap();
        let test2 = Identifier::new_unicode(&mut sp, "fOo", false).unwrap();
        assert_eq!(hash(&test1), hash(&test2));
        assert_eq!(test1, test2);

        let test1 = Identifier::new_unicode(&mut sp, "foo", false).unwrap();
        let test2 = Identifier::new_unicode(&mut sp, "foo", true).unwrap();
        assert!(test1 != test2);

        let test1 = Identifier::new_unicode(&mut sp, "foo", true).unwrap();
        let test2 = Identifier::new_unicode(&mut sp, "foo", true).unwrap();
        assert_eq!(hash(&test1), hash(&test2));
        assert_eq!(test1, test2);

        let test1 = Identifier::new_unicode(&mut sp, "foo", true).unwrap();
        let test2 = Identifier::new_unicode(&mut sp, "fOo", true).unwrap();
        assert!(test1 != test2);
    }

    #[test]
    fn identifier_debug_print() {
        let mut sp = StringPool::new();

        let test1 = Identifier::new_unicode(&mut sp, "foo", false).unwrap();
        assert_eq!(test1.debug_print(&sp), "\"foo\"");

        let test1 = Identifier::new_unicode(&mut sp, "foo", true).unwrap();
        assert_eq!(test1.debug_print(&sp), "\"\\\\foo\\\\\"");

        let test1 = Identifier::new_unicode(&mut sp, "fÖo", false).unwrap();
        assert_eq!(test1.debug_print(&sp), "\"f\\u00d6o\"");
    }
}
<commit_msg>Add internal identifiers that don't match ones from the input<commit_after>/*
Copyright (c) 2016-2017, Robert Ou <rqou@robertou.com>
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

1. Redistributions of source code must retain the above copyright notice,
   this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
   this list of conditions and the following disclaimer in the documentation
   and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

use std::hash::{Hash, Hasher};

use analyzer::objpools::*;
use analyzer::util::*;

#[derive(Copy, Clone, Eq, Debug)]
pub struct Identifier {
    pub orig_name: StringPoolIndexLatin1,
    pub canonical_name: StringPoolIndexLatin1,
    pub is_extended_id: bool,
    pub is_internal: bool,
}

impl PartialEq for Identifier {
    fn eq(&self, other: &Identifier) -> bool {
        (self.is_extended_id == other.is_extended_id) &&
        (self.canonical_name == other.canonical_name) &&
        (self.is_internal == other.is_internal)
    }
}

impl Hash for Identifier {
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.canonical_name.hash(state);
        self.is_extended_id.hash(state);
        self.is_internal.hash(state);
    }
}

impl Identifier {
    pub fn new_latin1(
        sp: &mut StringPool, name: StringPoolIndexLatin1, ext: bool)
        -> Result<Identifier, &'static str> {

        let canonical_name_vec = {
            // Borrow the name because we're going to need to look at it
            let name_ = sp.retrieve_latin1_str(name);

            // Validation
            if ext && !name_.valid_for_ext_id() {
                return Err("name is unacceptable as an identifier");
            }
            if !ext && !name_.valid_for_basic_id() {
                return Err("name is unacceptable as an identifier");
            }

            // Possibly lowercase canonical name for basic identifiers
            if ext {
                None
            } else {
                let mut lcase_name = Vec::<u8>::new();
                for c in name_.raw_name() {
                    lcase_name.push(LATIN1_LCASE_TABLE[*c as usize]);
                }
                Some(lcase_name)
            }
        };

        // We needed to make name_ out of scope before we can actually try
        // to add the new canonical name
        let mut canonical_name = name;
        if let Some(lcase_name) = canonical_name_vec {
            canonical_name = sp.add_latin1_str(&lcase_name);
        }

        Ok(Identifier {
            orig_name: name,
            canonical_name: canonical_name,
            is_extended_id: ext,
            is_internal: false,
        })
    }

    pub fn new_unicode(sp: &mut StringPool, name: &str, ext: bool)
        -> Result<Identifier, &'static str> {

        let mut latin1_name = Vec::<u8>::new();
        for c in name.chars() {
            if c >= '\u{0100}' {
                return Err("name contains characters outside Latin-1 range");
            }

            latin1_name.push(c as u8);
        }

        let sp_idx = sp.add_latin1_str(&latin1_name);
        Identifier::new_latin1(sp, sp_idx, ext)
    }

    pub fn debug_print(&self, sp: &StringPool) -> String {
        if self.is_extended_id {
            format!("\"\\\\{}\\\\\"", sp.retrieve_latin1_str(
                self.orig_name).debug_escaped_name())
        } else {
            format!("\"{}\"", sp.retrieve_latin1_str(
                self.orig_name).debug_escaped_name())
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::hash::SipHasher;

    #[test]
    fn identifier_basic() {
        let mut sp = StringPool::new();

        let sp_idx = sp.add_latin1_str(b"foo");
        let test1 = Identifier::new_latin1(&mut sp, sp_idx, false).unwrap();
        assert_eq!(sp.retrieve_latin1_str(
            test1.orig_name).raw_name(), b"foo");
        assert_eq!(sp.retrieve_latin1_str(
            test1.canonical_name).raw_name(), b"foo");
        assert_eq!(sp.retrieve_latin1_str(
            test1.orig_name).pretty_name(), "foo");
        assert!(!test1.is_extended_id);

        let sp_idx = sp.add_latin1_str(b"FoO");
        let test2 = Identifier::new_latin1(&mut sp, sp_idx, false).unwrap();
        assert_eq!(sp.retrieve_latin1_str(
            test2.orig_name).raw_name(), b"FoO");
        assert_eq!(sp.retrieve_latin1_str(
            test2.canonical_name).raw_name(), b"foo");
        assert_eq!(sp.retrieve_latin1_str(
            test2.orig_name).pretty_name(), "FoO");
        assert!(!test2.is_extended_id);

        let sp_idx = sp.add_latin1_str(b"foo_");
        let test3 = Identifier::new_latin1(&mut sp, sp_idx, false);
        assert!(test3.is_err());

        let sp_idx = sp.add_latin1_str(b"FoO");
        let test4 = Identifier::new_latin1(&mut sp, sp_idx, true).unwrap();
        assert_eq!(sp.retrieve_latin1_str(
            test4.orig_name).raw_name(), b"FoO");
        assert_eq!(sp.retrieve_latin1_str(
            test4.canonical_name).raw_name(), b"FoO");
        assert_eq!(sp.retrieve_latin1_str(
            test4.orig_name).pretty_name(), "FoO");
        assert!(test4.is_extended_id);
    }

    #[test]
    fn identifier_latin1_unusual() {
        let mut sp = StringPool::new();

        let sp_idx = sp.add_latin1_str(b"f\xD6o");
        let test1 = Identifier::new_latin1(&mut sp, sp_idx, false).unwrap();
        assert_eq!(sp.retrieve_latin1_str(
            test1.orig_name).raw_name(), b"f\xD6o");
        assert_eq!(sp.retrieve_latin1_str(
            test1.canonical_name).raw_name(), b"f\xF6o");
        assert_eq!(sp.retrieve_latin1_str(
            test1.orig_name).pretty_name(), "fÖo");
        assert!(!test1.is_extended_id);

        let sp_idx = sp.add_latin1_str(b"foo\xD7");
        let test2 = Identifier::new_latin1(&mut sp, sp_idx, false);
        assert!(test2.is_err());

        let sp_idx = sp.add_latin1_str(b"f\xD6o\xD7\xBC");
        let test3 = Identifier::new_latin1(&mut sp, sp_idx, true).unwrap();
        assert_eq!(sp.retrieve_latin1_str(
            test3.orig_name).raw_name(), b"f\xD6o\xD7\xBC");
        assert_eq!(sp.retrieve_latin1_str(
            test3.canonical_name).raw_name(), b"f\xD6o\xD7\xBC");
        assert_eq!(sp.retrieve_latin1_str(
            test3.orig_name).pretty_name(), "fÖo×¼");
        assert!(test3.is_extended_id);
    }

    #[test]
    fn identifier_unicode() {
        let mut sp = StringPool::new();

        let test1 = Identifier::new_unicode(&mut sp, "FoO", false).unwrap();
        assert_eq!(sp.retrieve_latin1_str(
            test1.orig_name).raw_name(), b"FoO");
        assert_eq!(sp.retrieve_latin1_str(
            test1.canonical_name).raw_name(), b"foo");
        assert_eq!(sp.retrieve_latin1_str(
            test1.orig_name).pretty_name(), "FoO");
        assert!(!test1.is_extended_id);

        let test2 = Identifier::new_unicode(&mut sp, "fÖo", false).unwrap();
        assert_eq!(sp.retrieve_latin1_str(
            test2.orig_name).raw_name(), b"f\xD6o");
        assert_eq!(sp.retrieve_latin1_str(
            test2.canonical_name).raw_name(), b"f\xF6o");
        assert_eq!(sp.retrieve_latin1_str(
            test2.orig_name).pretty_name(), "fÖo");
        assert!(!test2.is_extended_id);

        let test3 = Identifier::new_unicode(&mut sp, "fooĀ", false);
        assert!(test3.is_err());

        let test4 = Identifier::new_unicode(&mut sp, "f😀oo", false);
        assert!(test4.is_err());
    }

    fn hash<T: Hash>(t: &T) -> u64 {
        let mut s = SipHasher::new();
        t.hash(&mut s);
        s.finish()
    }

    #[test]
    fn identifier_eq_and_hash() {
        let mut sp = StringPool::new();

        let test1 = Identifier::new_unicode(&mut sp, "foo", false).unwrap();
        let test2 = Identifier::new_unicode(&mut sp, "fOo", false).unwrap();
        assert_eq!(hash(&test1), hash(&test2));
        assert_eq!(test1, test2);

        let test1 = Identifier::new_unicode(&mut sp, "foo", false).unwrap();
        let test2 = Identifier::new_unicode(&mut sp, "foo", true).unwrap();
        assert!(test1 != test2);

        let test1 = Identifier::new_unicode(&mut sp, "foo", true).unwrap();
        let test2 = Identifier::new_unicode(&mut sp, "foo", true).unwrap();
        assert_eq!(hash(&test1), hash(&test2));
        assert_eq!(test1, test2);

        let test1 = Identifier::new_unicode(&mut sp, "foo", true).unwrap();
        let test2 = Identifier::new_unicode(&mut sp, "fOo", true).unwrap();
        assert!(test1 != test2);
    }

    #[test]
    fn identifier_debug_print() {
        let mut sp = StringPool::new();

        let test1 = Identifier::new_unicode(&mut sp, "foo", false).unwrap();
        assert_eq!(test1.debug_print(&sp), "\"foo\"");

        let test1 = Identifier::new_unicode(&mut sp, "foo", true).unwrap();
        assert_eq!(test1.debug_print(&sp), "\"\\\\foo\\\\\"");

        let test1 = Identifier::new_unicode(&mut sp, "fÖo", false).unwrap();
        assert_eq!(test1.debug_print(&sp), "\"f\\u00d6o\"");
    }

    #[test]
    fn identifier_internal() {
        let mut sp = StringPool::new();

        let test1 = Identifier::new_unicode(&mut sp, "foo", false).unwrap();
        let test2 = Identifier::new_unicode(&mut sp, "foo", false).unwrap();
        assert_eq!(hash(&test1), hash(&test2));
        assert_eq!(test1, test2);

        let mut test1 = Identifier::new_unicode(&mut sp, "foo", false).unwrap();
        let mut test2 = Identifier::new_unicode(&mut sp, "foo", false).unwrap();
        test1.is_internal = true;
        test2.is_internal = true;
        assert_eq!(hash(&test1), hash(&test2));
        assert_eq!(test1, test2);

        let mut test1 = Identifier::new_unicode(&mut sp, "foo", false).unwrap();
        let test2 = Identifier::new_unicode(&mut sp, "foo", false).unwrap();
        test1.is_internal = true;
        assert!(test1 != test2);
    }
}
<|endoftext|>


<commit_before><commit_msg>add rust lexer<commit_after><|endoftext|>


<commit_before>extern crate chrono;
extern crate clap;
extern crate hostname;
#[macro_use]
extern crate log;
extern crate log4rs;
extern crate target_info;
extern crate xdg;

mod command_line_arguments;
mod context;
mod datetime;
mod execution_timer;
mod program_info;
mod qork;
mod system_info;

use log::LogLevelFilter;
use log4rs::config::{Appender, Config, Logger, Root};

use context::Context;
use execution_timer::ExecutionTimer;

fn main() {
    configure_logging();
    std::env::set_var("IN_QORK", "1");
    let _timer = ExecutionTimer::with_start_message("main.main");

    let context = Context::new();
    context.log_created_message();

    load_user_configuration_if_valid(&context);
}

fn load_user_configuration_if_valid(context: &Context) {
    if context.program_info().parsed_args().load_config() {
        let _timer = ExecutionTimer::with_start_message("main.load_user_configuration_if_valid");
        let dir = context.xdg().get_config_home();
        if !dir.exists() {
            warn!("The config_directory does not exist, no config will be loaded, config_directory={:?}", dir);
            return
        }

        if !dir.is_dir() {
            warn!("The config_directory is a file, not a directory, no config will be loaded, config_directory={:?}", dir);
            return
        }

        load_user_configuration(context);

    } else {
        info!("Loading of user configuration is disabled.");
    }
}

fn load_user_configuration(context: &Context) {
    let _timer = ExecutionTimer::with_start_message("main.load_user_configuration");
}

fn configure_logging() {
    use log4rs::append::console::ConsoleAppender;

    let stdout = ConsoleAppender::builder().build();

    let config = Config::builder()
        .appender(Appender::builder().build("stdout", Box::new(stdout)))
        .build(Root::builder().appender("stdout").build(LogLevelFilter::Debug))
        .unwrap();

    let handle = log4rs::init_config(config).unwrap();
}<commit_msg>Add logging configuration by file (YAML at the moment).<commit_after>extern crate chrono;
extern crate clap;
extern crate hostname;
#[macro_use]
extern crate log;
extern crate log4rs;
extern crate target_info;
extern crate xdg;

mod command_line_arguments;
mod context;
mod datetime;
mod execution_timer;
mod program_info;
mod qork;
mod system_info;

use xdg::BaseDirectories;

use context::Context;
use execution_timer::ExecutionTimer;

fn main() {
    std::env::set_var("IN_QORK", "1");
    let context = Context::new();
    configure_logging(context.xdg());
    let _timer = ExecutionTimer::with_start_message("main.main");
    context.log_created_message();
    load_user_configuration_if_valid(&context);
}

fn configure_logging(xdg: &BaseDirectories) {
    let path = xdg.place_config_file("logging.yaml");

    match path {
        Ok(p) => {
            if p.exists() {
                log4rs::init_file(&p, Default::default()).unwrap();
                info!("Logging initialized using file at {:?}", &p);
            }
            else {
            }
        },
        Err(_) => {
            // Do nothing, not sure there is anything we can do.
        }
    }
}

fn load_user_configuration_if_valid(context: &Context) {
    if context.program_info().parsed_args().load_config() {
        let _timer = ExecutionTimer::with_start_message("main.load_user_configuration_if_valid");
        let dir = context.xdg().get_config_home();
        if !dir.exists() {
            warn!("The config_directory does not exist, no config will be loaded, config_directory={:?}", dir);
            return
        }

        if !dir.is_dir() {
            warn!("The config_directory is a file, not a directory, no config will be loaded, config_directory={:?}", dir);
            return
        }

        load_user_configuration(context);

    } else {
        info!("Loading of user configuration is disabled.");
    }
}

fn load_user_configuration(context: &Context) {
    let _timer = ExecutionTimer::with_start_message("main.load_user_configuration");
}

<|endoftext|>


<commit_before>use kay::{Recipient, Fate, ActorSystem};
use descartes::{Band, Path};
use monet::{Thing, Instance};
use ::core::geometry::band_to_thing;
use super::{CurrentPlan, RoadStroke};

use monet::SetupInScene;

impl Recipient<SetupInScene> for CurrentPlan {
    fn receive(&mut self, _msg: &SetupInScene) -> Fate {
        self.create_interactables();
        Fate::Live
    }
}

use monet::RenderToScene;
use monet::UpdateThing;

impl Recipient<RenderToScene> for CurrentPlan {
    fn receive(&mut self, msg: &RenderToScene) -> Fate {match *msg{
        RenderToScene{renderer_id, scene_id} => {
            if self.ui_state.dirty {
                let thing : Thing = self.current_plan_result_delta.trimmed_strokes.to_create.values()
                    .filter(|stroke| stroke.nodes().len() > 1)
                    .map(RoadStroke::preview_thing)
                    .sum();
                renderer_id << UpdateThing{
                    scene_id: scene_id,
                    thing_id: 500,
                    thing: thing,
                    instance: Instance::with_color([0.3, 0.3, 0.5])
                };
                let intersections_thing : Thing = self.current_plan_result_delta.intersections.to_create.values()
                    .filter(|i| i.shape.segments().len() > 0)
                    .map(|i| band_to_thing(&Band::new(i.shape.clone(), 0.4), 0.5))
                    .sum();
                renderer_id << UpdateThing{
                    scene_id: scene_id,
                    thing_id: 501,
                    thing: intersections_thing,
                    instance: Instance::with_color([0.0, 0.0, 1.0])
                };
                let connecting_strokes_thing : Thing = self.current_plan_result_delta.intersections.to_create.values()
                    .filter(|i| !i.strokes.is_empty())
                    .map(|i| -> Thing {i.strokes.iter().map(RoadStroke::preview_thing).sum()})
                    .sum();
                renderer_id << UpdateThing{
                    scene_id: scene_id,
                    thing_id: 502,
                    thing: connecting_strokes_thing,
                    instance: Instance::with_color([0.5, 0.5, 1.0])
                };
                let transfer_strokes_thing : Thing = self.current_plan_result_delta.transfer_strokes.to_create.values()
                    .map(RoadStroke::preview_thing)
                    .sum();
                renderer_id << UpdateThing{
                    scene_id: scene_id,
                    thing_id: 503,
                    thing: transfer_strokes_thing,
                    instance: Instance::with_color([1.0, 0.5, 0.0])
                };
                self.ui_state.dirty = false;
            }
            Fate::Live
        }
    }}
}

pub fn setup(system: &mut ActorSystem) {
    system.add_inbox::<SetupInScene, CurrentPlan>();
    system.add_inbox::<RenderToScene, CurrentPlan>();
}<commit_msg>Make transfer lane preview thin<commit_after>use kay::{Recipient, Fate, ActorSystem};
use descartes::{Band, Path};
use monet::{Thing, Instance};
use ::core::geometry::band_to_thing;
use super::{CurrentPlan, RoadStroke};

use monet::SetupInScene;

impl Recipient<SetupInScene> for CurrentPlan {
    fn receive(&mut self, _msg: &SetupInScene) -> Fate {
        self.create_interactables();
        Fate::Live
    }
}

use monet::RenderToScene;
use monet::UpdateThing;

impl Recipient<RenderToScene> for CurrentPlan {
    fn receive(&mut self, msg: &RenderToScene) -> Fate {match *msg{
        RenderToScene{renderer_id, scene_id} => {
            if self.ui_state.dirty {
                let thing : Thing = self.current_plan_result_delta.trimmed_strokes.to_create.values()
                    .filter(|stroke| stroke.nodes().len() > 1)
                    .map(RoadStroke::preview_thing)
                    .sum();
                renderer_id << UpdateThing{
                    scene_id: scene_id,
                    thing_id: 500,
                    thing: thing,
                    instance: Instance::with_color([0.3, 0.3, 0.5])
                };
                let intersections_thing : Thing = self.current_plan_result_delta.intersections.to_create.values()
                    .filter(|i| i.shape.segments().len() > 0)
                    .map(|i| band_to_thing(&Band::new(i.shape.clone(), 0.4), 0.5))
                    .sum();
                renderer_id << UpdateThing{
                    scene_id: scene_id,
                    thing_id: 501,
                    thing: intersections_thing,
                    instance: Instance::with_color([0.0, 0.0, 1.0])
                };
                let connecting_strokes_thing : Thing = self.current_plan_result_delta.intersections.to_create.values()
                    .filter(|i| !i.strokes.is_empty())
                    .map(|i| -> Thing {i.strokes.iter().map(RoadStroke::preview_thing).sum()})
                    .sum();
                renderer_id << UpdateThing{
                    scene_id: scene_id,
                    thing_id: 502,
                    thing: connecting_strokes_thing,
                    instance: Instance::with_color([0.5, 0.5, 1.0])
                };
                let transfer_strokes_thing : Thing = self.current_plan_result_delta.transfer_strokes.to_create.values()
                    .map(|road_stroke|
                        band_to_thing(&Band::new(road_stroke.path().clone(), 0.3), 0.1))
                    .sum();
                renderer_id << UpdateThing{
                    scene_id: scene_id,
                    thing_id: 503,
                    thing: transfer_strokes_thing,
                    instance: Instance::with_color([1.0, 0.5, 0.0])
                };
                self.ui_state.dirty = false;
            }
            Fate::Live
        }
    }}
}

pub fn setup(system: &mut ActorSystem) {
    system.add_inbox::<SetupInScene, CurrentPlan>();
    system.add_inbox::<RenderToScene, CurrentPlan>();
}<|endoftext|>


<commit_before>use base::math::*;

pub struct Camera {
    // TODO
}

impl Camera {
    /// Returns the projection matrix
    pub fn proj_matrix(&self) -> Matrix4<f32> {
        perspective(deg(60.0), 16.0 / 9.0, 0.1, 100.0)
    }

    /// Returns view matrix
    pub fn view_matrix(&self) -> Matrix4<f32> {
        Matrix4::look_at(Point3::new(20.0, -20.0, 10.0),
                         Point3::new(50.0, 50.0, 2.0),
                         Vector3::unit_z())
    }
}
<commit_msg>add changes to camera.rs<commit_after>use base::math::*;

pub struct Camera {
    pub position: Point3f, // PRP
    // look_at_point: Point3<f32>, // VRP
    pub view_up_vector: Vector3f, // VUV
    pub theta: f32,
    pub phi: f32, // theta_phi: (f32, f32),
}

impl Camera {
    /// Returns the projection matrix
    pub fn proj_matrix(&self) -> Matrix4<f32> {
        perspective(deg(60.0), 16.0 / 9.0, 0.1, 100.0)
    }

    /// Returs view matrix
    pub fn view_matrix(&self) -> Matrix4<f32> {
        Matrix4::look_at(self.position, self.get_look_at_point(), self.view_up_vector)
    }

    /// Calculates the look_at_point by using theta and phi on the unit sphere
    pub fn get_look_at_point(&self) -> Point3f {
        // let lookatvector = self.get_look_at_vector();
        self.position + self.get_look_at_vector()
        // Point3f::new(lookatvector.x + self.position.x,
        //              lookatvector.y + self.position.y,
        //              lookatvector.z + self.position.z)
    }

    pub fn get_look_at_vector(&self) -> Vector3f {
        Vector3f::new(self.theta.sin() * self.phi.cos(),
                      self.theta.sin() * self.phi.sin(),
                      self.theta.cos())
    }

    pub fn move_by(&mut self, pos_diff: Vector3f) {
        self.position += pos_diff;
        // self.position.add_assign(pos_diff);
    }

    /// method to call when forward or backward movement is needed
    /// `factor` is a factor to scale the movement speed
    /// `factor` has to be positive for foward movement
    /// `factor` has to be negative for backward movement
    pub fn move_forward_backward(&mut self, factor: f32) {
        // maybe implement the function so the factor is a parameter (to regulate speed
        // with shift)
        let mut lookatvector = self.get_look_at_vector();
        lookatvector.z = 0.0;
        lookatvector.normalize();
        lookatvector *= factor;
        self.move_by(lookatvector); //does the "self" have to be here?
    }

    /// method to call when left or right movement is needed
    /// `factor` is a factor to scale the movement speed
    /// `factor` has to be positive for left movement
    /// `factor` has to be negative for right movement
    pub fn move_left_right(&mut self, factor: f32) {
        let mut lookatvector = self.get_look_at_vector();
        lookatvector.z = 0.0;
        lookatvector.normalize();
        // Get the orthogonal 2d-vector, which is 90 degrees to the left
        let mut move_dir = Vector3f::new(-lookatvector.y, lookatvector.x, 0.0);
        move_dir *= factor;
        self.move_by(move_dir);

    }

    /// method to call when upward or downward movement is needed
    /// `factor` is a factor to scale the movement speed
    /// `factor` has to be positive for upward movement
    /// `factor` has to be negative for downward movement
    pub fn move_up_down(&mut self, factor: f32) {
        self.move_by(Vector3f::new(0.0, 0.0, factor));
    }

    // Used in move_forward_backward
    // pub fn move_backward(&self) {
    //     let factor = -1.0;
    //     let lookatvector = get_look_at_vector();
    //     lookatvector.z = 0;
    //     lookatvector.normalize();
    //     lookatvector.mul_assign(factor);
    //     self.move_by(lookatvector); //does the "self" have to be here?
    // }
    // später mehtoden wie move_forward

    pub fn change_dir(&mut self, theta_diff: f32, phi_diff: f32) {
        self.theta += theta_diff;
        self.phi += phi_diff;
        // new matrix will be calculated
    }

    // pub fn view_matrix(&self) -> Matrix4<f32> {
    //     let N: Vector3 = (self.position).sub(self.look_at_point);
    //     let V: Vector3 = (N.cross(self.view_up_vector)).cross(N);
    //     let U: Vector3 = V.cross(N);
    //     Matrix4::new(U, V, N)
    // }
}
<|endoftext|>


<commit_before>// See LICENSE file for copyright and license details.

// http://bitsquid.blogspot.ru/2012/01/sensible-error-handling-part-1.html

#![feature(macro_rules)]

use std::cast::transmute;
use std::local_data;

#[macro_export]
macro_rules! set_error_context (
    ($name: expr, $data: expr) => (
        let _ec = error_context::ErrorContext::new($name, $data);
    )
)

// ErrorContext version without destructor for storing in global array
struct ErrorContextInternal {
    description: &'static str,
    data: &'static str,
}

local_data_key!(CONTEXTS: Vec<ErrorContextInternal>)

pub struct ErrorContext<'a> {
    description: &'static str,
    data: &'a str,
}

impl<'a> ErrorContext<'a> {
    #[inline]
    pub fn new<'a>(description: &'static str, data: &'a str) -> ErrorContext<'a> {
        if !is_initialized() {
            init();
        }
        local_data::get_mut(CONTEXTS, |contexts| {
            contexts.unwrap().push(ErrorContextInternal {
                description: description,
                data: unsafe {
                    transmute::<&'a str, &'static str>(data)
                },
            });
        });
        ErrorContext {
            description: description,
            data: data,
        }
    }
}

#[unsafe_destructor]
impl<'a> Drop for ErrorContext<'a> {
    fn drop(&mut self) {
        if std::task::failing() {
            on_task_fail();
        } else {
            local_data::get_mut(CONTEXTS, |contexts| {
                contexts.unwrap().pop();
            });
        }
    }
}

fn init() {
    local_data::get_mut(CONTEXTS, |contexts| {
        assert!(contexts.is_none());
    });
    local_data::set(CONTEXTS, Vec::new());
}

#[inline]
fn is_initialized() -> bool {
    local_data::get(CONTEXTS, |contexts| {
        contexts.is_some()
    })
}

fn print_contexts() {
    local_data::get(CONTEXTS, |contexts| {
        if contexts.is_some() {
            for context in contexts.unwrap().iter() {
                println!("When {}: {}", context.description, context.data);
            }
        }
    });
}

fn on_task_fail() {
    print_contexts();
    local_data::get_mut(CONTEXTS, |contexts| {
        if contexts.is_some() {
            contexts.unwrap().clear();
        }
    });
}

// vim: set tabstop=4 shiftwidth=4 softtabstop=4 expandtab:
<commit_msg>Updated to latest Rust: local_data changes<commit_after>// See LICENSE file for copyright and license details.

// http://bitsquid.blogspot.ru/2012/01/sensible-error-handling-part-1.html

#![feature(macro_rules)]

use std::cast::transmute;
use std::cell;

#[macro_export]
macro_rules! set_error_context (
    ($name: expr, $data: expr) => (
        let _ec = error_context::ErrorContext::new($name, $data);
    )
)

// ErrorContext version without destructor for storing in global array
struct ErrorContextInternal {
    description: &'static str,
    data: &'static str,
}

local_data_key!(CONTEXTS: cell::RefCell<Vec<ErrorContextInternal>>)

pub struct ErrorContext<'a> {
    description: &'static str,
    data: &'a str,
}

impl<'a> ErrorContext<'a> {
    #[inline]
    pub fn new<'a>(description: &'static str, data: &'a str) -> ErrorContext<'a> {
        if !is_initialized() {
            init();
        }
        match CONTEXTS.get() {
            Some(contexts) => {
                contexts.borrow_mut().push(ErrorContextInternal {
                    description: description,
                    data: unsafe {
                        transmute::<&'a str, &'static str>(data)
                    },
                });
            }
            None => fail!("Contexts can not be None"),
        }
        ErrorContext {
            description: description,
            data: data,
        }
    }
}

#[unsafe_destructor]
impl<'a> Drop for ErrorContext<'a> {
    fn drop(&mut self) {
        if std::task::failing() {
            on_task_fail();
        } else {
            match CONTEXTS.get() {
                Some(contexts) => {
                    contexts.borrow_mut().pop();
                },
                None => {},
            }
        }
    }
}

fn init() {
    assert!(!is_initialized());
    CONTEXTS.replace(Some(cell::RefCell::new(Vec::new())));
}

#[inline]
fn is_initialized() -> bool {
    CONTEXTS.get().is_some()
}

fn print_contexts() {
    match CONTEXTS.get() {
        Some(contexts) => {
            for context in contexts.borrow().iter() {
                println!("When {}: {}", context.description, context.data);
            }
        },
        None => fail!("Contexts can not be None"),
    }
}

fn on_task_fail() {
    print_contexts();
    match CONTEXTS.get() {
        Some(contexts) => contexts.borrow_mut().clear(),
        None => fail!("Contexts can not be None"),
    }
}

// vim: set tabstop=4 shiftwidth=4 softtabstop=4 expandtab:
<|endoftext|>