<commit_before>mod day01;
mod day02;
mod day03;
mod day19;

use anyhow::{Context, Result};
use std::time::Instant;

macro_rules! aoc {
    ($i:ident) => {
        let s = stringify!($i);
        let n = s
            .strip_prefix("day")
            .expect("argument to aoc!() must start with 'day'");
        let path = format!("input/{}.txt", s);
        let input = std::fs::read_to_string(&path).with_context(|| {
            format!(
                "could not read file '{}'. Please run from the crate root.",
                &path
            )
        })?;
        let parsed = $i::parse(&input)?;
        {
            let start = Instant::now();
            let answer = $i::part1(&parsed);
            let end = Instant::now();
            println!(
                "day {} part 1: {} ({} µs)",
                n,
                answer,
                (end - start).as_micros()
            );
        }
        {
            let start = Instant::now();
            let answer = $i::part2(&parsed);
            let end = Instant::now();
            println!(
                "day {} part 1: {} ({} µs)",
                n,
                answer,
                (end - start).as_micros()
            );
        }
    };
}

fn main() -> Result<()> {
    aoc!(day01);
    aoc!(day02);
    aoc!(day03);
    aoc!(day19);

    Ok(())
}
<commit_msg>Add parsing benchmarks<commit_after>mod day01;
mod day02;
mod day03;
mod day19;

use anyhow::{Context, Result};
use std::time::Instant;

macro_rules! aoc {
    ($i:ident) => {
        let s = stringify!($i);
        let n = s
            .strip_prefix("day")
            .expect("argument to aoc!() must start with 'day'");
        let path = format!("input/{}.txt", s);
        let input = std::fs::read_to_string(&path).with_context(|| {
            format!(
                "could not read file '{}'. Please run from the crate root.",
                &path
            )
        })?;

        let parsed = {
            let start = Instant::now();
            let parsed = $i::parse(&input)?;
            let end = Instant::now();
            println!("day {} parsed in {} µs", n, (end - start).as_micros());
            parsed
        };

        {
            let start = Instant::now();
            let answer = $i::part1(&parsed);
            let end = Instant::now();
            println!(
                "day {} part 1: {} ({} µs)",
                n,
                answer,
                (end - start).as_micros()
            );
        }
        {
            let start = Instant::now();
            let answer = $i::part2(&parsed);
            let end = Instant::now();
            println!(
                "day {} part 1: {} ({} µs)",
                n,
                answer,
                (end - start).as_micros()
            );
        }
    };
}

fn main() -> Result<()> {
    aoc!(day01);
    aoc!(day02);
    aoc!(day03);
    aoc!(day19);

    Ok(())
}
<|endoftext|>


<commit_before>use regex::Regex;
use std::path::PathBuf;
use std::result::Result;
use subprocess::{Exec, Redirection};

const LOOP_BACKING_DEVICE_BASENAME: &'static str = "flaglock6-home";
const LOOP_DEVICE_PARTITION_LABEL: &'static str = "fl6";

#[derive(Debug)]
pub enum AuricError {
    Invocation(String),
    Io(String),
    Subprocess(String),
    NotFound,
}

impl From<subprocess::PopenError> for AuricError {
    fn from(err: subprocess::PopenError) -> AuricError {
        AuricError::Subprocess(err.to_string())
    }
}
struct SshfsManager {
    mountpoint: PathBuf,
}

struct LoopManager {
    target: Regex,
    backing: PathBuf,
}

impl SshfsManager {
    pub fn new() -> Result<SshfsManager, AuricError> {
        let xdg_runtime_dir = match std::env::var("XDG_RUNTIME_DIR") {
            Ok(val) => val,
            Err(e) => {
                return Err(AuricError::Invocation(format!(
                    "fatal error getting ${{XDG_RUNTIME_DIR}}: ``{}''",
                    e
                )))
            }
        };
        let mut mountpoint = PathBuf::new();
        mountpoint.push(xdg_runtime_dir);
        mountpoint.push("rsync.net-mountpoint");

        Ok(SshfsManager {
            mountpoint: mountpoint,
        })
    }

    pub fn ensure_mountpoint_is_dir(&self) -> Result<(), AuricError> {
        if self.mountpoint.is_dir() {
            return Ok(());
        }
        std::fs::create_dir(self.mountpoint.as_path())
            .map_err(|e| AuricError::Io(format!("bad mountpoint: ``{}''", e)))
    }

    // Does _not_ ensure that backing device exists.
    pub fn loop_backing_device_path(&self) -> PathBuf {
        let mut result: PathBuf = self.mountpoint.clone();
        result.push(LOOP_BACKING_DEVICE_BASENAME);
        result
    }

    pub fn loop_backing_device_present(&self) -> bool {
        self.loop_backing_device_path().is_file()
    }
}

impl LoopManager {
    pub fn new(backing: &PathBuf) -> LoopManager {
        let target = format!(
            r"^(/dev/loop\d)(\s+\d+){{4}}\s+({})\s+",
            backing.to_str().unwrap()
        );
        LoopManager {
            target: Regex::new(&target).unwrap(),
            backing: backing.clone(),
        }
    }

    pub fn find(&self) -> Result<PathBuf, AuricError> {
        let result = Exec::cmd("sudo")
            .arg("losetup")
            .arg("-l")
            .stdout(Redirection::Pipe)
            .stderr(Redirection::Pipe)
            .capture()?;
        if !result.success() {
            return Err(AuricError::Subprocess(format!(
                "failed to list loop devices: ``{}''",
                result.stderr_str()
            )));
        }

        for line in result.stdout_str().lines() {
            if let Some(captures) = self.target.captures(line) {
                return Ok(PathBuf::from(captures.get(1).unwrap().as_str()));
            }
        }
        Err(AuricError::NotFound)
    }

    pub fn attach(&self) -> Result<(), AuricError> {
        let result = Exec::cmd("udisksctl")
            .arg("loop-setup")
            .arg("-f")
            .arg(&self.backing)
            .stdout(Redirection::Pipe)
            .stderr(Redirection::Pipe)
            .capture()?;
        if !result.success() {
            return Err(AuricError::Subprocess(format!(
                "failed to attach loop device: ``{}''",
                result.stderr_str()
            )));
        }
        Ok(())
    }

    // Note that the loop device will linger if the volume remains
    // unlocked. Prefer not to call this before locking.
    pub fn detach(&self) -> Result<(), AuricError> {
        let attached_loop = match self.find() {
            Ok(path) => path,
            Err(e) => {
                if let AuricError::NotFound = e {
                    return Ok(());
                }
                return Err(e);
            }
        };
        let result = Exec::cmd("udisksctl")
            .arg("loop-delete")
            .arg("-b")
            .arg(&attached_loop)
            .stdout(Redirection::Pipe)
            .stderr(Redirection::Pipe)
            .capture()?;
        if !result.success() {
            return Err(AuricError::Subprocess(format!(
                "failed to detach loop device: ``{}''",
                result.stderr_str()
            )));
        }
        Ok(())
    }
}

fn main_impl() -> Result<(), AuricError> {
    println!("Hello there!");
    Ok(())
}

fn main() {
    std::process::exit(match main_impl() {
        Ok(_) => 0,
        Err(e) => {
            eprintln!("{:?}", e);
            1
        }
    });
}
<commit_msg>apricot-auric: Add sshfs functionality<commit_after>use regex::Regex;
use std::path::PathBuf;
use std::result::Result;
use subprocess::{Exec, Redirection};

const LOOP_BACKING_DEVICE_BASENAME: &'static str = "flaglock6-home";
const LOOP_DEVICE_PARTITION_LABEL: &'static str = "fl6";
const RSYNC_DOT_NET_REMOTE_DIR: &'static str = "usw-s007.rsync.net:./";

#[derive(Debug)]
pub enum AuricError {
    Invocation(String),
    Io(String),
    Subprocess(String),
    NotFound,
}

impl From<subprocess::PopenError> for AuricError {
    fn from(err: subprocess::PopenError) -> AuricError {
        AuricError::Subprocess(err.to_string())
    }
}
struct SshfsManager {
    mountpoint: PathBuf,
}

struct LoopManager {
    target: Regex,
    backing: PathBuf,
}

impl SshfsManager {
    pub fn new() -> Result<SshfsManager, AuricError> {
        let xdg_runtime_dir = match std::env::var("XDG_RUNTIME_DIR") {
            Ok(val) => val,
            Err(e) => {
                return Err(AuricError::Invocation(format!(
                    "fatal error getting ${{XDG_RUNTIME_DIR}}: ``{}''",
                    e
                )))
            }
        };
        let mut mountpoint = PathBuf::new();
        mountpoint.push(xdg_runtime_dir);
        mountpoint.push("rsync.net-mountpoint");

        Ok(SshfsManager {
            mountpoint: mountpoint,
        })
    }

    fn ensure_mountpoint_is_dir(&self) -> Result<(), AuricError> {
        if self.mountpoint.is_dir() {
            return Ok(());
        }
        std::fs::create_dir(self.mountpoint.as_path())
            .map_err(|e| AuricError::Io(format!("bad mountpoint: ``{}''", e)))
    }

    // Does _not_ ensure that backing device exists.
    pub fn loop_backing_device_path(&self) -> PathBuf {
        let mut result: PathBuf = self.mountpoint.clone();
        result.push(LOOP_BACKING_DEVICE_BASENAME);
        result
    }

    pub fn loop_backing_device_present(&self) -> bool {
        self.loop_backing_device_path().is_file()
    }

    pub fn mount(&self) -> Result<(), AuricError> {
        self.ensure_mountpoint_is_dir()?;
        let result = Exec::cmd("sshfs")
            .arg("-o")
            .arg("allow_other")
            .arg(RSYNC_DOT_NET_REMOTE_DIR)
            .arg(&self.mountpoint)
            .stdout(Redirection::Pipe)
            .stderr(Redirection::Pipe)
            .capture()?;
        if !result.success() {
            return Err(AuricError::Subprocess(format!(
                "sshfs failed: ``{}''",
                result.stderr_str()
            )));
        }
        Ok(())
    }

    pub fn unmount(&self) -> Result<(), AuricError> {
        let result = Exec::cmd("fusermount")
            .arg("-u")
            .arg(&self.mountpoint)
            .stdout(Redirection::Pipe)
            .stderr(Redirection::Pipe)
            .capture()?;
        if !result.success() {
            return Err(AuricError::Subprocess(format!(
                "fusermount -u failed: ``{}''",
                result.stderr_str()
            )));
        }
        Ok(())
    }
}

impl LoopManager {
    pub fn new(backing: &PathBuf) -> LoopManager {
        let target = format!(
            r"^(/dev/loop\d)(\s+\d+){{4}}\s+({})\s+",
            backing.to_str().unwrap()
        );
        LoopManager {
            target: Regex::new(&target).unwrap(),
            backing: backing.clone(),
        }
    }

    pub fn find(&self) -> Result<PathBuf, AuricError> {
        let result = Exec::cmd("sudo")
            .arg("losetup")
            .arg("-l")
            .stdout(Redirection::Pipe)
            .stderr(Redirection::Pipe)
            .capture()?;
        if !result.success() {
            return Err(AuricError::Subprocess(format!(
                "failed to list loop devices: ``{}''",
                result.stderr_str()
            )));
        }

        for line in result.stdout_str().lines() {
            if let Some(captures) = self.target.captures(line) {
                return Ok(PathBuf::from(captures.get(1).unwrap().as_str()));
            }
        }
        Err(AuricError::NotFound)
    }

    pub fn attach(&self) -> Result<(), AuricError> {
        let result = Exec::cmd("udisksctl")
            .arg("loop-setup")
            .arg("-f")
            .arg(&self.backing)
            .stdout(Redirection::Pipe)
            .stderr(Redirection::Pipe)
            .capture()?;
        if !result.success() {
            return Err(AuricError::Subprocess(format!(
                "failed to attach loop device: ``{}''",
                result.stderr_str()
            )));
        }
        Ok(())
    }

    // Note that the loop device will linger if the volume remains
    // unlocked. Prefer not to call this before locking.
    pub fn detach(&self) -> Result<(), AuricError> {
        let attached_loop = match self.find() {
            Ok(path) => path,
            Err(e) => {
                if let AuricError::NotFound = e {
                    return Ok(());
                }
                return Err(e);
            }
        };
        let result = Exec::cmd("udisksctl")
            .arg("loop-delete")
            .arg("-b")
            .arg(&attached_loop)
            .stdout(Redirection::Pipe)
            .stderr(Redirection::Pipe)
            .capture()?;
        if !result.success() {
            return Err(AuricError::Subprocess(format!(
                "failed to detach loop device: ``{}''",
                result.stderr_str()
            )));
        }
        Ok(())
    }
}

fn main_impl() -> Result<(), AuricError> {
    println!("Hello there!");
    Ok(())
}

fn main() {
    std::process::exit(match main_impl() {
        Ok(_) => 0,
        Err(e) => {
            eprintln!("{:?}", e);
            1
        }
    });
}
<|endoftext|>


<commit_before>//! `PUT /_matrix/app/*/transactions/{txnId}`
//!
//! Endpoint to push an event (or batch of events) to the application service.

#[cfg(feature = "unstable-msc2409")]
use js_int::UInt;
#[cfg(feature = "unstable-msc2409")]
use ruma_common::{
    events::receipt::Receipt, presence::PresenceState, serde::from_raw_json_value, OwnedEventId,
    OwnedRoomId, OwnedUserId,
};
#[cfg(feature = "unstable-msc2409")]
use serde::{de, Deserialize, Serialize};
#[cfg(feature = "unstable-msc2409")]
use serde_json::{value::RawValue as RawJsonValue, Value as JsonValue};
#[cfg(feature = "unstable-msc2409")]
use std::collections::BTreeMap;

/// Type for passing ephemeral data to homeservers.
#[cfg(feature = "unstable-msc2409")]
#[derive(Clone, Debug, Serialize)]
#[non_exhaustive]
pub enum Edu {
    /// An EDU representing presence updates for users of the sending homeserver.
    Presence(PresenceContent),

    /// An EDU representing receipt updates for users of the sending homeserver.
    Receipt(ReceiptContent),

    /// A typing notification EDU for a user in a room.
    Typing(TypingContent),

    #[doc(hidden)]
    #[serde(skip)]
    _Custom(JsonValue),
}

#[derive(Debug, Deserialize)]
#[cfg(feature = "unstable-msc2409")]
struct EduDeHelper {
    /// The message type field
    r#type: String,
    content: Box<RawJsonValue>,
}

#[cfg(feature = "unstable-msc2409")]
impl<'de> Deserialize<'de> for Edu {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: de::Deserializer<'de>,
    {
        let json = Box::<RawJsonValue>::deserialize(deserializer)?;
        let EduDeHelper { r#type, content } = from_raw_json_value(&json)?;

        Ok(match r#type.as_ref() {
            "m.presence" => Self::Presence(from_raw_json_value(&content)?),
            "m.receipt" => Self::Receipt(from_raw_json_value(&content)?),
            "m.typing" => Self::Typing(from_raw_json_value(&content)?),
            _ => Self::_Custom(from_raw_json_value(&content)?),
        })
    }
}

/// The content for "m.presence" Edu.
#[cfg(feature = "unstable-msc2409")]
#[derive(Clone, Debug, Deserialize, Serialize)]
#[cfg_attr(not(feature = "unstable-exhaustive-types"), non_exhaustive)]
pub struct PresenceContent {
    /// A list of presence updates that the receiving server is likely to be interested in.
    pub push: Vec<PresenceUpdate>,
}

#[cfg(feature = "unstable-msc2409")]
impl PresenceContent {
    /// Creates a new `PresenceContent`.
    pub fn new(push: Vec<PresenceUpdate>) -> Self {
        Self { push }
    }
}

/// An update to the presence of a user.
#[cfg(feature = "unstable-msc2409")]
#[derive(Clone, Debug, Deserialize, Serialize)]
#[cfg_attr(not(feature = "unstable-exhaustive-types"), non_exhaustive)]
pub struct PresenceUpdate {
    /// The user ID this presence EDU is for.
    pub user_id: OwnedUserId,

    /// The presence of the user.
    pub presence: PresenceState,

    /// An optional description to accompany the presence.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub status_msg: Option<String>,

    /// The number of milliseconds that have elapsed since the user last did something.
    pub last_active_ago: UInt,

    /// Whether or not the user is currently active.
    ///
    /// Defaults to false.
    #[serde(default, skip_serializing_if = "ruma_common::serde::is_default")]
    pub currently_active: bool,
}

#[cfg(feature = "unstable-msc2409")]
impl PresenceUpdate {
    /// Creates a new `PresenceUpdate` with the given `user_id`, `presence` and `last_activity`.
    pub fn new(user_id: OwnedUserId, presence: PresenceState, last_activity: UInt) -> Self {
        Self {
            user_id,
            presence,
            last_active_ago: last_activity,
            status_msg: None,
            currently_active: false,
        }
    }
}

/// The content for "m.receipt" Edu.
#[cfg(feature = "unstable-msc2409")]
#[derive(Clone, Debug, Deserialize, Serialize)]
#[cfg_attr(not(feature = "unstable-exhaustive-types"), non_exhaustive)]
#[serde(transparent)]
pub struct ReceiptContent(pub BTreeMap<OwnedRoomId, ReceiptMap>);

#[cfg(feature = "unstable-msc2409")]
impl ReceiptContent {
    /// Creates a new `ReceiptContent`.
    pub fn new(receipts: BTreeMap<OwnedRoomId, ReceiptMap>) -> Self {
        Self(receipts)
    }
}

/// Mapping between user and `ReceiptData`.
#[cfg(feature = "unstable-msc2409")]
#[derive(Clone, Debug, Deserialize, Serialize)]
#[cfg_attr(not(feature = "unstable-exhaustive-types"), non_exhaustive)]
pub struct ReceiptMap {
    /// Read receipts for users in the room.
    #[serde(rename = "m.read")]
    pub read: BTreeMap<OwnedUserId, ReceiptData>,
}

#[cfg(feature = "unstable-msc2409")]
impl ReceiptMap {
    /// Creates a new `ReceiptMap`.
    pub fn new(read: BTreeMap<OwnedUserId, ReceiptData>) -> Self {
        Self { read }
    }
}

/// Metadata about the event that was last read and when.
#[cfg(feature = "unstable-msc2409")]
#[derive(Clone, Debug, Deserialize, Serialize)]
#[cfg_attr(not(feature = "unstable-exhaustive-types"), non_exhaustive)]
pub struct ReceiptData {
    /// Metadata for the read receipt.
    pub data: Receipt,

    /// The extremity event ID the user has read up to.
    pub event_ids: Vec<OwnedEventId>,
}

#[cfg(feature = "unstable-msc2409")]
impl ReceiptData {
    /// Creates a new `ReceiptData`.
    pub fn new(data: Receipt, event_ids: Vec<OwnedEventId>) -> Self {
        Self { data, event_ids }
    }
}

/// The content for "m.typing" Edu.
#[cfg(feature = "unstable-msc2409")]
#[derive(Clone, Debug, Deserialize, Serialize)]
#[cfg_attr(not(feature = "unstable-exhaustive-types"), non_exhaustive)]
pub struct TypingContent {
    /// The room where the user's typing status has been updated.
    pub room_id: OwnedRoomId,

    /// The user ID that has had their typing status changed.
    pub user_id: OwnedUserId,

    /// Whether the user is typing in the room or not.
    pub typing: bool,
}

#[cfg(feature = "unstable-msc2409")]
impl TypingContent {
    /// Creates a new `TypingContent`.
    pub fn new(room_id: OwnedRoomId, user_id: OwnedUserId, typing: bool) -> Self {
        Self { room_id, user_id, typing }
    }
}

pub mod v1 {
    //! `/v1/` ([spec])
    //!
    //! [spec]: https://spec.matrix.org/v1.4/application-service-api/#put_matrixappv1transactionstxnid

    #[cfg(feature = "unstable-msc2409")]
    use super::Edu;
    #[cfg(feature = "unstable-msc2409")]
    use ruma_common::events::AnyToDeviceEvent;

    use ruma_common::{
        api::ruma_api, events::AnyTimelineEvent, serde::Raw, OwnedTransactionId, TransactionId,
    };

    #[cfg(feature = "unstable-msc3202")]
    use js_int::UInt;
    #[cfg(feature = "unstable-msc3202")]
    use ruma_common::{DeviceKeyAlgorithm, OwnedDeviceId, OwnedUserId};
    #[cfg(feature = "unstable-msc3202")]
    use serde::{Deserialize, Serialize};
    #[cfg(feature = "unstable-msc3202")]
    use std::collections::BTreeMap;

    ruma_api! {
        metadata: {
            description: "This API is called by the homeserver when it wants to push an event (or batch of events) to the application service.",
            method: PUT,
            name: "push_events",
            stable_path: "/_matrix/app/v1/transactions/:txn_id",
            rate_limited: false,
            authentication: AccessToken,
            added: 1.0,
        }

        request: {
            /// The transaction ID for this set of events.
            ///
            /// Homeservers generate these IDs and they are used to ensure idempotency of results.
            #[ruma_api(path)]
            pub txn_id: &'a TransactionId,

            /// A list of events.
            pub events: &'a [Raw<AnyTimelineEvent>],

            /// Information on E2E device updates.
            #[cfg(feature = "unstable-msc3202")]
            #[serde(
                default,
                skip_serializing_if = "DeviceLists::is_empty",
                rename = "org.matrix.msc3202.device_lists"
            )]
            pub device_lists: DeviceLists,

            /// The number of unclaimed one-time keys currently held on the server for this device, for each algorithm.
            #[cfg(feature = "unstable-msc3202")]
            #[serde(
                default,
                skip_serializing_if = "BTreeMap::is_empty",
                rename = "org.matrix.msc3202.device_one_time_keys_count"
            )]
            pub device_one_time_keys_count: BTreeMap<OwnedUserId, BTreeMap<OwnedDeviceId, BTreeMap<DeviceKeyAlgorithm, UInt>>>,

            /// A list of key algorithms for which the server has an unused fallback key for the device.
            #[cfg(feature = "unstable-msc3202")]
            #[serde(
                default,
                skip_serializing_if = "BTreeMap::is_empty",
                rename = "org.matrix.msc3202.device_unused_fallback_key_types"
            )]
            pub device_unused_fallback_key_types: BTreeMap<OwnedUserId, BTreeMap<OwnedDeviceId, Vec<DeviceKeyAlgorithm>>>,

            /// A list of EDUs.
            #[cfg(feature = "unstable-msc2409")]
            #[serde(
                default,
                skip_serializing_if = "<[_]>::is_empty",
                rename = "de.sorunome.msc2409.ephemeral"
            )]
            pub ephemeral: &'a [Edu],

            /// A list of to-device messages.
            #[cfg(feature = "unstable-msc2409")]
            #[serde(
                default,
                skip_serializing_if = "<[_]>::is_empty",
                rename = "de.sorunome.msc2409.to_device"
            )]
            pub to_device: &'a [Raw<AnyToDeviceEvent>]
        }

        #[derive(Default)]
        response: {}
    }

    impl<'a> Request<'a> {
        /// Creates a new `Request` with the given transaction ID and list of events.
        pub fn new(txn_id: &'a TransactionId, events: &'a [Raw<AnyTimelineEvent>]) -> Self {
            Self {
                txn_id,
                events,
                #[cfg(feature = "unstable-msc3202")]
                device_lists: DeviceLists::new(),
                #[cfg(feature = "unstable-msc3202")]
                device_one_time_keys_count: BTreeMap::new(),
                #[cfg(feature = "unstable-msc3202")]
                device_unused_fallback_key_types: BTreeMap::new(),
                #[cfg(feature = "unstable-msc2409")]
                ephemeral: &[],
                #[cfg(feature = "unstable-msc2409")]
                to_device: &[],
            }
        }
    }

    impl IncomingRequest {
        /// Creates an `IncomingRequest` with the given transaction ID and list of events.
        pub fn new(
            txn_id: OwnedTransactionId,
            events: Vec<Raw<AnyTimelineEvent>>,
        ) -> IncomingRequest {
            IncomingRequest {
                txn_id,
                events,
                #[cfg(feature = "unstable-msc3202")]
                device_lists: DeviceLists::new(),
                #[cfg(feature = "unstable-msc3202")]
                device_one_time_keys_count: BTreeMap::new(),
                #[cfg(feature = "unstable-msc3202")]
                device_unused_fallback_key_types: BTreeMap::new(),
                #[cfg(feature = "unstable-msc2409")]
                ephemeral: Vec::new(),
                #[cfg(feature = "unstable-msc2409")]
                to_device: Vec::new(),
            }
        }
    }

    impl Response {
        /// Creates an empty `Response`.
        pub fn new() -> Self {
            Self {}
        }
    }

    /// Information on E2E device updates.
    #[derive(Clone, Debug, Default, Deserialize, Serialize)]
    #[cfg_attr(not(feature = "unstable-exhaustive-types"), non_exhaustive)]
    #[cfg(feature = "unstable-msc3202")]
    pub struct DeviceLists {
        /// List of users who have updated their device identity keys or who now
        /// share an encrypted room with the client since the previous sync.
        #[serde(default, skip_serializing_if = "Vec::is_empty")]
        pub changed: Vec<OwnedUserId>,

        /// List of users who no longer share encrypted rooms since the previous sync
        /// response.
        #[serde(default, skip_serializing_if = "Vec::is_empty")]
        pub left: Vec<OwnedUserId>,
    }

    #[cfg(feature = "unstable-msc3202")]
    impl DeviceLists {
        /// Creates an empty `DeviceLists`.
        pub fn new() -> Self {
            Default::default()
        }

        /// Returns true if there are no device list updates.
        pub fn is_empty(&self) -> bool {
            self.changed.is_empty() && self.left.is_empty()
        }
    }

    #[cfg(feature = "server")]
    #[cfg(test)]
    mod tests {
        use ruma_common::api::{OutgoingRequest, SendAccessToken};
        use serde_json::json;

        use super::Request;

        #[test]
        fn decode_request_contains_events_field() {
            let dummy_event = serde_json::from_value(json!({
                "type": "m.room.message",
                "event_id": "$143273582443PhrSn:example.com",
                "origin_server_ts": 1,
                "room_id": "!roomid:room.com",
                "sender": "@user:example.com",
                "content": {
                    "body": "test",
                    "msgtype": "m.text",
                },
            }))
            .unwrap();
            let events = vec![dummy_event];

            let req = Request::new("any_txn_id".into(), &events)
                .try_into_http_request::<Vec<u8>>(
                    "https://homeserver.tld",
                    SendAccessToken::IfRequired("auth_tok"),
                    &[ruma_common::api::MatrixVersion::V1_1],
                )
                .unwrap();
            let json_body: serde_json::Value = serde_json::from_slice(req.body()).unwrap();

            assert_eq!(
                1,
                json_body.as_object().unwrap().get("events").unwrap().as_array().unwrap().len()
            );
        }
    }
}
<commit_msg>appservice: Move msc2409 types from push_events to push_events::v1<commit_after>//! `PUT /_matrix/app/*/transactions/{txnId}`
//!
//! Endpoint to push an event (or batch of events) to the application service.

pub mod v1 {
    //! `/v1/` ([spec])
    //!
    //! [spec]: https://spec.matrix.org/v1.4/application-service-api/#put_matrixappv1transactionstxnid

    #[cfg(any(feature = "unstable-msc2409", feature = "unstable-msc3202"))]
    use std::collections::BTreeMap;

    #[cfg(any(feature = "unstable-msc2409", feature = "unstable-msc3202"))]
    use js_int::UInt;
    #[cfg(feature = "unstable-msc2409")]
    use ruma_common::events::AnyToDeviceEvent;
    #[cfg(any(feature = "unstable-msc2409", feature = "unstable-msc3202"))]
    use ruma_common::OwnedUserId;
    use ruma_common::{
        api::ruma_api, events::AnyTimelineEvent, serde::Raw, OwnedTransactionId, TransactionId,
    };
    #[cfg(feature = "unstable-msc2409")]
    use ruma_common::{
        events::receipt::Receipt, presence::PresenceState, serde::from_raw_json_value,
        OwnedEventId, OwnedRoomId,
    };
    #[cfg(feature = "unstable-msc3202")]
    use ruma_common::{DeviceKeyAlgorithm, OwnedDeviceId};
    #[cfg(feature = "unstable-msc2409")]
    use serde::Deserializer;
    #[cfg(any(feature = "unstable-msc2409", feature = "unstable-msc3202"))]
    use serde::{Deserialize, Serialize};
    #[cfg(feature = "unstable-msc2409")]
    use serde_json::{value::RawValue as RawJsonValue, Value as JsonValue};

    ruma_api! {
        metadata: {
            description: "This API is called by the homeserver when it wants to push an event (or batch of events) to the application service.",
            method: PUT,
            name: "push_events",
            stable_path: "/_matrix/app/v1/transactions/:txn_id",
            rate_limited: false,
            authentication: AccessToken,
            added: 1.0,
        }

        request: {
            /// The transaction ID for this set of events.
            ///
            /// Homeservers generate these IDs and they are used to ensure idempotency of results.
            #[ruma_api(path)]
            pub txn_id: &'a TransactionId,

            /// A list of events.
            pub events: &'a [Raw<AnyTimelineEvent>],

            /// Information on E2E device updates.
            #[cfg(feature = "unstable-msc3202")]
            #[serde(
                default,
                skip_serializing_if = "DeviceLists::is_empty",
                rename = "org.matrix.msc3202.device_lists"
            )]
            pub device_lists: DeviceLists,

            /// The number of unclaimed one-time keys currently held on the server for this device, for each algorithm.
            #[cfg(feature = "unstable-msc3202")]
            #[serde(
                default,
                skip_serializing_if = "BTreeMap::is_empty",
                rename = "org.matrix.msc3202.device_one_time_keys_count"
            )]
            pub device_one_time_keys_count: BTreeMap<OwnedUserId, BTreeMap<OwnedDeviceId, BTreeMap<DeviceKeyAlgorithm, UInt>>>,

            /// A list of key algorithms for which the server has an unused fallback key for the device.
            #[cfg(feature = "unstable-msc3202")]
            #[serde(
                default,
                skip_serializing_if = "BTreeMap::is_empty",
                rename = "org.matrix.msc3202.device_unused_fallback_key_types"
            )]
            pub device_unused_fallback_key_types: BTreeMap<OwnedUserId, BTreeMap<OwnedDeviceId, Vec<DeviceKeyAlgorithm>>>,

            /// A list of EDUs.
            #[cfg(feature = "unstable-msc2409")]
            #[serde(
                default,
                skip_serializing_if = "<[_]>::is_empty",
                rename = "de.sorunome.msc2409.ephemeral"
            )]
            pub ephemeral: &'a [Edu],

            /// A list of to-device messages.
            #[cfg(feature = "unstable-msc2409")]
            #[serde(
                default,
                skip_serializing_if = "<[_]>::is_empty",
                rename = "de.sorunome.msc2409.to_device"
            )]
            pub to_device: &'a [Raw<AnyToDeviceEvent>]
        }

        #[derive(Default)]
        response: {}
    }

    impl<'a> Request<'a> {
        /// Creates a new `Request` with the given transaction ID and list of events.
        pub fn new(txn_id: &'a TransactionId, events: &'a [Raw<AnyTimelineEvent>]) -> Self {
            Self {
                txn_id,
                events,
                #[cfg(feature = "unstable-msc3202")]
                device_lists: DeviceLists::new(),
                #[cfg(feature = "unstable-msc3202")]
                device_one_time_keys_count: BTreeMap::new(),
                #[cfg(feature = "unstable-msc3202")]
                device_unused_fallback_key_types: BTreeMap::new(),
                #[cfg(feature = "unstable-msc2409")]
                ephemeral: &[],
                #[cfg(feature = "unstable-msc2409")]
                to_device: &[],
            }
        }
    }

    impl IncomingRequest {
        /// Creates an `IncomingRequest` with the given transaction ID and list of events.
        pub fn new(
            txn_id: OwnedTransactionId,
            events: Vec<Raw<AnyTimelineEvent>>,
        ) -> IncomingRequest {
            IncomingRequest {
                txn_id,
                events,
                #[cfg(feature = "unstable-msc3202")]
                device_lists: DeviceLists::new(),
                #[cfg(feature = "unstable-msc3202")]
                device_one_time_keys_count: BTreeMap::new(),
                #[cfg(feature = "unstable-msc3202")]
                device_unused_fallback_key_types: BTreeMap::new(),
                #[cfg(feature = "unstable-msc2409")]
                ephemeral: Vec::new(),
                #[cfg(feature = "unstable-msc2409")]
                to_device: Vec::new(),
            }
        }
    }

    impl Response {
        /// Creates an empty `Response`.
        pub fn new() -> Self {
            Self {}
        }
    }

    /// Information on E2E device updates.
    #[derive(Clone, Debug, Default, Deserialize, Serialize)]
    #[cfg_attr(not(feature = "unstable-exhaustive-types"), non_exhaustive)]
    #[cfg(feature = "unstable-msc3202")]
    pub struct DeviceLists {
        /// List of users who have updated their device identity keys or who now
        /// share an encrypted room with the client since the previous sync.
        #[serde(default, skip_serializing_if = "Vec::is_empty")]
        pub changed: Vec<OwnedUserId>,

        /// List of users who no longer share encrypted rooms since the previous sync
        /// response.
        #[serde(default, skip_serializing_if = "Vec::is_empty")]
        pub left: Vec<OwnedUserId>,
    }

    #[cfg(feature = "unstable-msc3202")]
    impl DeviceLists {
        /// Creates an empty `DeviceLists`.
        pub fn new() -> Self {
            Default::default()
        }

        /// Returns true if there are no device list updates.
        pub fn is_empty(&self) -> bool {
            self.changed.is_empty() && self.left.is_empty()
        }
    }

    /// Type for passing ephemeral data to homeservers.
    #[cfg(feature = "unstable-msc2409")]
    #[derive(Clone, Debug, Serialize)]
    #[non_exhaustive]
    pub enum Edu {
        /// An EDU representing presence updates for users of the sending homeserver.
        Presence(PresenceContent),

        /// An EDU representing receipt updates for users of the sending homeserver.
        Receipt(ReceiptContent),

        /// A typing notification EDU for a user in a room.
        Typing(TypingContent),

        #[doc(hidden)]
        #[serde(skip)]
        _Custom(JsonValue),
    }

    #[derive(Debug, Deserialize)]
    #[cfg(feature = "unstable-msc2409")]
    struct EduDeHelper {
        /// The message type field
        r#type: String,
        content: Box<RawJsonValue>,
    }

    #[cfg(feature = "unstable-msc2409")]
    impl<'de> Deserialize<'de> for Edu {
        fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
        where
            D: Deserializer<'de>,
        {
            let json = Box::<RawJsonValue>::deserialize(deserializer)?;
            let EduDeHelper { r#type, content } = from_raw_json_value(&json)?;

            Ok(match r#type.as_ref() {
                "m.presence" => Self::Presence(from_raw_json_value(&content)?),
                "m.receipt" => Self::Receipt(from_raw_json_value(&content)?),
                "m.typing" => Self::Typing(from_raw_json_value(&content)?),
                _ => Self::_Custom(from_raw_json_value(&content)?),
            })
        }
    }

    /// The content for "m.presence" Edu.
    #[cfg(feature = "unstable-msc2409")]
    #[derive(Clone, Debug, Deserialize, Serialize)]
    #[cfg_attr(not(feature = "unstable-exhaustive-types"), non_exhaustive)]
    pub struct PresenceContent {
        /// A list of presence updates that the receiving server is likely to be interested in.
        pub push: Vec<PresenceUpdate>,
    }

    #[cfg(feature = "unstable-msc2409")]
    impl PresenceContent {
        /// Creates a new `PresenceContent`.
        pub fn new(push: Vec<PresenceUpdate>) -> Self {
            Self { push }
        }
    }

    /// An update to the presence of a user.
    #[cfg(feature = "unstable-msc2409")]
    #[derive(Clone, Debug, Deserialize, Serialize)]
    #[cfg_attr(not(feature = "unstable-exhaustive-types"), non_exhaustive)]
    pub struct PresenceUpdate {
        /// The user ID this presence EDU is for.
        pub user_id: OwnedUserId,

        /// The presence of the user.
        pub presence: PresenceState,

        /// An optional description to accompany the presence.
        #[serde(skip_serializing_if = "Option::is_none")]
        pub status_msg: Option<String>,

        /// The number of milliseconds that have elapsed since the user last did something.
        pub last_active_ago: UInt,

        /// Whether or not the user is currently active.
        ///
        /// Defaults to false.
        #[serde(default, skip_serializing_if = "ruma_common::serde::is_default")]
        pub currently_active: bool,
    }

    #[cfg(feature = "unstable-msc2409")]
    impl PresenceUpdate {
        /// Creates a new `PresenceUpdate` with the given `user_id`, `presence` and `last_activity`.
        pub fn new(user_id: OwnedUserId, presence: PresenceState, last_activity: UInt) -> Self {
            Self {
                user_id,
                presence,
                last_active_ago: last_activity,
                status_msg: None,
                currently_active: false,
            }
        }
    }

    /// The content for "m.receipt" Edu.
    #[cfg(feature = "unstable-msc2409")]
    #[derive(Clone, Debug, Deserialize, Serialize)]
    #[cfg_attr(not(feature = "unstable-exhaustive-types"), non_exhaustive)]
    #[serde(transparent)]
    pub struct ReceiptContent(pub BTreeMap<OwnedRoomId, ReceiptMap>);

    #[cfg(feature = "unstable-msc2409")]
    impl ReceiptContent {
        /// Creates a new `ReceiptContent`.
        pub fn new(receipts: BTreeMap<OwnedRoomId, ReceiptMap>) -> Self {
            Self(receipts)
        }
    }

    /// Mapping between user and `ReceiptData`.
    #[cfg(feature = "unstable-msc2409")]
    #[derive(Clone, Debug, Deserialize, Serialize)]
    #[cfg_attr(not(feature = "unstable-exhaustive-types"), non_exhaustive)]
    pub struct ReceiptMap {
        /// Read receipts for users in the room.
        #[serde(rename = "m.read")]
        pub read: BTreeMap<OwnedUserId, ReceiptData>,
    }

    #[cfg(feature = "unstable-msc2409")]
    impl ReceiptMap {
        /// Creates a new `ReceiptMap`.
        pub fn new(read: BTreeMap<OwnedUserId, ReceiptData>) -> Self {
            Self { read }
        }
    }

    /// Metadata about the event that was last read and when.
    #[cfg(feature = "unstable-msc2409")]
    #[derive(Clone, Debug, Deserialize, Serialize)]
    #[cfg_attr(not(feature = "unstable-exhaustive-types"), non_exhaustive)]
    pub struct ReceiptData {
        /// Metadata for the read receipt.
        pub data: Receipt,

        /// The extremity event ID the user has read up to.
        pub event_ids: Vec<OwnedEventId>,
    }

    #[cfg(feature = "unstable-msc2409")]
    impl ReceiptData {
        /// Creates a new `ReceiptData`.
        pub fn new(data: Receipt, event_ids: Vec<OwnedEventId>) -> Self {
            Self { data, event_ids }
        }
    }

    /// The content for "m.typing" Edu.
    #[cfg(feature = "unstable-msc2409")]
    #[derive(Clone, Debug, Deserialize, Serialize)]
    #[cfg_attr(not(feature = "unstable-exhaustive-types"), non_exhaustive)]
    pub struct TypingContent {
        /// The room where the user's typing status has been updated.
        pub room_id: OwnedRoomId,

        /// The user ID that has had their typing status changed.
        pub user_id: OwnedUserId,

        /// Whether the user is typing in the room or not.
        pub typing: bool,
    }

    #[cfg(feature = "unstable-msc2409")]
    impl TypingContent {
        /// Creates a new `TypingContent`.
        pub fn new(room_id: OwnedRoomId, user_id: OwnedUserId, typing: bool) -> Self {
            Self { room_id, user_id, typing }
        }
    }

    #[cfg(feature = "server")]
    #[cfg(test)]
    mod tests {
        use ruma_common::api::{OutgoingRequest, SendAccessToken};
        use serde_json::json;

        use super::Request;

        #[test]
        fn decode_request_contains_events_field() {
            let dummy_event = serde_json::from_value(json!({
                "type": "m.room.message",
                "event_id": "$143273582443PhrSn:example.com",
                "origin_server_ts": 1,
                "room_id": "!roomid:room.com",
                "sender": "@user:example.com",
                "content": {
                    "body": "test",
                    "msgtype": "m.text",
                },
            }))
            .unwrap();
            let events = vec![dummy_event];

            let req = Request::new("any_txn_id".into(), &events)
                .try_into_http_request::<Vec<u8>>(
                    "https://homeserver.tld",
                    SendAccessToken::IfRequired("auth_tok"),
                    &[ruma_common::api::MatrixVersion::V1_1],
                )
                .unwrap();
            let json_body: serde_json::Value = serde_json::from_slice(req.body()).unwrap();

            assert_eq!(
                1,
                json_body.as_object().unwrap().get("events").unwrap().as_array().unwrap().len()
            );
        }
    }
}
<|endoftext|>


<commit_before>use data::{Asn1Seq, Asn1SeqField};
use parse::{asn1_type_name, asn1_type};
use parse::space::{skip_other};

named!(pub asn1_seq_field <Asn1SeqField>, chain!(
  skip_other? ~
  name: asn1_type_name ~
  skip_other? ~
  asn1_type: asn1_type,
  || Asn1SeqField {
    name: name,
    asn1_type: asn1_type,
  }
));

named!(pub asn1_seq <Asn1Seq>, chain!(
  tag!("SEQUENCE") ~
  skip_other? ~
  fields: delimited!(
    tag!("{"),
    separated_list!(
      chain!(skip_other? ~ tag!(","), || ()),
      asn1_seq_field
    ),
    tuple!(opt!(skip_other), tag!("}"))
  ),
  || Asn1Seq {
    fields: fields,
  }
));

#[test]
fn test_asn1_sequence_field() {
  let field1 = Asn1SeqField {
    name: "foo".into(),
    asn1_type: ::data::Asn1Type::Type("Bar".into()),
  };
  let field2 = Asn1SeqField {
    name: "asdf".into(),
    asn1_type: ::data::Asn1Type::Type("INTEGER".into()),
  };
  assert_eq!(
    field1,
    asn1_seq_field("foo Bar".as_bytes()).unwrap().1
  );
  assert_eq!(
    field2,
    asn1_seq_field("asdf INTEGER,".as_bytes()).unwrap().1
  );
  assert_eq!(
    field1,
    asn1_seq_field("foo--test\n Bar".as_bytes()).unwrap().1
  );
}

#[test]
fn test_seq_fields() {
  let seq = Asn1Seq {
    fields: vec![
      Asn1SeqField {
        name: "foo".into(),
        asn1_type: ::data::Asn1Type::Type("Bar".into()),
      },
      Asn1SeqField {
        name: "asdf".into(),
        asn1_type: ::data::Asn1Type::Type("INTEGER".into()),
      }
    ],
  };
  println!("{:#?}", asn1_seq("\
      SEQUENCE {\
        foo Bar,\
        asdf INTEGER\
      }\
    ".as_bytes()));
  assert_eq!(
    seq,
    asn1_seq("\
      SEQUENCE {\
        foo Bar,\
        asdf INTEGER\
      }\
    ".as_bytes()).unwrap().1
  );
}
<commit_msg>Improve sequence tests<commit_after>use data::{Asn1Seq, Asn1SeqField};
use parse::{asn1_type_name, asn1_type};
use parse::space::{skip_other};

named!(pub asn1_seq_field <Asn1SeqField>, chain!(
  skip_other? ~
  name: asn1_type_name ~
  skip_other? ~
  asn1_type: asn1_type,
  || Asn1SeqField {
    name: name,
    asn1_type: asn1_type,
  }
));

named!(pub asn1_seq <Asn1Seq>, chain!(
  tag!("SEQUENCE") ~
  skip_other? ~
  fields: delimited!(
    tag!("{"),
    separated_list!(
      chain!(skip_other? ~ tag!(","), || ()),
      asn1_seq_field
    ),
    tuple!(opt!(skip_other), tag!("}"))
  ),
  || Asn1Seq {
    fields: fields,
  }
));

#[test]
fn test_asn1_sequence_field() {
  let field1 = Asn1SeqField {
    name: "foo".into(),
    asn1_type: ::data::Asn1Type::Type("Bar".into()),
  };
  let field2 = Asn1SeqField {
    name: "asdf".into(),
    asn1_type: ::data::Asn1Type::Type("INTEGER".into()),
  };
  assert_eq!(
    field1,
    asn1_seq_field("foo Bar".as_bytes()).unwrap().1
  );
  assert_eq!(
    field2,
    asn1_seq_field("asdf INTEGER,".as_bytes()).unwrap().1
  );
  assert_eq!(
    field1,
    asn1_seq_field("foo--test\n Bar".as_bytes()).unwrap().1
  );
}

#[test]
fn test_seq_fields() {
  let seq = Asn1Seq {
    fields: vec![
      Asn1SeqField {
        name: "foo".into(),
        asn1_type: ::data::Asn1Type::Type("Bar".into()),
      },
      Asn1SeqField {
        name: "asdf".into(),
        asn1_type: ::data::Asn1Type::Type("INTEGER".into()),
      }
    ],
  };
  assert_eq!(
    seq,
    asn1_seq("\
      SEQUENCE {\
        foo Bar,\
        asdf INTEGER\
      }\
    ".as_bytes()).unwrap().1
  );
  assert_eq!(
    seq,
    asn1_seq("\
      SEQUENCE {
        foo Bar --,
        , asdf INTEGER
      }
    ".as_bytes()).unwrap().1
  );
  assert!(asn1_seq("SEQUENC ".as_bytes()).is_err());
}
<|endoftext|>


<commit_before>extern crate ssz_helpers;

use self::ssz_helpers::ssz_block::{
    SszBlock,
    SszBlockError,
};
use std::sync::Arc;
use super::{
    ClientDB,
    DBError,
};
use super::BLOCKS_DB_COLUMN as DB_COLUMN;

#[derive(Clone, Debug, PartialEq)]
pub enum BlockAtSlotError {
    UnknownBlock,
    InvalidBlock,
    DBError(String),
}

pub struct BlockStore<T>
    where T: ClientDB
{
    db: Arc<T>,
}

impl<T: ClientDB> BlockStore<T> {
    pub fn new(db: Arc<T>) -> Self {
        Self {
            db,
        }
    }

    pub fn put_serialized_block(&self, hash: &[u8], ssz: &[u8])
        -> Result<(), DBError>
    {
        self.db.put(DB_COLUMN, hash, ssz)
    }

    pub fn get_serialized_block(&self, hash: &[u8])
        -> Result<Option<Vec<u8>>, DBError>
    {
        self.db.get(DB_COLUMN, hash)
    }

    pub fn block_exists(&self, hash: &[u8])
        -> Result<bool, DBError>
    {
        self.db.exists(DB_COLUMN, hash)
    }

    pub fn block_exists_in_canonical_chain(&self, hash: &[u8])
        -> Result<bool, DBError>
    {
        // TODO: implement logic for canonical chain
        self.db.exists(DB_COLUMN, hash)
    }

    /// Retrieve the block at a slot given a "head_hash" and a slot.
    ///
    /// A "head_hash" must be a block with a slot number greater than or equal to the desired slot.
    ///
    /// This function will read each block down the chain until it finds a block with the given
    /// slot number. If the slot is skipped, the function will return None.
    pub fn block_at_slot(&self, head_hash: &[u8], slot: u64)
        -> Result<Option<Vec<u8>>, BlockAtSlotError>
    {
        match self.get_serialized_block(head_hash)? {
            None => Err(BlockAtSlotError::UnknownBlock),
            Some(ssz) => {
                let block = SszBlock::from_slice(&ssz)
                    .map_err(|_| BlockAtSlotError::InvalidBlock)?;
                match block.slot_number() {
                    s if s == slot => Ok(Some(ssz.to_vec())),
                    s if s < slot => Ok(None),
                    _ => self.block_at_slot(block.parent_hash(), slot)
                }
            }
        }
    }
}

impl From<DBError> for BlockAtSlotError {
    fn from(e: DBError) -> Self {
        BlockAtSlotError::DBError(e.message)
    }
}

#[cfg(test)]
mod tests {
    extern crate ssz;
    extern crate types;

    use self::types::block::Block;
    use self::types::attestation_record::AttestationRecord;
    use self::types::Hash256;
    use self::ssz::SszStream;

    use super::*;
    use super::super::super::MemoryDB;
    use std::thread;
    use std::sync::Arc;

    #[test]
    fn test_block_store_on_memory_db() {
        let db = Arc::new(MemoryDB::open());
        let bs = Arc::new(BlockStore::new(db.clone()));

        let thread_count = 10;
        let write_count = 10;

        // We're expecting the product of these numbers to fit in one byte.
        assert!(thread_count * write_count <= 255);

        let mut handles = vec![];
        for t in 0..thread_count {
            let wc = write_count;
            let bs = bs.clone();
            let handle = thread::spawn(move || {
                for w in 0..wc {
                    let key = (t * w) as u8;
                    let val = 42;
                    bs.put_serialized_block(&vec![key], &vec![val]).unwrap();
                }
            });
            handles.push(handle);
        }

        for handle in handles {
            handle.join().unwrap();
        }

        for t in 0..thread_count {
            for w in 0..write_count {
                let key = (t * w) as u8;
                assert!(bs.block_exists(&vec![key]).unwrap());
                let val = bs.get_serialized_block(&vec![key]).unwrap().unwrap();
                assert_eq!(vec![42], val);
            }
        }
    }

    #[test]
    fn test_block_at_slot() {
        let db = Arc::new(MemoryDB::open());
        let bs = Arc::new(BlockStore::new(db.clone()));

        let blocks = (0..5).into_iter()
            .map(|_| {
                let mut block = Block::zero();
                let ar = AttestationRecord::zero();
                block.attestations.push(ar);
                block
            });

        let hashes = [
            Hash256::from("zero".as_bytes()),
            Hash256::from("one".as_bytes()),
            Hash256::from("two".as_bytes()),
            Hash256::from("three".as_bytes()),
            Hash256::from("four".as_bytes()),
        ];

        let parent_hashes = [
            Hash256::from("genesis".as_bytes()),
            Hash256::from("zero".as_bytes()),
            Hash256::from("one".as_bytes()),
            Hash256::from("two".as_bytes()),
            Hash256::from("three".as_bytes()),
        ];

        let slots = [0, 1, 3, 4, 5];

        for (i, mut block) in blocks.enumerate() {
            block.parent_hash = parent_hashes[i];
            block.slot_number = slots[i];
            let mut s = SszStream::new();
            s.append(&block);
            let ssz = s.drain();
            bs.put_serialized_block(&hashes[i].to_vec(), &ssz).unwrap();
        }

        let ssz = bs.block_at_slot(&hashes[4], 5).unwrap().unwrap();
        let block = SszBlock::from_slice(&ssz).unwrap();
        assert_eq!(block.slot_number(), 5);

        let ssz = bs.block_at_slot(&hashes[4], 3).unwrap().unwrap();
        let block = SszBlock::from_slice(&ssz).unwrap();
        assert_eq!(block.slot_number(), 3);

        let ssz = bs.block_at_slot(&hashes[4], 0).unwrap().unwrap();
        let block = SszBlock::from_slice(&ssz).unwrap();
        assert_eq!(block.slot_number(), 0);

        let ssz = bs.block_at_slot(&hashes[4], 2).unwrap();
        assert_eq!(ssz, None);

        let ssz = bs.block_at_slot(&hashes[4], 6).unwrap();
        assert_eq!(ssz, None);
    }
}
<commit_msg>Return block hash with block_at_slot()<commit_after>extern crate ssz_helpers;

use self::ssz_helpers::ssz_block::{
    SszBlock,
    SszBlockError,
};
use std::sync::Arc;
use super::{
    ClientDB,
    DBError,
};
use super::BLOCKS_DB_COLUMN as DB_COLUMN;

#[derive(Clone, Debug, PartialEq)]
pub enum BlockAtSlotError {
    UnknownBlock,
    InvalidBlock,
    DBError(String),
}

pub struct BlockStore<T>
    where T: ClientDB
{
    db: Arc<T>,
}

impl<T: ClientDB> BlockStore<T> {
    pub fn new(db: Arc<T>) -> Self {
        Self {
            db,
        }
    }

    pub fn put_serialized_block(&self, hash: &[u8], ssz: &[u8])
        -> Result<(), DBError>
    {
        self.db.put(DB_COLUMN, hash, ssz)
    }

    pub fn get_serialized_block(&self, hash: &[u8])
        -> Result<Option<Vec<u8>>, DBError>
    {
        self.db.get(DB_COLUMN, hash)
    }

    pub fn block_exists(&self, hash: &[u8])
        -> Result<bool, DBError>
    {
        self.db.exists(DB_COLUMN, hash)
    }

    pub fn block_exists_in_canonical_chain(&self, hash: &[u8])
        -> Result<bool, DBError>
    {
        // TODO: implement logic for canonical chain
        self.db.exists(DB_COLUMN, hash)
    }

    /// Retrieve the block at a slot given a "head_hash" and a slot.
    ///
    /// A "head_hash" must be a block hash with a slot number greater than or equal to the desired
    /// slot.
    ///
    /// This function will read each block down the chain until it finds a block with the given
    /// slot number. If the slot is skipped, the function will return None.
    ///
    /// If a block is found, a tuple of (block_hash, serialized_block) is returned.
    pub fn block_at_slot(&self, head_hash: &[u8], slot: u64)
        -> Result<Option<(Vec<u8>, Vec<u8>)>, BlockAtSlotError>
    {
        match self.get_serialized_block(head_hash)? {
            None => Err(BlockAtSlotError::UnknownBlock),
            Some(ssz) => {
                let block = SszBlock::from_slice(&ssz)
                    .map_err(|_| BlockAtSlotError::InvalidBlock)?;
                match block.slot_number() {
                    s if s == slot => Ok(Some((head_hash.to_vec(), ssz.to_vec()))),
                    s if s < slot => Ok(None),
                    _ => self.block_at_slot(block.parent_hash(), slot)
                }
            }
        }
    }
}

impl From<DBError> for BlockAtSlotError {
    fn from(e: DBError) -> Self {
        BlockAtSlotError::DBError(e.message)
    }
}

#[cfg(test)]
mod tests {
    extern crate ssz;
    extern crate types;

    use self::types::block::Block;
    use self::types::attestation_record::AttestationRecord;
    use self::types::Hash256;
    use self::ssz::SszStream;

    use super::*;
    use super::super::super::MemoryDB;
    use std::thread;
    use std::sync::Arc;

    #[test]
    fn test_block_store_on_memory_db() {
        let db = Arc::new(MemoryDB::open());
        let bs = Arc::new(BlockStore::new(db.clone()));

        let thread_count = 10;
        let write_count = 10;

        // We're expecting the product of these numbers to fit in one byte.
        assert!(thread_count * write_count <= 255);

        let mut handles = vec![];
        for t in 0..thread_count {
            let wc = write_count;
            let bs = bs.clone();
            let handle = thread::spawn(move || {
                for w in 0..wc {
                    let key = (t * w) as u8;
                    let val = 42;
                    bs.put_serialized_block(&vec![key], &vec![val]).unwrap();
                }
            });
            handles.push(handle);
        }

        for handle in handles {
            handle.join().unwrap();
        }

        for t in 0..thread_count {
            for w in 0..write_count {
                let key = (t * w) as u8;
                assert!(bs.block_exists(&vec![key]).unwrap());
                let val = bs.get_serialized_block(&vec![key]).unwrap().unwrap();
                assert_eq!(vec![42], val);
            }
        }
    }

    #[test]
    fn test_block_at_slot() {
        let db = Arc::new(MemoryDB::open());
        let bs = Arc::new(BlockStore::new(db.clone()));

        let blocks = (0..5).into_iter()
            .map(|_| {
                let mut block = Block::zero();
                let ar = AttestationRecord::zero();
                block.attestations.push(ar);
                block
            });

        let hashes = [
            Hash256::from("zero".as_bytes()),
            Hash256::from("one".as_bytes()),
            Hash256::from("two".as_bytes()),
            Hash256::from("three".as_bytes()),
            Hash256::from("four".as_bytes()),
        ];

        let parent_hashes = [
            Hash256::from("genesis".as_bytes()),
            Hash256::from("zero".as_bytes()),
            Hash256::from("one".as_bytes()),
            Hash256::from("two".as_bytes()),
            Hash256::from("three".as_bytes()),
        ];

        let slots = [0, 1, 3, 4, 5];

        for (i, mut block) in blocks.enumerate() {
            block.parent_hash = parent_hashes[i];
            block.slot_number = slots[i];
            let mut s = SszStream::new();
            s.append(&block);
            let ssz = s.drain();
            bs.put_serialized_block(&hashes[i].to_vec(), &ssz).unwrap();
        }

        let tuple = bs.block_at_slot(&hashes[4], 5).unwrap().unwrap();
        let block = SszBlock::from_slice(&tuple.1).unwrap();
        assert_eq!(block.slot_number(), 5);
        assert_eq!(tuple.0, hashes[4].to_vec());

        let tuple = bs.block_at_slot(&hashes[4], 4).unwrap().unwrap();
        let block = SszBlock::from_slice(&tuple.1).unwrap();
        assert_eq!(block.slot_number(), 4);
        assert_eq!(tuple.0, hashes[3].to_vec());

        let tuple = bs.block_at_slot(&hashes[4], 3).unwrap().unwrap();
        let block = SszBlock::from_slice(&tuple.1).unwrap();
        assert_eq!(block.slot_number(), 3);
        assert_eq!(tuple.0, hashes[2].to_vec());

        let tuple = bs.block_at_slot(&hashes[4], 0).unwrap().unwrap();
        let block = SszBlock::from_slice(&tuple.1).unwrap();
        assert_eq!(block.slot_number(), 0);
        assert_eq!(tuple.0, hashes[0].to_vec());

        let ssz = bs.block_at_slot(&hashes[4], 2).unwrap();
        assert_eq!(ssz, None);

        let ssz = bs.block_at_slot(&hashes[4], 6).unwrap();
        assert_eq!(ssz, None);
    }
}
<|endoftext|>


<commit_before>//! Eigenvalue decomposition for general matrices

use crate::{error::*, layout::MatrixLayout, *};
use cauchy::*;
use num_traits::{ToPrimitive, Zero};

/// Wraps `*geev` for general matrices
pub trait Eig_: Scalar {
    /// Calculate Right eigenvalue
    fn eig(
        calc_v: bool,
        l: MatrixLayout,
        a: &mut [Self],
    ) -> Result<(Vec<Self::Complex>, Vec<Self::Complex>)>;
}

macro_rules! impl_eig_complex {
    ($scalar:ty, $ev:path) => {
        impl Eig_ for $scalar {
            fn eig(
                calc_v: bool,
                l: MatrixLayout,
                mut a: &mut [Self],
            ) -> Result<(Vec<Self::Complex>, Vec<Self::Complex>)> {
                let (n, _) = l.size();
                // Because LAPACK assumes F-continious array, C-continious array should be taken Hermitian conjugate.
                // However, we utilize a fact that left eigenvector of A^H corresponds to the right eigenvector of A
                let (jobvl, jobvr) = if calc_v {
                    match l {
                        MatrixLayout::C { .. } => (b'V', b'N'),
                        MatrixLayout::F { .. } => (b'N', b'V'),
                    }
                } else {
                    (b'N', b'N')
                };
                let mut eigs = unsafe { vec_uninit(n as usize) };
                let mut rwork = unsafe { vec_uninit(2 * n as usize) };

                let mut vl = if jobvl == b'V' {
                    Some(unsafe { vec_uninit((n * n) as usize) })
                } else {
                    None
                };
                let mut vr = if jobvr == b'V' {
                    Some(unsafe { vec_uninit((n * n) as usize) })
                } else {
                    None
                };

                // calc work size
                let mut info = 0;
                let mut work_size = [Self::zero()];
                unsafe {
                    $ev(
                        jobvl,
                        jobvr,
                        n,
                        &mut a,
                        n,
                        &mut eigs,
                        &mut vl.as_mut().map(|v| v.as_mut_slice()).unwrap_or(&mut []),
                        n,
                        &mut vr.as_mut().map(|v| v.as_mut_slice()).unwrap_or(&mut []),
                        n,
                        &mut work_size,
                        -1,
                        &mut rwork,
                        &mut info,
                    )
                };
                info.as_lapack_result()?;

                // actal ev
                let lwork = work_size[0].to_usize().unwrap();
                let mut work = unsafe { vec_uninit(lwork) };
                unsafe {
                    $ev(
                        jobvl,
                        jobvr,
                        n,
                        &mut a,
                        n,
                        &mut eigs,
                        &mut vl.as_mut().map(|v| v.as_mut_slice()).unwrap_or(&mut []),
                        n,
                        &mut vr.as_mut().map(|v| v.as_mut_slice()).unwrap_or(&mut []),
                        n,
                        &mut work,
                        lwork as i32,
                        &mut rwork,
                        &mut info,
                    )
                };
                info.as_lapack_result()?;

                // Hermite conjugate
                if jobvl == b'V' {
                    for c in vl.as_mut().unwrap().iter_mut() {
                        c.im = -c.im
                    }
                }

                Ok((eigs, vr.or(vl).unwrap_or(Vec::new())))
            }
        }
    };
}

impl_eig_complex!(c64, lapack::zgeev);
impl_eig_complex!(c32, lapack::cgeev);

macro_rules! impl_eig_real {
    ($scalar:ty, $ev:path) => {
        impl Eig_ for $scalar {
            fn eig(
                calc_v: bool,
                l: MatrixLayout,
                mut a: &mut [Self],
            ) -> Result<(Vec<Self::Complex>, Vec<Self::Complex>)> {
                let (n, _) = l.size();
                // Because LAPACK assumes F-continious array, C-continious array should be taken Hermitian conjugate.
                // However, we utilize a fact that left eigenvector of A^H corresponds to the right eigenvector of A
                let (jobvl, jobvr) = if calc_v {
                    match l {
                        MatrixLayout::C { .. } => (b'V', b'N'),
                        MatrixLayout::F { .. } => (b'N', b'V'),
                    }
                } else {
                    (b'N', b'N')
                };
                let mut eig_re = unsafe { vec_uninit(n as usize) };
                let mut eig_im = unsafe { vec_uninit(n as usize) };

                let mut vl = if jobvl == b'V' {
                    Some(unsafe { vec_uninit((n * n) as usize) })
                } else {
                    None
                };
                let mut vr = if jobvr == b'V' {
                    Some(unsafe { vec_uninit((n * n) as usize) })
                } else {
                    None
                };

                // calc work size
                let mut info = 0;
                let mut work_size = [0.0];
                unsafe {
                    $ev(
                        jobvl,
                        jobvr,
                        n,
                        &mut a,
                        n,
                        &mut eig_re,
                        &mut eig_im,
                        vl.as_mut().map(|v| v.as_mut_slice()).unwrap_or(&mut []),
                        n,
                        vr.as_mut().map(|v| v.as_mut_slice()).unwrap_or(&mut []),
                        n,
                        &mut work_size,
                        -1,
                        &mut info,
                    )
                };
                info.as_lapack_result()?;

                // actual ev
                let lwork = work_size[0].to_usize().unwrap();
                let mut work = unsafe { vec_uninit(lwork) };
                unsafe {
                    $ev(
                        jobvl,
                        jobvr,
                        n,
                        &mut a,
                        n,
                        &mut eig_re,
                        &mut eig_im,
                        vl.as_mut().map(|v| v.as_mut_slice()).unwrap_or(&mut []),
                        n,
                        vr.as_mut().map(|v| v.as_mut_slice()).unwrap_or(&mut []),
                        n,
                        &mut work,
                        lwork as i32,
                        &mut info,
                    )
                };
                info.as_lapack_result()?;

                // reconstruct eigenvalues
                let eigs: Vec<Self::Complex> = eig_re
                    .iter()
                    .zip(eig_im.iter())
                    .map(|(&re, &im)| Self::complex(re, im))
                    .collect();

                if !calc_v {
                    return Ok((eigs, Vec::new()));
                }

                // Reconstruct eigenvectors into complex-array
                // --------------------------------------------
                //
                // From LAPACK API https://software.intel.com/en-us/node/469230
                //
                // - If the j-th eigenvalue is real,
                //   - v(j) = VR(:,j), the j-th column of VR.
                //
                // - If the j-th and (j+1)-st eigenvalues form a complex conjugate pair,
                //   - v(j)   = VR(:,j) + i*VR(:,j+1)
                //   - v(j+1) = VR(:,j) - i*VR(:,j+1).
                //
                // ```
                //  j ->         <----pair---->  <----pair---->
                // [ ... (real), (imag), (imag), (imag), (imag), ... ] : eigs
                //       ^       ^       ^       ^       ^
                //       false   false   true    false   true          : is_conjugate_pair
                // ```
                let n = n as usize;
                let v = vr.or(vl).unwrap();
                let mut eigvecs = unsafe { vec_uninit(n * n) };
                let mut is_conjugate_pair = false; // flag for check `j` is complex conjugate
                for j in 0..n {
                    if eig_im[j] == 0.0 {
                        // j-th eigenvalue is real
                        for i in 0..n {
                            eigvecs[i + j * n] = Self::complex(v[i + j * n], 0.0);
                        }
                    } else {
                        // j-th eigenvalue is complex
                        // complex conjugated pair can be `j-1` or `j+1`
                        if is_conjugate_pair {
                            let j_pair = j - 1;
                            assert!(j_pair < n);
                            for i in 0..n {
                                eigvecs[i + j * n] = Self::complex(v[i + j_pair * n], v[i + j * n]);
                            }
                        } else {
                            let j_pair = j + 1;
                            assert!(j_pair < n);
                            for i in 0..n {
                                eigvecs[i + j * n] =
                                    Self::complex(v[i + j * n], -v[i + j_pair * n]);
                            }
                        }
                        is_conjugate_pair = !is_conjugate_pair;
                    }
                }

                Ok((eigs, eigvecs))
            }
        }
    };
}

impl_eig_real!(f64, lapack::dgeev);
impl_eig_real!(f32, lapack::sgeev);
<commit_msg>Fix eig for column-major arrays with real elements<commit_after>//! Eigenvalue decomposition for general matrices

use crate::{error::*, layout::MatrixLayout, *};
use cauchy::*;
use num_traits::{ToPrimitive, Zero};

/// Wraps `*geev` for general matrices
pub trait Eig_: Scalar {
    /// Calculate Right eigenvalue
    fn eig(
        calc_v: bool,
        l: MatrixLayout,
        a: &mut [Self],
    ) -> Result<(Vec<Self::Complex>, Vec<Self::Complex>)>;
}

macro_rules! impl_eig_complex {
    ($scalar:ty, $ev:path) => {
        impl Eig_ for $scalar {
            fn eig(
                calc_v: bool,
                l: MatrixLayout,
                mut a: &mut [Self],
            ) -> Result<(Vec<Self::Complex>, Vec<Self::Complex>)> {
                let (n, _) = l.size();
                // LAPACK assumes a column-major input. A row-major input can
                // be interpreted as the transpose of a column-major input. So,
                // for row-major inputs, we we want to solve the following,
                // given the column-major input `A`:
                //
                //   A^T V = V Λ ⟺ V^T A = Λ V^T ⟺ conj(V)^H A = Λ conj(V)^H
                //
                // So, in this case, the right eigenvectors are the conjugates
                // of the left eigenvectors computed with `A`, and the
                // eigenvalues are the eigenvalues computed with `A`.
                let (jobvl, jobvr) = if calc_v {
                    match l {
                        MatrixLayout::C { .. } => (b'V', b'N'),
                        MatrixLayout::F { .. } => (b'N', b'V'),
                    }
                } else {
                    (b'N', b'N')
                };
                let mut eigs = unsafe { vec_uninit(n as usize) };
                let mut rwork = unsafe { vec_uninit(2 * n as usize) };

                let mut vl = if jobvl == b'V' {
                    Some(unsafe { vec_uninit((n * n) as usize) })
                } else {
                    None
                };
                let mut vr = if jobvr == b'V' {
                    Some(unsafe { vec_uninit((n * n) as usize) })
                } else {
                    None
                };

                // calc work size
                let mut info = 0;
                let mut work_size = [Self::zero()];
                unsafe {
                    $ev(
                        jobvl,
                        jobvr,
                        n,
                        &mut a,
                        n,
                        &mut eigs,
                        &mut vl.as_mut().map(|v| v.as_mut_slice()).unwrap_or(&mut []),
                        n,
                        &mut vr.as_mut().map(|v| v.as_mut_slice()).unwrap_or(&mut []),
                        n,
                        &mut work_size,
                        -1,
                        &mut rwork,
                        &mut info,
                    )
                };
                info.as_lapack_result()?;

                // actal ev
                let lwork = work_size[0].to_usize().unwrap();
                let mut work = unsafe { vec_uninit(lwork) };
                unsafe {
                    $ev(
                        jobvl,
                        jobvr,
                        n,
                        &mut a,
                        n,
                        &mut eigs,
                        &mut vl.as_mut().map(|v| v.as_mut_slice()).unwrap_or(&mut []),
                        n,
                        &mut vr.as_mut().map(|v| v.as_mut_slice()).unwrap_or(&mut []),
                        n,
                        &mut work,
                        lwork as i32,
                        &mut rwork,
                        &mut info,
                    )
                };
                info.as_lapack_result()?;

                // Hermite conjugate
                if jobvl == b'V' {
                    for c in vl.as_mut().unwrap().iter_mut() {
                        c.im = -c.im
                    }
                }

                Ok((eigs, vr.or(vl).unwrap_or(Vec::new())))
            }
        }
    };
}

impl_eig_complex!(c64, lapack::zgeev);
impl_eig_complex!(c32, lapack::cgeev);

macro_rules! impl_eig_real {
    ($scalar:ty, $ev:path) => {
        impl Eig_ for $scalar {
            fn eig(
                calc_v: bool,
                l: MatrixLayout,
                mut a: &mut [Self],
            ) -> Result<(Vec<Self::Complex>, Vec<Self::Complex>)> {
                let (n, _) = l.size();
                // LAPACK assumes a column-major input. A row-major input can
                // be interpreted as the transpose of a column-major input. So,
                // for row-major inputs, we we want to solve the following,
                // given the column-major input `A`:
                //
                //   A^T V = V Λ ⟺ V^T A = Λ V^T ⟺ conj(V)^H A = Λ conj(V)^H
                //
                // So, in this case, the right eigenvectors are the conjugates
                // of the left eigenvectors computed with `A`, and the
                // eigenvalues are the eigenvalues computed with `A`.
                //
                // We could conjugate the eigenvalues instead of the
                // eigenvectors, but we have to reconstruct the eigenvectors
                // into new matrices anyway, and by not modifying the
                // eigenvalues, we preserve the nice ordering specified by
                // `sgeev`/`dgeev`.
                let (jobvl, jobvr) = if calc_v {
                    match l {
                        MatrixLayout::C { .. } => (b'V', b'N'),
                        MatrixLayout::F { .. } => (b'N', b'V'),
                    }
                } else {
                    (b'N', b'N')
                };
                let mut eig_re = unsafe { vec_uninit(n as usize) };
                let mut eig_im = unsafe { vec_uninit(n as usize) };

                let mut vl = if jobvl == b'V' {
                    Some(unsafe { vec_uninit((n * n) as usize) })
                } else {
                    None
                };
                let mut vr = if jobvr == b'V' {
                    Some(unsafe { vec_uninit((n * n) as usize) })
                } else {
                    None
                };

                // calc work size
                let mut info = 0;
                let mut work_size = [0.0];
                unsafe {
                    $ev(
                        jobvl,
                        jobvr,
                        n,
                        &mut a,
                        n,
                        &mut eig_re,
                        &mut eig_im,
                        vl.as_mut().map(|v| v.as_mut_slice()).unwrap_or(&mut []),
                        n,
                        vr.as_mut().map(|v| v.as_mut_slice()).unwrap_or(&mut []),
                        n,
                        &mut work_size,
                        -1,
                        &mut info,
                    )
                };
                info.as_lapack_result()?;

                // actual ev
                let lwork = work_size[0].to_usize().unwrap();
                let mut work = unsafe { vec_uninit(lwork) };
                unsafe {
                    $ev(
                        jobvl,
                        jobvr,
                        n,
                        &mut a,
                        n,
                        &mut eig_re,
                        &mut eig_im,
                        vl.as_mut().map(|v| v.as_mut_slice()).unwrap_or(&mut []),
                        n,
                        vr.as_mut().map(|v| v.as_mut_slice()).unwrap_or(&mut []),
                        n,
                        &mut work,
                        lwork as i32,
                        &mut info,
                    )
                };
                info.as_lapack_result()?;

                // reconstruct eigenvalues
                let eigs: Vec<Self::Complex> = eig_re
                    .iter()
                    .zip(eig_im.iter())
                    .map(|(&re, &im)| Self::complex(re, im))
                    .collect();

                if !calc_v {
                    return Ok((eigs, Vec::new()));
                }

                // Reconstruct eigenvectors into complex-array
                // --------------------------------------------
                //
                // From LAPACK API https://software.intel.com/en-us/node/469230
                //
                // - If the j-th eigenvalue is real,
                //   - v(j) = VR(:,j), the j-th column of VR.
                //
                // - If the j-th and (j+1)-st eigenvalues form a complex conjugate pair,
                //   - v(j)   = VR(:,j) + i*VR(:,j+1)
                //   - v(j+1) = VR(:,j) - i*VR(:,j+1).
                //
                // In the C-layout case, we need the conjugates of the left
                // eigenvectors, so the signs should be reversed.

                let n = n as usize;
                let v = vr.or(vl).unwrap();
                let mut eigvecs = unsafe { vec_uninit(n * n) };
                let mut col = 0;
                while col < n {
                    if eig_im[col] == 0. {
                        // The corresponding eigenvalue is real.
                        for row in 0..n {
                            let re = v[row + col * n];
                            eigvecs[row + col * n] = Self::complex(re, 0.);
                        }
                        col += 1;
                    } else {
                        // This is a complex conjugate pair.
                        assert!(col + 1 < n);
                        for row in 0..n {
                            let re = v[row + col * n];
                            let mut im = v[row + (col + 1) * n];
                            if jobvl == b'V' {
                                im = -im;
                            }
                            eigvecs[row + col * n] = Self::complex(re, im);
                            eigvecs[row + (col + 1) * n] = Self::complex(re, -im);
                        }
                        col += 2;
                    }
                }

                Ok((eigs, eigvecs))
            }
        }
    };
}

impl_eig_real!(f64, lapack::dgeev);
impl_eig_real!(f32, lapack::sgeev);
<|endoftext|>


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

use cgmath::vector::Vector;
use geom::Geom;
use core_types::{
    Bool,
    Int,
    MapPos,
    UnitId,
};
use core::{
    Unit,
};
use gl_types::{
    Scene,
    SceneNode,
    Float,
    WorldPos,
};
use game_state::GameState;

pub trait EventVisualizer {
    fn is_finished(&self) -> Bool;
    fn draw(&mut self, geom: &Geom, scene: &mut Scene);
    fn end(&mut self, geom: &Geom, scene: &mut Scene, game_state: &mut GameState);
}

static MOVE_SPEED: Float = 40.0; // TODO: config?

pub struct EventMoveVisualizer {
    unit_id: UnitId,
    path: ~[MapPos],
    current_move_index: Int,
}

impl EventVisualizer for EventMoveVisualizer {
    fn is_finished(&self) -> Bool {
        assert!(self.current_move_index <= self.frames_count());
        self.current_move_index == self.frames_count()
    }

    fn draw(&mut self, geom: &Geom, scene: &mut Scene) {
        let node = scene.get_mut(&self.unit_id);
        node.pos = self.current_position(geom);
        self.current_move_index += 1;
    }

    fn end(&mut self, geom: &Geom, scene: &mut Scene, game_state: &mut GameState) {
        let unit_node = scene.get_mut(&self.unit_id);
        unit_node.pos = self.current_position(geom);
        let unit = game_state.units.mut_iter().find(|u| u.id == self.unit_id).unwrap();
        unit.pos = *self.path.last().unwrap();
    }
}

impl EventMoveVisualizer {
    pub fn new(unit_id: UnitId, path: ~[MapPos]) -> ~EventVisualizer {
        ~EventMoveVisualizer {
            unit_id: unit_id,
            path: path,
            current_move_index: 0,
        } as ~EventVisualizer
    }

    fn frames_count(&self) -> Int {
        let len = self.path.len() as Int - 1;
        len * MOVE_SPEED as Int
    }

    fn current_tile(&self) -> MapPos {
        self.path[self.current_tile_index()]
    }

    fn next_tile(&self) -> MapPos {
        self.path[self.current_tile_index() + 1]
    }

    fn current_tile_index(&self) -> Int {
        // self.current_move_index / MOVE_SPEED as Int
        0
    }

    fn node_index(&self) -> Int {
        // self.current_move_index - self.current_tile_index() * MOVE_SPEED
        self.current_move_index
    }

    fn current_position(&self, geom: &Geom) -> WorldPos {
        let from = geom.map_pos_to_world_pos(self.current_tile());
        let to = geom.map_pos_to_world_pos(self.next_tile());
        let diff = to.sub_v(&from).div_s(MOVE_SPEED);
        from.add_v(&diff.mul_s(self.node_index() as Float))
    }
}

pub struct EventEndTurnVisualizer;

impl EventEndTurnVisualizer {
    pub fn new() -> ~EventVisualizer {
        ~EventEndTurnVisualizer as ~EventVisualizer
    }
}

impl EventVisualizer for EventEndTurnVisualizer {
    fn is_finished(&self) -> Bool {
        true
    }

    fn draw(&mut self, _: &Geom, _: &mut Scene) {}

    fn end(&mut self, _: &Geom, _: &mut Scene, _: &mut GameState) {}
}

pub struct EventCreateUnitVisualizer {
    id: UnitId,
    pos: MapPos,
}

impl EventCreateUnitVisualizer {
    pub fn new(id: UnitId, pos: MapPos) -> ~EventVisualizer {
        ~EventCreateUnitVisualizer {
            id: id,
            pos: pos,
        } as ~EventVisualizer
    }
}

impl EventVisualizer for EventCreateUnitVisualizer {
    fn is_finished(&self) -> Bool {
        true
    }

    fn draw(&mut self, _: &Geom, _: &mut Scene) {}

    fn end(&mut self, geom: &Geom, scene: &mut Scene, game_state: &mut GameState) {
        let world_pos = geom.map_pos_to_world_pos(self.pos);
        scene.insert(self.id, SceneNode{pos: world_pos});
        assert!(game_state.units.iter().find(|u| u.id == self.id).is_none());
        game_state.units.push(Unit{id: self.id, pos: self.pos});
    }
}
// vim: set tabstop=4 shiftwidth=4 softtabstop=4 expandtab:
<commit_msg>EventCreateUnitVisualizer: Added animation<commit_after>// See LICENSE file for copyright and license details.

use cgmath::vector::Vector;
use geom::Geom;
use core_types::{
    Bool,
    Int,
    MapPos,
    UnitId,
};
use core::{
    Unit,
};
use gl_types::{
    Scene,
    SceneNode,
    Float,
    WorldPos,
};
use game_state::GameState;

pub trait EventVisualizer {
    fn is_finished(&self) -> Bool;
    fn draw(&mut self, geom: &Geom, scene: &mut Scene);
    fn end(&mut self, geom: &Geom, scene: &mut Scene, game_state: &mut GameState);
}

static MOVE_SPEED: Float = 40.0; // TODO: config?

pub struct EventMoveVisualizer {
    unit_id: UnitId,
    path: ~[MapPos],
    current_move_index: Int,
}

impl EventVisualizer for EventMoveVisualizer {
    fn is_finished(&self) -> Bool {
        assert!(self.current_move_index <= self.frames_count());
        self.current_move_index == self.frames_count()
    }

    fn draw(&mut self, geom: &Geom, scene: &mut Scene) {
        let node = scene.get_mut(&self.unit_id);
        node.pos = self.current_position(geom);
        self.current_move_index += 1;
    }

    fn end(&mut self, geom: &Geom, scene: &mut Scene, game_state: &mut GameState) {
        let unit_node = scene.get_mut(&self.unit_id);
        unit_node.pos = self.current_position(geom);
        let unit = game_state.units.mut_iter().find(|u| u.id == self.unit_id).unwrap();
        unit.pos = *self.path.last().unwrap();
    }
}

impl EventMoveVisualizer {
    pub fn new(unit_id: UnitId, path: ~[MapPos]) -> ~EventVisualizer {
        ~EventMoveVisualizer {
            unit_id: unit_id,
            path: path,
            current_move_index: 0,
        } as ~EventVisualizer
    }

    fn frames_count(&self) -> Int {
        let len = self.path.len() as Int - 1;
        len * MOVE_SPEED as Int
    }

    fn current_tile(&self) -> MapPos {
        self.path[self.current_tile_index()]
    }

    fn next_tile(&self) -> MapPos {
        self.path[self.current_tile_index() + 1]
    }

    fn current_tile_index(&self) -> Int {
        // self.current_move_index / MOVE_SPEED as Int
        0
    }

    fn node_index(&self) -> Int {
        // self.current_move_index - self.current_tile_index() * MOVE_SPEED
        self.current_move_index
    }

    fn current_position(&self, geom: &Geom) -> WorldPos {
        let from = geom.map_pos_to_world_pos(self.current_tile());
        let to = geom.map_pos_to_world_pos(self.next_tile());
        let diff = to.sub_v(&from).div_s(MOVE_SPEED);
        from.add_v(&diff.mul_s(self.node_index() as Float))
    }
}

pub struct EventEndTurnVisualizer;

impl EventEndTurnVisualizer {
    pub fn new() -> ~EventVisualizer {
        ~EventEndTurnVisualizer as ~EventVisualizer
    }
}

impl EventVisualizer for EventEndTurnVisualizer {
    fn is_finished(&self) -> Bool {
        true
    }

    fn draw(&mut self, _: &Geom, _: &mut Scene) {}

    fn end(&mut self, _: &Geom, _: &mut Scene, _: &mut GameState) {}
}

pub struct EventCreateUnitVisualizer {
    id: UnitId,
    pos: MapPos,
    anim_index: Int,
    is_initialized: Bool,
}

impl EventCreateUnitVisualizer {
    pub fn new(id: UnitId, pos: MapPos) -> ~EventVisualizer {
        ~EventCreateUnitVisualizer {
            id: id,
            pos: pos,
            anim_index: 0,
            is_initialized: false,
        } as ~EventVisualizer
    }
}

impl EventVisualizer for EventCreateUnitVisualizer {
    fn is_finished(&self) -> Bool {
        self.anim_index == MOVE_SPEED as Int
    }

    fn draw(&mut self, geom: &Geom, scene: &mut Scene) {
        if !self.is_initialized {
            let world_pos = geom.map_pos_to_world_pos(self.pos);
            scene.insert(self.id, SceneNode{pos: world_pos});
            self.is_initialized = true;
        }
        let mut pos = geom.map_pos_to_world_pos(self.pos);
        pos.z -= 0.02 * (MOVE_SPEED / self.anim_index as Float);
        scene.get_mut(&self.id).pos = pos;
        self.anim_index += 1;
    }

    fn end(&mut self, _: &Geom, _: &mut Scene, game_state: &mut GameState) {
        assert!(game_state.units.iter().find(|u| u.id == self.id).is_none());
        game_state.units.push(Unit{id: self.id, pos: self.pos});
    }
}
// vim: set tabstop=4 shiftwidth=4 softtabstop=4 expandtab:
<|endoftext|>


<commit_before>use super::Rope;
use std::iter;

#[test]
fn rebalance_test_1() {
    let mut r = Rope::from("This is a large string \
                        that will need to be rebalanced.".to_string());
    r.rebalance();
    assert!(r.is_balanced());
}

#[test]
fn rebalance_test_2() {
    let mut r =
        Rope::from("Lorem ipsum dolor sit amet, consectetur adipiscing eli\
                    t, sed do eiusmod tempor incididunt ut labore et dolor\
                    e magna aliqua. Ut enim ad minim veniam, quis nostrud \
                    exercitation ullamco laboris nisi ut aliquip ex ea com\
                    modo consequat. Duis aute irure dolor in reprehenderit\
                     in voluptate velit esse cillum dolore eu fugiat nulla\
                     pariatur. Excepteur sint occaecat cupidatat non proid\
                    ent, sunt in culpa qui officia deserunt mollit anim id\
                     est laborum.".to_string());
    r.rebalance();
    assert!(r.is_balanced());
}

#[test]
fn big_rebalance() {
    let s: String = iter::repeat('a').take(10_000).collect();
    let mut r = Rope::from(s);
    r.rebalance();
    assert!(r.is_balanced());
}

#[test]
fn repeated_concat_left_rebalance() {
    let s: String = iter::repeat('a').take(10_000).collect();
    let mut r = Rope::from(s);
    for _ in 1..1000 {
        r = r + iter::repeat('a').take(100).collect::<String>();
    }
    assert!(r.is_balanced());
}

#[test]
fn repeated_concat_right_rebalance() {
    let s: String = iter::repeat('a').take(10_000).collect();
    let mut r = Rope::from(s);
    for _ in 1..1000 {
        let s2 = iter::repeat('a').take(100).collect::<String>();
        r = Rope::from(s2) + r;
    }
    assert!(r.is_balanced());
}

#[test]
fn merge_rebalance_test() {
    let s = "Lorem ipsum dolor sit amet, consectetur adipiscing eli\
             t, sed do eiusmod tempor incididunt ut labore et dolor\
             e magna aliqua. Ut enim ad minim veniam, quis nostrud \
             exercitation ullamco laboris nisi ut aliquip ex ea com\
             modo consequat. Duis aute irure dolor in reprehenderit\
              in voluptate velit esse cillum dolore eu fugiat nulla\
              pariatur. Excepteur sint occaecat cupidatat non proid\
             ent, sunt in culpa qui officia deserunt mollit anim id\
              est laborum.";

     let t = Rope::from(s.to_owned());
     let mut u = t + s;
     u.rebalance();
     assert!(u.is_balanced());
}

#[test]
fn with_insert_rope_balance_test() {
    let s: String = iter::repeat('a').take(10).collect();
    let mut r_1 = Rope::from(s);
    for _ in 0..99 {
        let t: String = iter::repeat('a').take(10).collect();
        r_1 = r_1.with_insert_rope(5, Rope::from(t));
    }
    //  this isn't necessary, with_insert_rope() will automatically rebalance
    //      - eliza, 12/18/2016
    // r_1.rebalance();
    assert!(r_1.is_balanced());
}

#[test]
fn with_insert_rope_test_1() {
    let s: String = iter::repeat('a').take(1_000).collect();
    let r_1 = Rope::from(s);
    let mut r_2 = Rope::new();
    for _ in 0..100 {
        let t: String = iter::repeat('a').take(10).collect();
        r_2 = r_2.with_insert_rope(0, Rope::from(t));
    }
    assert_eq!(r_1, r_2);
}

#[test]
fn with_insert_rope_test_2() {
    let s: String = iter::repeat('a').take(10).collect();
    let mut r_1 = Rope::from(s);
    for _ in 0..99 {
        let t: String = iter::repeat('a').take(10).collect();
        r_1 = r_1.with_insert_rope(5, Rope::from(t));
    }

    let q: String = iter::repeat('a').take(1_000).collect();
    let r_2 = Rope::from(q);
    assert_eq!(r_1, r_2);
}

#[test]
fn mutable_insert_rope_test_1() {
    let mut s_1 = Rope::from(String::from("aaaaa"));
    let mut s_2 = Rope::from(String::from("bbbbb"));
    let s_3 = Rope::from(String::from("ccccc"));
    s_2.insert_rope(0, s_3);
    s_1.insert_rope(0, s_2);
    assert_eq!(&s_1, "cccccbbbbbaaaaa");
}

#[test]
fn mutable_insert_str_test_1() {
    let mut s = Rope::from("aaaaa");
    s.insert_str(0, "bbbbb");
    s.insert_str(10, "ccccc");
    assert_eq!(&s, "bbbbbaaaaaccccc");
}

#[test]
fn mutable_insert_char_test_1() {
    let mut s = Rope::from("aaaaa");
    for _ in 0..5 { s.insert(0, 'b')}
    for _ in 0..5 { s.insert(10, 'c')}
    assert_eq!(&s, "bbbbbaaaaaccccc");
}

#[test]
fn with_insert_char_test_1() {
    let s = Rope::from("aaaaa");
    let s_1 = s.with_insert(5, 'b');
    let s_2 = s_1.with_insert(4, 'b');
    let s_3 = s_2.with_insert(3, 'b');
    let s_4 = s_3.with_insert(2, 'b');
    let s_5 = s_4.with_insert(1, 'b');
    assert_eq!(&s, "aaaaa");
    assert_eq!(&s_1, "aaaaab");
    assert_eq!(&s_2, "aaaabab");
    assert_eq!(&s_3, "aaababab");
    assert_eq!(&s_4, "aabababab");
    assert_eq!(&s_5, "ababababab");

}

#[test]
fn with_insert_str_test_1() {
    let s = Rope::from("aaaaa");
    let s_1 = s.with_insert_str(5, "ccccc");
    let s_2 = s_1.with_insert_str(5, "bbbbb");
    assert_eq!(&s, "aaaaa");
    assert_eq!(&s_1, "aaaaaccccc");
    assert_eq!(&s_2, "aaaaabbbbbccccc");
}
<commit_msg>rope: add mutable test for with_insert_char_test_1<commit_after>use super::Rope;
use std::iter;

#[test]
fn rebalance_test_1() {
    let mut r = Rope::from("This is a large string \
                        that will need to be rebalanced.".to_string());
    r.rebalance();
    assert!(r.is_balanced());
}

#[test]
fn rebalance_test_2() {
    let mut r =
        Rope::from("Lorem ipsum dolor sit amet, consectetur adipiscing eli\
                    t, sed do eiusmod tempor incididunt ut labore et dolor\
                    e magna aliqua. Ut enim ad minim veniam, quis nostrud \
                    exercitation ullamco laboris nisi ut aliquip ex ea com\
                    modo consequat. Duis aute irure dolor in reprehenderit\
                     in voluptate velit esse cillum dolore eu fugiat nulla\
                     pariatur. Excepteur sint occaecat cupidatat non proid\
                    ent, sunt in culpa qui officia deserunt mollit anim id\
                     est laborum.".to_string());
    r.rebalance();
    assert!(r.is_balanced());
}

#[test]
fn big_rebalance() {
    let s: String = iter::repeat('a').take(10_000).collect();
    let mut r = Rope::from(s);
    r.rebalance();
    assert!(r.is_balanced());
}

#[test]
fn repeated_concat_left_rebalance() {
    let s: String = iter::repeat('a').take(10_000).collect();
    let mut r = Rope::from(s);
    for _ in 1..1000 {
        r = r + iter::repeat('a').take(100).collect::<String>();
    }
    assert!(r.is_balanced());
}

#[test]
fn repeated_concat_right_rebalance() {
    let s: String = iter::repeat('a').take(10_000).collect();
    let mut r = Rope::from(s);
    for _ in 1..1000 {
        let s2 = iter::repeat('a').take(100).collect::<String>();
        r = Rope::from(s2) + r;
    }
    assert!(r.is_balanced());
}

#[test]
fn merge_rebalance_test() {
    let s = "Lorem ipsum dolor sit amet, consectetur adipiscing eli\
             t, sed do eiusmod tempor incididunt ut labore et dolor\
             e magna aliqua. Ut enim ad minim veniam, quis nostrud \
             exercitation ullamco laboris nisi ut aliquip ex ea com\
             modo consequat. Duis aute irure dolor in reprehenderit\
              in voluptate velit esse cillum dolore eu fugiat nulla\
              pariatur. Excepteur sint occaecat cupidatat non proid\
             ent, sunt in culpa qui officia deserunt mollit anim id\
              est laborum.";

     let t = Rope::from(s.to_owned());
     let mut u = t + s;
     u.rebalance();
     assert!(u.is_balanced());
}

#[test]
fn with_insert_rope_balance_test() {
    let s: String = iter::repeat('a').take(10).collect();
    let mut r_1 = Rope::from(s);
    for _ in 0..99 {
        let t: String = iter::repeat('a').take(10).collect();
        r_1 = r_1.with_insert_rope(5, Rope::from(t));
    }
    //  this isn't necessary, with_insert_rope() will automatically rebalance
    //      - eliza, 12/18/2016
    // r_1.rebalance();
    assert!(r_1.is_balanced());
}

#[test]
fn with_insert_rope_test_1() {
    let s: String = iter::repeat('a').take(1_000).collect();
    let r_1 = Rope::from(s);
    let mut r_2 = Rope::new();
    for _ in 0..100 {
        let t: String = iter::repeat('a').take(10).collect();
        r_2 = r_2.with_insert_rope(0, Rope::from(t));
    }
    assert_eq!(r_1, r_2);
}

#[test]
fn with_insert_rope_test_2() {
    let s: String = iter::repeat('a').take(10).collect();
    let mut r_1 = Rope::from(s);
    for _ in 0..99 {
        let t: String = iter::repeat('a').take(10).collect();
        r_1 = r_1.with_insert_rope(5, Rope::from(t));
    }

    let q: String = iter::repeat('a').take(1_000).collect();
    let r_2 = Rope::from(q);
    assert_eq!(r_1, r_2);
}

#[test]
fn mutable_insert_rope_test_1() {
    let mut s_1 = Rope::from(String::from("aaaaa"));
    let mut s_2 = Rope::from(String::from("bbbbb"));
    let s_3 = Rope::from(String::from("ccccc"));
    s_2.insert_rope(0, s_3);
    s_1.insert_rope(0, s_2);
    assert_eq!(&s_1, "cccccbbbbbaaaaa");
}

#[test]
fn mutable_insert_str_test_1() {
    let mut s = Rope::from("aaaaa");
    s.insert_str(0, "bbbbb");
    s.insert_str(10, "ccccc");
    assert_eq!(&s, "bbbbbaaaaaccccc");
}

#[test]
fn mutable_insert_char_test_1() {
    let mut s = Rope::from("aaaaa");
    for _ in 0..5 { s.insert(0, 'b')}
    for _ in 0..5 { s.insert(10, 'c')}
    assert_eq!(&s, "bbbbbaaaaaccccc");
}

#[test]
fn mutable_insert_char_test_2() {
    // this is the same as with_insert_char_test1() except mutable
    let mut s = Rope::from("aaaaa");
    assert_eq!(&s, "aaaaa");
    s.insert(5, 'b');
    assert_eq!(&s, "aaaaab");
    s.insert(4, 'b');
    assert_eq!(&s, "aaaabab");
    s.insert(3, 'b');
    assert_eq!(&s, "aaababab");
    s.insert(2, 'b');
    assert_eq!(&s, "aabababab");
    s.insert(1, 'b');
    assert_eq!(&s, "ababababab");

}

#[test]
fn with_insert_char_test_1() {
    let s = Rope::from("aaaaa");
    let s_1 = s.with_insert(5, 'b');
    let s_2 = s_1.with_insert(4, 'b');
    let s_3 = s_2.with_insert(3, 'b');
    let s_4 = s_3.with_insert(2, 'b');
    let s_5 = s_4.with_insert(1, 'b');
    assert_eq!(&s, "aaaaa");
    assert_eq!(&s_1, "aaaaab");
    assert_eq!(&s_2, "aaaabab");
    assert_eq!(&s_3, "aaababab");
    assert_eq!(&s_4, "aabababab");
    assert_eq!(&s_5, "ababababab");

}

#[test]
fn with_insert_str_test_1() {
    let s = Rope::from("aaaaa");
    let s_1 = s.with_insert_str(5, "ccccc");
    let s_2 = s_1.with_insert_str(5, "bbbbb");
    assert_eq!(&s, "aaaaa");
    assert_eq!(&s_1, "aaaaaccccc");
    assert_eq!(&s_2, "aaaaabbbbbccccc");
}
<|endoftext|>