<commit_before>use std::{io, io::prelude::Write};

use super::OutputFormatter;
use crate::{
    bench::fmt_bench_samples,
    console::{ConsoleTestState, OutputLocation},
    test_result::TestResult,
    time,
    types::TestDesc,
};

pub(crate) struct PrettyFormatter<T> {
    out: OutputLocation<T>,
    use_color: bool,
    time_options: Option<time::TestTimeOptions>,

    /// Number of columns to fill when aligning names
    max_name_len: usize,

    is_multithreaded: bool,
}

impl<T: Write> PrettyFormatter<T> {
    pub fn new(
        out: OutputLocation<T>,
        use_color: bool,
        max_name_len: usize,
        is_multithreaded: bool,
        time_options: Option<time::TestTimeOptions>,
    ) -> Self {
        PrettyFormatter { out, use_color, max_name_len, is_multithreaded, time_options }
    }

    #[cfg(test)]
    pub fn output_location(&self) -> &OutputLocation<T> {
        &self.out
    }

    pub fn write_ok(&mut self) -> io::Result<()> {
        self.write_short_result("ok", term::color::GREEN)
    }

    pub fn write_failed(&mut self) -> io::Result<()> {
        self.write_short_result("FAILED", term::color::RED)
    }

    pub fn write_ignored(&mut self) -> io::Result<()> {
        self.write_short_result("ignored", term::color::YELLOW)
    }

    pub fn write_allowed_fail(&mut self) -> io::Result<()> {
        self.write_short_result("FAILED (allowed)", term::color::YELLOW)
    }

    pub fn write_time_failed(&mut self) -> io::Result<()> {
        self.write_short_result("FAILED (time limit exceeded)", term::color::RED)
    }

    pub fn write_bench(&mut self) -> io::Result<()> {
        self.write_pretty("bench", term::color::CYAN)
    }

    pub fn write_short_result(
        &mut self,
        result: &str,
        color: term::color::Color,
    ) -> io::Result<()> {
        self.write_pretty(result, color)
    }

    pub fn write_pretty(&mut self, word: &str, color: term::color::Color) -> io::Result<()> {
        match self.out {
            OutputLocation::Pretty(ref mut term) => {
                if self.use_color {
                    term.fg(color)?;
                }
                term.write_all(word.as_bytes())?;
                if self.use_color {
                    term.reset()?;
                }
                term.flush()
            }
            OutputLocation::Raw(ref mut stdout) => {
                stdout.write_all(word.as_bytes())?;
                stdout.flush()
            }
        }
    }

    pub fn write_plain<S: AsRef<str>>(&mut self, s: S) -> io::Result<()> {
        let s = s.as_ref();
        self.out.write_all(s.as_bytes())?;
        self.out.flush()
    }

    fn write_time(
        &mut self,
        desc: &TestDesc,
        exec_time: Option<&time::TestExecTime>,
    ) -> io::Result<()> {
        if let (Some(opts), Some(time)) = (self.time_options, exec_time) {
            let time_str = format!(" <{}>", time);

            let color = if opts.colored {
                if opts.is_critical(desc, time) {
                    Some(term::color::RED)
                } else if opts.is_warn(desc, time) {
                    Some(term::color::YELLOW)
                } else {
                    None
                }
            } else {
                None
            };

            match color {
                Some(color) => self.write_pretty(&time_str, color)?,
                None => self.write_plain(&time_str)?,
            }
        }

        Ok(())
    }

    fn write_results(
        &mut self,
        inputs: &Vec<(TestDesc, Vec<u8>)>,
        results_type: &str,
    ) -> io::Result<()> {
        let results_out_str = format!("\n{}:\n", results_type);

        self.write_plain(&results_out_str)?;

        let mut results = Vec::new();
        let mut stdouts = String::new();
        for &(ref f, ref stdout) in inputs {
            results.push(f.name.to_string());
            if !stdout.is_empty() {
                stdouts.push_str(&format!("---- {} stdout ----\n", f.name));
                let output = String::from_utf8_lossy(stdout);
                stdouts.push_str(&output);
                stdouts.push('\n');
            }
        }
        if !stdouts.is_empty() {
            self.write_plain("\n")?;
            self.write_plain(&stdouts)?;
        }

        self.write_plain(&results_out_str)?;
        results.sort();
        for name in &results {
            self.write_plain(&format!("    {}\n", name))?;
        }
        Ok(())
    }

    pub fn write_successes(&mut self, state: &ConsoleTestState) -> io::Result<()> {
        self.write_results(&state.not_failures, "successes")
    }

    pub fn write_failures(&mut self, state: &ConsoleTestState) -> io::Result<()> {
        self.write_results(&state.failures, "failures")
    }

    pub fn write_time_failures(&mut self, state: &ConsoleTestState) -> io::Result<()> {
        self.write_results(&state.time_failures, "failures (time limit exceeded)")
    }

    fn write_test_name(&mut self, desc: &TestDesc) -> io::Result<()> {
        let name = desc.padded_name(self.max_name_len, desc.name.padding());
        self.write_plain(&format!("test {} ... ", name))?;

        Ok(())
    }
}

impl<T: Write> OutputFormatter for PrettyFormatter<T> {
    fn write_run_start(&mut self, test_count: usize) -> io::Result<()> {
        let noun = if test_count != 1 { "tests" } else { "test" };
        self.write_plain(&format!("\nrunning {} {}\n", test_count, noun))
    }

    fn write_test_start(&mut self, desc: &TestDesc) -> io::Result<()> {
        // When running tests concurrently, we should not print
        // the test's name as the result will be mis-aligned.
        // When running the tests serially, we print the name here so
        // that the user can see which test hangs.
        if !self.is_multithreaded {
            self.write_test_name(desc)?;
        }

        Ok(())
    }

    fn write_result(
        &mut self,
        desc: &TestDesc,
        result: &TestResult,
        exec_time: Option<&time::TestExecTime>,
        _: &[u8],
        _: &ConsoleTestState,
    ) -> io::Result<()> {
        if self.is_multithreaded {
            self.write_test_name(desc)?;
        }

        match *result {
            TestResult::TrOk => self.write_ok()?,
            TestResult::TrFailed | TestResult::TrFailedMsg(_) => self.write_failed()?,
            TestResult::TrIgnored => self.write_ignored()?,
            TestResult::TrAllowedFail => self.write_allowed_fail()?,
            TestResult::TrBench(ref bs) => {
                self.write_bench()?;
                self.write_plain(&format!(": {}", fmt_bench_samples(bs)))?;
            }
            TestResult::TrTimedFail => self.write_time_failed()?,
        }

        self.write_time(desc, exec_time)?;
        self.write_plain("\n")
    }

    fn write_timeout(&mut self, desc: &TestDesc) -> io::Result<()> {
        if self.is_multithreaded {
            self.write_test_name(desc)?;
        }

        self.write_plain(&format!(
            "test {} has been running for over {} seconds\n",
            desc.name,
            time::TEST_WARN_TIMEOUT_S
        ))
    }

    fn write_run_finish(&mut self, state: &ConsoleTestState) -> io::Result<bool> {
        if state.options.display_output {
            self.write_successes(state)?;
        }
        let success = state.failed == 0;
        if !success {
            if !state.failures.is_empty() {
                self.write_failures(state)?;
            }

            if !state.time_failures.is_empty() {
                self.write_time_failures(state)?;
            }
        }

        self.write_plain("\ntest result: ")?;

        if success {
            // There's no parallelism at this point so it's safe to use color
            self.write_pretty("ok", term::color::GREEN)?;
        } else {
            self.write_pretty("FAILED", term::color::RED)?;
        }

        let s = if state.allowed_fail > 0 {
            format!(
                ". {} passed; {} failed ({} allowed); {} ignored; {} measured; {} filtered out",
                state.passed,
                state.failed + state.allowed_fail,
                state.allowed_fail,
                state.ignored,
                state.measured,
                state.filtered_out
            )
        } else {
            format!(
                ". {} passed; {} failed; {} ignored; {} measured; {} filtered out",
                state.passed, state.failed, state.ignored, state.measured, state.filtered_out
            )
        };

        self.write_plain(&s)?;

        if let Some(ref exec_time) = state.exec_time {
            let time_str = format!("; finished in {}", exec_time);
            self.write_plain(&time_str)?;
        }

        self.write_plain("\n\n")?;

        Ok(success)
    }
}
<commit_msg>Rollup merge of #82349 - tmiasko:pretty-test-timeout, r=Mark-Simulacrum<commit_after>use std::{io, io::prelude::Write};

use super::OutputFormatter;
use crate::{
    bench::fmt_bench_samples,
    console::{ConsoleTestState, OutputLocation},
    test_result::TestResult,
    time,
    types::TestDesc,
};

pub(crate) struct PrettyFormatter<T> {
    out: OutputLocation<T>,
    use_color: bool,
    time_options: Option<time::TestTimeOptions>,

    /// Number of columns to fill when aligning names
    max_name_len: usize,

    is_multithreaded: bool,
}

impl<T: Write> PrettyFormatter<T> {
    pub fn new(
        out: OutputLocation<T>,
        use_color: bool,
        max_name_len: usize,
        is_multithreaded: bool,
        time_options: Option<time::TestTimeOptions>,
    ) -> Self {
        PrettyFormatter { out, use_color, max_name_len, is_multithreaded, time_options }
    }

    #[cfg(test)]
    pub fn output_location(&self) -> &OutputLocation<T> {
        &self.out
    }

    pub fn write_ok(&mut self) -> io::Result<()> {
        self.write_short_result("ok", term::color::GREEN)
    }

    pub fn write_failed(&mut self) -> io::Result<()> {
        self.write_short_result("FAILED", term::color::RED)
    }

    pub fn write_ignored(&mut self) -> io::Result<()> {
        self.write_short_result("ignored", term::color::YELLOW)
    }

    pub fn write_allowed_fail(&mut self) -> io::Result<()> {
        self.write_short_result("FAILED (allowed)", term::color::YELLOW)
    }

    pub fn write_time_failed(&mut self) -> io::Result<()> {
        self.write_short_result("FAILED (time limit exceeded)", term::color::RED)
    }

    pub fn write_bench(&mut self) -> io::Result<()> {
        self.write_pretty("bench", term::color::CYAN)
    }

    pub fn write_short_result(
        &mut self,
        result: &str,
        color: term::color::Color,
    ) -> io::Result<()> {
        self.write_pretty(result, color)
    }

    pub fn write_pretty(&mut self, word: &str, color: term::color::Color) -> io::Result<()> {
        match self.out {
            OutputLocation::Pretty(ref mut term) => {
                if self.use_color {
                    term.fg(color)?;
                }
                term.write_all(word.as_bytes())?;
                if self.use_color {
                    term.reset()?;
                }
                term.flush()
            }
            OutputLocation::Raw(ref mut stdout) => {
                stdout.write_all(word.as_bytes())?;
                stdout.flush()
            }
        }
    }

    pub fn write_plain<S: AsRef<str>>(&mut self, s: S) -> io::Result<()> {
        let s = s.as_ref();
        self.out.write_all(s.as_bytes())?;
        self.out.flush()
    }

    fn write_time(
        &mut self,
        desc: &TestDesc,
        exec_time: Option<&time::TestExecTime>,
    ) -> io::Result<()> {
        if let (Some(opts), Some(time)) = (self.time_options, exec_time) {
            let time_str = format!(" <{}>", time);

            let color = if opts.colored {
                if opts.is_critical(desc, time) {
                    Some(term::color::RED)
                } else if opts.is_warn(desc, time) {
                    Some(term::color::YELLOW)
                } else {
                    None
                }
            } else {
                None
            };

            match color {
                Some(color) => self.write_pretty(&time_str, color)?,
                None => self.write_plain(&time_str)?,
            }
        }

        Ok(())
    }

    fn write_results(
        &mut self,
        inputs: &Vec<(TestDesc, Vec<u8>)>,
        results_type: &str,
    ) -> io::Result<()> {
        let results_out_str = format!("\n{}:\n", results_type);

        self.write_plain(&results_out_str)?;

        let mut results = Vec::new();
        let mut stdouts = String::new();
        for &(ref f, ref stdout) in inputs {
            results.push(f.name.to_string());
            if !stdout.is_empty() {
                stdouts.push_str(&format!("---- {} stdout ----\n", f.name));
                let output = String::from_utf8_lossy(stdout);
                stdouts.push_str(&output);
                stdouts.push('\n');
            }
        }
        if !stdouts.is_empty() {
            self.write_plain("\n")?;
            self.write_plain(&stdouts)?;
        }

        self.write_plain(&results_out_str)?;
        results.sort();
        for name in &results {
            self.write_plain(&format!("    {}\n", name))?;
        }
        Ok(())
    }

    pub fn write_successes(&mut self, state: &ConsoleTestState) -> io::Result<()> {
        self.write_results(&state.not_failures, "successes")
    }

    pub fn write_failures(&mut self, state: &ConsoleTestState) -> io::Result<()> {
        self.write_results(&state.failures, "failures")
    }

    pub fn write_time_failures(&mut self, state: &ConsoleTestState) -> io::Result<()> {
        self.write_results(&state.time_failures, "failures (time limit exceeded)")
    }

    fn write_test_name(&mut self, desc: &TestDesc) -> io::Result<()> {
        let name = desc.padded_name(self.max_name_len, desc.name.padding());
        self.write_plain(&format!("test {} ... ", name))?;

        Ok(())
    }
}

impl<T: Write> OutputFormatter for PrettyFormatter<T> {
    fn write_run_start(&mut self, test_count: usize) -> io::Result<()> {
        let noun = if test_count != 1 { "tests" } else { "test" };
        self.write_plain(&format!("\nrunning {} {}\n", test_count, noun))
    }

    fn write_test_start(&mut self, desc: &TestDesc) -> io::Result<()> {
        // When running tests concurrently, we should not print
        // the test's name as the result will be mis-aligned.
        // When running the tests serially, we print the name here so
        // that the user can see which test hangs.
        if !self.is_multithreaded {
            self.write_test_name(desc)?;
        }

        Ok(())
    }

    fn write_result(
        &mut self,
        desc: &TestDesc,
        result: &TestResult,
        exec_time: Option<&time::TestExecTime>,
        _: &[u8],
        _: &ConsoleTestState,
    ) -> io::Result<()> {
        if self.is_multithreaded {
            self.write_test_name(desc)?;
        }

        match *result {
            TestResult::TrOk => self.write_ok()?,
            TestResult::TrFailed | TestResult::TrFailedMsg(_) => self.write_failed()?,
            TestResult::TrIgnored => self.write_ignored()?,
            TestResult::TrAllowedFail => self.write_allowed_fail()?,
            TestResult::TrBench(ref bs) => {
                self.write_bench()?;
                self.write_plain(&format!(": {}", fmt_bench_samples(bs)))?;
            }
            TestResult::TrTimedFail => self.write_time_failed()?,
        }

        self.write_time(desc, exec_time)?;
        self.write_plain("\n")
    }

    fn write_timeout(&mut self, desc: &TestDesc) -> io::Result<()> {
        self.write_plain(&format!(
            "test {} has been running for over {} seconds\n",
            desc.name,
            time::TEST_WARN_TIMEOUT_S
        ))
    }

    fn write_run_finish(&mut self, state: &ConsoleTestState) -> io::Result<bool> {
        if state.options.display_output {
            self.write_successes(state)?;
        }
        let success = state.failed == 0;
        if !success {
            if !state.failures.is_empty() {
                self.write_failures(state)?;
            }

            if !state.time_failures.is_empty() {
                self.write_time_failures(state)?;
            }
        }

        self.write_plain("\ntest result: ")?;

        if success {
            // There's no parallelism at this point so it's safe to use color
            self.write_pretty("ok", term::color::GREEN)?;
        } else {
            self.write_pretty("FAILED", term::color::RED)?;
        }

        let s = if state.allowed_fail > 0 {
            format!(
                ". {} passed; {} failed ({} allowed); {} ignored; {} measured; {} filtered out",
                state.passed,
                state.failed + state.allowed_fail,
                state.allowed_fail,
                state.ignored,
                state.measured,
                state.filtered_out
            )
        } else {
            format!(
                ". {} passed; {} failed; {} ignored; {} measured; {} filtered out",
                state.passed, state.failed, state.ignored, state.measured, state.filtered_out
            )
        };

        self.write_plain(&s)?;

        if let Some(ref exec_time) = state.exec_time {
            let time_str = format!("; finished in {}", exec_time);
            self.write_plain(&time_str)?;
        }

        self.write_plain("\n\n")?;

        Ok(success)
    }
}
<|endoftext|>


<commit_before><commit_msg>missing socks5_auth when local-socks4 is disabled<commit_after><|endoftext|>


<commit_before><commit_msg>CLI guard object<commit_after><|endoftext|>


<commit_before><commit_msg>Update to rust master<commit_after><|endoftext|>


<commit_before><commit_msg>Add a test for the body of an `impl`<commit_after><|endoftext|>


<commit_before><commit_msg>Fix warnings.<commit_after><|endoftext|>


<commit_before><commit_msg>Implementers of Player should also implement Sync + Send<commit_after><|endoftext|>


<commit_before><commit_msg>Add Server.poll_timeout method for #200<commit_after><|endoftext|>


<commit_before><commit_msg>more canonical rustification<commit_after><|endoftext|>


<commit_before>// Copyright (c) The Libra Core Contributors
// SPDX-License-Identifier: Apache-2.0

use crate::{validate_transaction::ValidateTransaction, TransactionContext};
use libra_management::error::Error;
use std::{thread::sleep, time};
use structopt::StructOpt;

#[derive(Clone, Debug, StructOpt)]
pub struct AutoValidate {
    #[structopt(long, help = "Disables auto validation")]
    disable_validate: bool,
    #[structopt(
        long,
        help = "The sleep duration in seconds between validation checks",
        default_value = "1"
    )]
    sleep_interval: u64,
    #[structopt(
        long,
        help = "The timeout in seconds for automatic validation",
        default_value = "30"
    )]
    validate_timeout: u64,
}

impl AutoValidate {
    pub fn execute(
        &self,
        json_server: String,
        transaction_context: TransactionContext,
    ) -> Result<TransactionContext, Error> {
        // If validation is disabled return the transaction context unmodified
        if self.disable_validate {
            return Ok(transaction_context);
        }

        // Create the validate transaction command to run
        let validate_transaction = ValidateTransaction::new(
            json_server,
            transaction_context.address,
            transaction_context.sequence_number,
        );

        // Loop until we get a successful result, or hit the timeout
        let mut time_slept = 0;
        while time_slept < self.validate_timeout {
            let validation_result = validate_transaction.execute()?;
            if validation_result.execution_result.is_some() {
                // The transaction was executed, return the context.
                return Ok(validation_result);
            }

            sleep(time::Duration::from_secs(self.sleep_interval));
            time_slept += self.sleep_interval;
        }

        // Tried to find the execution result, but the transaction still hasn't been executed...
        Ok(transaction_context)
    }
}
<commit_msg>[Operational Tool] Use checked_add for auto validate feature.<commit_after>// Copyright (c) The Libra Core Contributors
// SPDX-License-Identifier: Apache-2.0

use crate::{validate_transaction::ValidateTransaction, TransactionContext};
use libra_management::error::Error;
use std::{thread::sleep, time};
use structopt::StructOpt;

#[derive(Clone, Debug, StructOpt)]
pub struct AutoValidate {
    #[structopt(long, help = "Disables auto validation")]
    disable_validate: bool,
    #[structopt(
        long,
        help = "The sleep duration in seconds between validation checks",
        default_value = "1"
    )]
    sleep_interval: u64,
    #[structopt(
        long,
        help = "The timeout in seconds for automatic validation",
        default_value = "30"
    )]
    validate_timeout: u64,
}

impl AutoValidate {
    pub fn execute(
        &self,
        json_server: String,
        transaction_context: TransactionContext,
    ) -> Result<TransactionContext, Error> {
        // If validation is disabled return the transaction context unmodified
        if self.disable_validate {
            return Ok(transaction_context);
        }

        // Create the validate transaction command to run
        let validate_transaction = ValidateTransaction::new(
            json_server,
            transaction_context.address,
            transaction_context.sequence_number,
        );

        // Loop until we get a successful result, or hit the timeout
        let mut time_slept = 0;
        while time_slept < self.validate_timeout {
            let validation_result = validate_transaction.execute()?;
            if validation_result.execution_result.is_some() {
                // The transaction was executed, return the context.
                return Ok(validation_result);
            }

            sleep(time::Duration::from_secs(self.sleep_interval));
            time_slept = time_slept
                .checked_add(self.sleep_interval)
                .expect("Integer overflow/underflow detected: unexpected amount of time slept!");
        }

        // Tried to find the execution result, but the transaction still hasn't been executed...
        Ok(transaction_context)
    }
}
<|endoftext|>


<commit_before><commit_msg>finished<commit_after><|endoftext|>


<commit_before>
#[macro_use(s)]
extern crate ndarray;
extern crate ndarray_rand;
extern crate rand;

use ndarray_rand::{RandomExt, F32};
use rand::Rng;

use ndarray::{
    ArrayBase,
    Array,
    Dimension,
    Data,
    DataMut,
    Axis, RemoveAxis,
    LinalgScalar,
    Ix,
};

use rand::distributions::Normal;

// simple, slow, correct (hopefully) mat mul
fn reference_mat_mul<A, S, S2>(lhs: &ArrayBase<S, (Ix, Ix)>, rhs: &ArrayBase<S2, (Ix, Ix)>)
    -> Array<A, (Ix, Ix)>
    where A: LinalgScalar,
          S: Data<Elem=A>,
          S2: Data<Elem=A>,
{
    let ((m, k), (_, n)) = (lhs.dim(), rhs.dim());
    let mut res_elems = Vec::<A>::with_capacity(m * n);
    unsafe {
        res_elems.set_len(m * n);
    }

    let mut i = 0;
    let mut j = 0;
    for rr in &mut res_elems {
        unsafe {
            *rr = (0..k).fold(A::zero(),
                move |s, x| s + *lhs.uget((i, x)) * *rhs.uget((x, j)));
        }
        j += 1;
        if j == n {
            j = 0;
            i += 1;
        }
    }
    unsafe {
        ArrayBase::from_vec_dim_unchecked((m, n), res_elems)
    }
}

fn gen<D>(d: D) -> Array<f32, D>
    where D: Dimension,
{
    Array::random(d, F32(Normal::new(0., 1.)))
}
fn gen_f64<D>(d: D) -> Array<f64, D>
    where D: Dimension,
{
    Array::random(d, Normal::new(0., 1.))
}

#[test]
fn accurate_eye_f32() {
    for i in 0..20 {
        let eye = Array::eye(i);
        for j in 0..20 {
            let a = gen((i, j));
            let a2 = eye.dot(&a);
            if !a.all_close(&a2, 1e-6) {
                panic!("Arrays are not equal:\n{:?}\n{:?}\n{:?}", a, a2, &a2 - &a);
            }
            let a3 = a.t().dot(&eye);
            if !a.t().all_close(&a3, 1e-6) {
                panic!("Arrays are not equal:\n{:?}\n{:?}\n{:?}", a.t(), a3, &a3 - &a.t());
            }
        }
    }
    // pick a few random sizes
    let mut rng = rand::weak_rng();
    for _ in 0..10 {
        let i = rng.gen_range(15, 512);
        let j = rng.gen_range(15, 512);
        println!("Testing size {} by {}", i, j);
        let a = gen((i, j));
        let eye = Array::eye(i);
        let a2 = eye.dot(&a);
        if !a.all_close(&a2, 1e-6) {
            panic!("Arrays are not equal:\n{:?}\n{:?}\n{:?}", a, a2, &a2 - &a);
        }
        let a3 = a.t().dot(&eye);
        if !a.t().all_close(&a3, 1e-6) {
            panic!("Arrays are not equal:\n{:?}\n{:?}\n{:?}", a.t(), a3, &a3 - &a.t());
        }
    }
}

#[test]
fn accurate_eye_f64() {
    let abs_tol = 1e-15;
    for i in 0..20 {
        let eye = Array::eye(i);
        for j in 0..20 {
            let a = gen_f64((i, j));
            let a2 = eye.dot(&a);
            if !a.all_close(&a2, abs_tol) {
                panic!("Arrays are not equal:\n{:?}\n{:?}\n{:?}", a, a2, &a2 - &a);
            }
            let a3 = a.t().dot(&eye);
            if !a.t().all_close(&a3, abs_tol) {
                panic!("Arrays are not equal:\n{:?}\n{:?}\n{:?}", a.t(), a3, &a3 - &a.t());
            }
        }
    }
    // pick a few random sizes
    let mut rng = rand::weak_rng();
    for _ in 0..10 {
        let i = rng.gen_range(15, 512);
        let j = rng.gen_range(15, 512);
        println!("Testing size {} by {}", i, j);
        let a = gen_f64((i, j));
        let eye = Array::eye(i);
        let a2 = eye.dot(&a);
        if !a.all_close(&a2, 1e-6) {
            panic!("Arrays are not equal:\n{:?}\n{:?}\n{:?}", a, a2, &a2 - &a);
        }
        let a3 = a.t().dot(&eye);
        if !a.t().all_close(&a3, 1e-6) {
            panic!("Arrays are not equal:\n{:?}\n{:?}\n{:?}", a.t(), a3, &a3 - &a.t());
        }
    }
}

#[test]
fn accurate_mul_f32() {
    // pick a few random sizes
    let mut rng = rand::weak_rng();
    for i in 0..20 {
        let m = rng.gen_range(15, 512);
        let k = rng.gen_range(15, 512);
        let n = rng.gen_range(15, 1560);
        let a = gen((m, k));
        let b = gen((n, k));
        let b = b.t();
        let (a, b) = if i > 10 {
            (a.slice(s![..;2, ..;2]),
             b.slice(s![..;2, ..;2]))
        } else { (a.view(), b) };

        println!("Testing size {} by {} by {}", a.shape()[0], a.shape()[1], b.shape()[1]);
        let c = a.dot(&b);
        let reference = reference_mat_mul(&a, &b);
        let diff = (&c - &reference).mapv_into(f32::abs);

        let rtol = 1e-3;
        let atol = 1e-4;
        let crtol = c.mapv(|x| x.abs() * rtol);
        let tol = crtol + atol;
        let tol_m_diff = &diff - &tol;
        let maxdiff = *tol_m_diff.max();
        println!("diff offset from tolerance level= {:.2e}", maxdiff);
        if maxdiff > 0. {
            panic!("results differ");
        }
    }
}

#[test]
fn accurate_mul_f64() {
    // pick a few random sizes
    let mut rng = rand::weak_rng();
    for i in 0..20 {
        let m = rng.gen_range(15, 512);
        let k = rng.gen_range(15, 512);
        let n = rng.gen_range(15, 1560);
        let a = gen_f64((m, k));
        let b = gen_f64((n, k));
        let b = b.t();
        let (a, b) = if i > 10 {
            (a.slice(s![..;2, ..;2]),
             b.slice(s![..;2, ..;2]))
        } else { (a.view(), b) };

        println!("Testing size {} by {} by {}", a.shape()[0], a.shape()[1], b.shape()[1]);
        let c = a.dot(&b);
        let reference = reference_mat_mul(&a, &b);
        let diff = (&c - &reference).mapv_into(f64::abs);

        let rtol = 1e-7;
        let atol = 1e-12;
        let crtol = c.mapv(|x| x.abs() * rtol);
        let tol = crtol + atol;
        let tol_m_diff = &diff - &tol;
        let maxdiff = *tol_m_diff.max();
        println!("diff offset from tolerance level= {:.2e}", maxdiff);
        if maxdiff > 0. {
            panic!("results differ");
        }
    }
}

trait Utils {
    type Elem;
    type Dim;
    type Data;
    fn max(&self) -> &Self::Elem
        where Self::Elem: PartialOrd;
    fn lift<F>(&mut self, F)
        where F: FnMut(Self::Elem) -> Self::Elem, Self::Elem: Copy,
              Self::Data: DataMut;
    fn fold_axis<F>(&self, axis: Axis, f: F) -> Array<Self::Elem, <Self::Dim as RemoveAxis>::Smaller>
        where Self::Dim: RemoveAxis,
              Self::Elem: Clone,
              F: FnMut(&Self::Elem, &Self::Elem) -> Self::Elem;
}

impl<A, S, D> Utils for ArrayBase<S, D>
    where S: Data<Elem=A>,
          D: Dimension,
{
    type Elem = A;
    type Dim = D;
    type Data = S;

    fn max(&self) -> &A
        where A: PartialOrd
    {
        let mut iter = self.iter();
        if let Some(mut max) = iter.next() {
            for elt in iter {
                if elt > max {
                    max = elt;
                }
            }
            max
        } else {
            panic!("empty");
        }
    }
    fn lift<F>(&mut self, mut f: F)
        where F: FnMut(A) -> A, A: Copy,
              S: DataMut<Elem=A>

    {
        for elt in self {
            *elt = f(*elt);
        }
    }

    fn fold_axis<F>(&self, axis: Axis, mut f: F) -> Array<A, D::Smaller>
        where D: RemoveAxis,
              F: FnMut(&A, &A) -> A,
              A: Clone,
    {
        let len = self.shape()[axis.axis()];
        let mut row = self.subview(axis, 0).to_owned();
        for i in 1..len {
            let r2 = self.subview(axis, i);
            for (a, b) in row.iter_mut().zip(r2) {
                *a = f(a, b);
            }
        }
        row
    }
}
<commit_msg>Update ndarray-tests for ndarray 0.6<commit_after>
#[macro_use(s)]
extern crate ndarray;
extern crate ndarray_rand;
extern crate rand;

use ndarray_rand::{RandomExt, F32};
use rand::Rng;

use ndarray::{
    ArrayBase,
    Array,
    Dimension,
    Data,
    DataMut,
    Axis, RemoveAxis,
    LinalgScalar,
    Ix,
};

use rand::distributions::Normal;

// simple, slow, correct (hopefully) mat mul
fn reference_mat_mul<A, S, S2>(lhs: &ArrayBase<S, (Ix, Ix)>, rhs: &ArrayBase<S2, (Ix, Ix)>)
    -> Array<A, (Ix, Ix)>
    where A: LinalgScalar,
          S: Data<Elem=A>,
          S2: Data<Elem=A>,
{
    let ((m, k), (_, n)) = (lhs.dim(), rhs.dim());
    let mut res_elems = Vec::<A>::with_capacity(m * n);
    unsafe {
        res_elems.set_len(m * n);
    }

    let mut i = 0;
    let mut j = 0;
    for rr in &mut res_elems {
        unsafe {
            *rr = (0..k).fold(A::zero(),
                move |s, x| s + *lhs.uget((i, x)) * *rhs.uget((x, j)));
        }
        j += 1;
        if j == n {
            j = 0;
            i += 1;
        }
    }
    unsafe {
        ArrayBase::from_shape_vec_unchecked((m, n), res_elems)
    }
}

fn gen<D>(d: D) -> Array<f32, D>
    where D: Dimension,
{
    Array::random(d, F32(Normal::new(0., 1.)))
}
fn gen_f64<D>(d: D) -> Array<f64, D>
    where D: Dimension,
{
    Array::random(d, Normal::new(0., 1.))
}

#[test]
fn accurate_eye_f32() {
    for i in 0..20 {
        let eye = Array::eye(i);
        for j in 0..20 {
            let a = gen((i, j));
            let a2 = eye.dot(&a);
            if !a.all_close(&a2, 1e-6) {
                panic!("Arrays are not equal:\n{:?}\n{:?}\n{:?}", a, a2, &a2 - &a);
            }
            let a3 = a.t().dot(&eye);
            if !a.t().all_close(&a3, 1e-6) {
                panic!("Arrays are not equal:\n{:?}\n{:?}\n{:?}", a.t(), a3, &a3 - &a.t());
            }
        }
    }
    // pick a few random sizes
    let mut rng = rand::weak_rng();
    for _ in 0..10 {
        let i = rng.gen_range(15, 512);
        let j = rng.gen_range(15, 512);
        println!("Testing size {} by {}", i, j);
        let a = gen((i, j));
        let eye = Array::eye(i);
        let a2 = eye.dot(&a);
        if !a.all_close(&a2, 1e-6) {
            panic!("Arrays are not equal:\n{:?}\n{:?}\n{:?}", a, a2, &a2 - &a);
        }
        let a3 = a.t().dot(&eye);
        if !a.t().all_close(&a3, 1e-6) {
            panic!("Arrays are not equal:\n{:?}\n{:?}\n{:?}", a.t(), a3, &a3 - &a.t());
        }
    }
}

#[test]
fn accurate_eye_f64() {
    let abs_tol = 1e-15;
    for i in 0..20 {
        let eye = Array::eye(i);
        for j in 0..20 {
            let a = gen_f64((i, j));
            let a2 = eye.dot(&a);
            if !a.all_close(&a2, abs_tol) {
                panic!("Arrays are not equal:\n{:?}\n{:?}\n{:?}", a, a2, &a2 - &a);
            }
            let a3 = a.t().dot(&eye);
            if !a.t().all_close(&a3, abs_tol) {
                panic!("Arrays are not equal:\n{:?}\n{:?}\n{:?}", a.t(), a3, &a3 - &a.t());
            }
        }
    }
    // pick a few random sizes
    let mut rng = rand::weak_rng();
    for _ in 0..10 {
        let i = rng.gen_range(15, 512);
        let j = rng.gen_range(15, 512);
        println!("Testing size {} by {}", i, j);
        let a = gen_f64((i, j));
        let eye = Array::eye(i);
        let a2 = eye.dot(&a);
        if !a.all_close(&a2, 1e-6) {
            panic!("Arrays are not equal:\n{:?}\n{:?}\n{:?}", a, a2, &a2 - &a);
        }
        let a3 = a.t().dot(&eye);
        if !a.t().all_close(&a3, 1e-6) {
            panic!("Arrays are not equal:\n{:?}\n{:?}\n{:?}", a.t(), a3, &a3 - &a.t());
        }
    }
}

#[test]
fn accurate_mul_f32() {
    // pick a few random sizes
    let mut rng = rand::weak_rng();
    for i in 0..20 {
        let m = rng.gen_range(15, 512);
        let k = rng.gen_range(15, 512);
        let n = rng.gen_range(15, 1560);
        let a = gen((m, k));
        let b = gen((n, k));
        let b = b.t();
        let (a, b) = if i > 10 {
            (a.slice(s![..;2, ..;2]),
             b.slice(s![..;2, ..;2]))
        } else { (a.view(), b) };

        println!("Testing size {} by {} by {}", a.shape()[0], a.shape()[1], b.shape()[1]);
        let c = a.dot(&b);
        let reference = reference_mat_mul(&a, &b);
        let diff = (&c - &reference).mapv_into(f32::abs);

        let rtol = 1e-3;
        let atol = 1e-4;
        let crtol = c.mapv(|x| x.abs() * rtol);
        let tol = crtol + atol;
        let tol_m_diff = &diff - &tol;
        let maxdiff = *tol_m_diff.max();
        println!("diff offset from tolerance level= {:.2e}", maxdiff);
        if maxdiff > 0. {
            panic!("results differ");
        }
    }
}

#[test]
fn accurate_mul_f64() {
    // pick a few random sizes
    let mut rng = rand::weak_rng();
    for i in 0..20 {
        let m = rng.gen_range(15, 512);
        let k = rng.gen_range(15, 512);
        let n = rng.gen_range(15, 1560);
        let a = gen_f64((m, k));
        let b = gen_f64((n, k));
        let b = b.t();
        let (a, b) = if i > 10 {
            (a.slice(s![..;2, ..;2]),
             b.slice(s![..;2, ..;2]))
        } else { (a.view(), b) };

        println!("Testing size {} by {} by {}", a.shape()[0], a.shape()[1], b.shape()[1]);
        let c = a.dot(&b);
        let reference = reference_mat_mul(&a, &b);
        let diff = (&c - &reference).mapv_into(f64::abs);

        let rtol = 1e-7;
        let atol = 1e-12;
        let crtol = c.mapv(|x| x.abs() * rtol);
        let tol = crtol + atol;
        let tol_m_diff = &diff - &tol;
        let maxdiff = *tol_m_diff.max();
        println!("diff offset from tolerance level= {:.2e}", maxdiff);
        if maxdiff > 0. {
            panic!("results differ");
        }
    }
}

trait Utils {
    type Elem;
    type Dim;
    type Data;
    fn max(&self) -> &Self::Elem
        where Self::Elem: PartialOrd;
    fn lift<F>(&mut self, F)
        where F: FnMut(Self::Elem) -> Self::Elem, Self::Elem: Copy,
              Self::Data: DataMut;
    fn fold_axis<F>(&self, axis: Axis, f: F) -> Array<Self::Elem, <Self::Dim as RemoveAxis>::Smaller>
        where Self::Dim: RemoveAxis,
              Self::Elem: Clone,
              F: FnMut(&Self::Elem, &Self::Elem) -> Self::Elem;
}

impl<A, S, D> Utils for ArrayBase<S, D>
    where S: Data<Elem=A>,
          D: Dimension,
{
    type Elem = A;
    type Dim = D;
    type Data = S;

    fn max(&self) -> &A
        where A: PartialOrd
    {
        let mut iter = self.iter();
        if let Some(mut max) = iter.next() {
            for elt in iter {
                if elt > max {
                    max = elt;
                }
            }
            max
        } else {
            panic!("empty");
        }
    }
    fn lift<F>(&mut self, mut f: F)
        where F: FnMut(A) -> A, A: Copy,
              S: DataMut<Elem=A>

    {
        for elt in self {
            *elt = f(*elt);
        }
    }

    fn fold_axis<F>(&self, axis: Axis, mut f: F) -> Array<A, D::Smaller>
        where D: RemoveAxis,
              F: FnMut(&A, &A) -> A,
              A: Clone,
    {
        let len = self.shape()[axis.axis()];
        let mut row = self.subview(axis, 0).to_owned();
        for i in 1..len {
            let r2 = self.subview(axis, i);
            for (a, b) in row.iter_mut().zip(r2) {
                *a = f(a, b);
            }
        }
        row
    }
}
<|endoftext|>


<commit_before>use std::collections::HashMap;

use ron::Value;

use crate::theming::{
    config::{ThemeConfig, RESOURCE_KEY},
    Selector, Style, ThemeState,
};

/// Theme is used to read properties for a given selector with a
/// internal state.
#[derive(Debug, Clone, Default, PartialEq)]
pub struct Theme {
    styles: HashMap<String, Style>,
    fonts: HashMap<String, &'static [u8]>,
}

impl Theme {
    /// Creates a theme from the given config.
    pub fn from_config(config: ThemeConfig) -> Self {
        let mut styles = HashMap::new();

        for style_key in config.styles.keys() {
            Theme::read_config(style_key, style_key, &config, &mut styles)
        }

        Theme {
            styles,
            fonts: HashMap::new(),
        }
    }

    /// Registers a new font file as binary.
    pub fn register_font(mut self, key: &str, font: &'static [u8]) -> Self {
        self.fonts.insert(key.to_string(), font);
        self
    }

    /// Returns the map of registered fonts.
    pub fn fonts(&self) -> &HashMap<String, &'static [u8]> {
        &self.fonts
    }

    /// Returns a reference to the style corresponding to the key.
    pub fn style(&self, key: &str) -> Option<&Style> {
        self.styles.get(key)
    }

    pub fn properties(&self, selector: &Selector) -> Option<HashMap<String, Value>> {
        if !selector.dirty() {
            return None;
        }

        if let Some(style) = &selector.style {
            let mut properties = HashMap::new();

            if let Some(style) = self.styles.get(style) {
                for (key, value) in &style.properties {
                    properties.insert(key.clone(), value.clone());
                }

                // reverse order because last active state has highest priority
                for state in style.states.iter().rev() {
                    if selector.states().contains(&state.key) {
                        for (key, value) in &state.properties {
                            // properties of the selected state overrides default properties
                            properties.insert(key.clone(), value.clone());
                        }

                        break;
                    }
                }
            }

            return Some(properties);
        }

        None
    }

    // reads the given config and copy it's data in the given styles map
    fn read_config(
        style_key: &str,
        base_key: &str,
        config: &ThemeConfig,
        styles: &mut HashMap<String, Style>,
    ) {
        if style_key.is_empty() {
            return;
        }

        if !styles.contains_key(style_key) {
            styles.insert(style_key.to_string(), Style::new());
        }

        // start from topmost base
        if let Some(style) = config.styles.get(base_key) {
            if !style.base.is_empty() && style.base != *style_key {
                Theme::read_config(style_key, &style.base, config, styles);
            }
        }

        if let Some(style_config) = config.styles.get(base_key) {
            if let Some(style) = styles.get_mut(style_key) {
                // reads the properties
                for (property_key, property_value) in &style_config.properties {
                    style.properties.insert(
                        property_key.clone(),
                        Theme::read_value(property_value, &config.resources),
                    );
                }

                // reads the states
                for state in &style_config.states {
                    let mut new_state = ThemeState::new(state.key.clone());

                    for (property_key, property_value) in &state.properties {
                        new_state.properties.insert(
                            property_key.clone(),
                            Theme::read_value(property_value, &config.resources),
                        );
                    }

                    // a state with the same name on a lower base style or the indented style overrides the state of a higher base
                    if let Some(pos) = style.states.iter().position(|s| s.key == new_state.key) {
                        style.states.remove(pos);
                        style.states.insert(pos, new_state)
                    } else {
                        style.states.push(new_state);
                    }
                }
            }
        }
    }

    // if the property value is a place holder replace it with the corresponding value of the resources
    fn read_value(property_value: &Value, resources: &HashMap<String, Value>) -> Value {
        if let Ok(value) = property_value.clone().into_rust::<String>() {
            if let Some(replace_value) = resources.get(&value.replace(RESOURCE_KEY, "")) {
                return replace_value.clone();
            }
        }

        property_value.clone()
    }
}
<commit_msg>orbtk_core: update theming documentation<commit_after>use std::collections::HashMap;

use ron::Value;

use crate::theming::{
    config::{ThemeConfig, RESOURCE_KEY},
    Selector, Style, ThemeState,
};

/// Theme is used to read properties for a given selector with an
/// internal state.
#[derive(Debug, Clone, Default, PartialEq)]
pub struct Theme {
    styles: HashMap<String, Style>,
    fonts: HashMap<String, &'static [u8]>,
}

impl Theme {
    /// Creates a theme from the given config.
    pub fn from_config(config: ThemeConfig) -> Self {
        let mut styles = HashMap::new();

        for style_key in config.styles.keys() {
            Theme::read_config(style_key, style_key, &config, &mut styles)
        }

        Theme {
            styles,
            fonts: HashMap::new(),
        }
    }

    /// Registers a new font file as binary.
    pub fn register_font(mut self, key: &str, font: &'static [u8]) -> Self {
        self.fonts.insert(key.to_string(), font);
        self
    }

    /// Returns the map of registered fonts.
    pub fn fonts(&self) -> &HashMap<String, &'static [u8]> {
        &self.fonts
    }

    /// Returns a reference to the style corresponding to the key.
    pub fn style(&self, key: &str) -> Option<&Style> {
        self.styles.get(key)
    }

    pub fn properties(&self, selector: &Selector) -> Option<HashMap<String, Value>> {
        if !selector.dirty() {
            return None;
        }

        if let Some(style) = &selector.style {
            let mut properties = HashMap::new();

            if let Some(style) = self.styles.get(style) {
                for (key, value) in &style.properties {
                    properties.insert(key.clone(), value.clone());
                }

                // reverse order because last active state has highest priority
                for state in style.states.iter().rev() {
                    if selector.states().contains(&state.key) {
                        for (key, value) in &state.properties {
                            // properties of the selected state overrides default properties
                            properties.insert(key.clone(), value.clone());
                        }

                        break;
                    }
                }
            }

            return Some(properties);
        }

        None
    }

    // reads the given config and copy it's data in the given styles map
    fn read_config(
        style_key: &str,
        base_key: &str,
        config: &ThemeConfig,
        styles: &mut HashMap<String, Style>,
    ) {
        if style_key.is_empty() {
            return;
        }

        if !styles.contains_key(style_key) {
            styles.insert(style_key.to_string(), Style::new());
        }

        // start from topmost base
        if let Some(style) = config.styles.get(base_key) {
            if !style.base.is_empty() && style.base != *style_key {
                Theme::read_config(style_key, &style.base, config, styles);
            }
        }

        if let Some(style_config) = config.styles.get(base_key) {
            if let Some(style) = styles.get_mut(style_key) {
                // reads the properties
                for (property_key, property_value) in &style_config.properties {
                    style.properties.insert(
                        property_key.clone(),
                        Theme::read_value(property_value, &config.resources),
                    );
                }

                // reads the states
                for state in &style_config.states {
                    let mut new_state = ThemeState::new(state.key.clone());

                    for (property_key, property_value) in &state.properties {
                        new_state.properties.insert(
                            property_key.clone(),
                            Theme::read_value(property_value, &config.resources),
                        );
                    }

                    // a state with the same name on a lower base style or the indented style overrides the state of a higher base
                    if let Some(pos) = style.states.iter().position(|s| s.key == new_state.key) {
                        style.states.remove(pos);
                        style.states.insert(pos, new_state)
                    } else {
                        style.states.push(new_state);
                    }
                }
            }
        }
    }

    // if the property value is a place holder replace it with the corresponding value of the resources
    fn read_value(property_value: &Value, resources: &HashMap<String, Value>) -> Value {
        if let Ok(value) = property_value.clone().into_rust::<String>() {
            if let Some(replace_value) = resources.get(&value.replace(RESOURCE_KEY, "")) {
                return replace_value.clone();
            }
        }

        property_value.clone()
    }
}
<|endoftext|>


<commit_before>use ra_syntax::{
    ast::{self, AstNode},
    SyntaxKind::{
        BLOCK_EXPR, BREAK_EXPR, COMMENT, LAMBDA_EXPR, LOOP_EXPR, MATCH_ARM, PATH_EXPR, RETURN_EXPR,
        WHITESPACE,
    },
    SyntaxNode,
};
use stdx::format_to;
use test_utils::mark;

use crate::{AssistContext, AssistId, AssistKind, Assists};

// Assist: extract_variable
//
// Extracts subexpression into a variable.
//
// ```
// fn main() {
//     <|>(1 + 2)<|> * 4;
// }
// ```
// ->
// ```
// fn main() {
//     let $0var_name = (1 + 2);
//     var_name * 4;
// }
// ```
pub(crate) fn extract_variable(acc: &mut Assists, ctx: &AssistContext) -> Option<()> {
    if ctx.frange.range.is_empty() {
        return None;
    }
    let node = ctx.covering_element();
    if node.kind() == COMMENT {
        mark::hit!(extract_var_in_comment_is_not_applicable);
        return None;
    }
    let expr = node.ancestors().find_map(valid_target_expr)?;
    let (anchor_stmt, wrap_in_block) = anchor_stmt(&expr)?;
    let indent = anchor_stmt.prev_sibling_or_token()?.as_token()?.clone();
    if indent.kind() != WHITESPACE {
        return None;
    }
    let target = expr.syntax().text_range();
    acc.add(
        AssistId("extract_variable", AssistKind::RefactorExtract),
        "Extract into variable",
        target,
        move |edit| {
            let field_shorthand = match expr.syntax().parent().and_then(ast::RecordField::cast) {
                Some(field) => field.name_ref(),
                None => None,
            };

            let mut buf = String::new();

            let var_name = match &field_shorthand {
                Some(it) => it.to_string(),
                None => "var_name".to_string(),
            };
            let expr_range = match &field_shorthand {
                Some(it) => it.syntax().text_range().cover(expr.syntax().text_range()),
                None => expr.syntax().text_range(),
            };

            if wrap_in_block {
                format_to!(buf, "{{ let {} = ", var_name);
            } else {
                format_to!(buf, "let {} = ", var_name);
            };
            format_to!(buf, "{}", expr.syntax());

            let full_stmt = ast::ExprStmt::cast(anchor_stmt.clone());
            let is_full_stmt = if let Some(expr_stmt) = &full_stmt {
                Some(expr.syntax().clone()) == expr_stmt.expr().map(|e| e.syntax().clone())
            } else {
                false
            };
            if is_full_stmt {
                mark::hit!(test_extract_var_expr_stmt);
                if full_stmt.unwrap().semicolon_token().is_none() {
                    buf.push_str(";");
                }
                match ctx.config.snippet_cap {
                    Some(cap) => {
                        let snip = buf
                            .replace(&format!("let {}", var_name), &format!("let $0{}", var_name));
                        edit.replace_snippet(cap, expr_range, snip)
                    }
                    None => edit.replace(expr_range, buf),
                }
                return;
            }

            buf.push_str(";");

            // We want to maintain the indent level,
            // but we do not want to duplicate possible
            // extra newlines in the indent block
            let text = indent.text();
            if text.starts_with('\n') {
                buf.push_str("\n");
                buf.push_str(text.trim_start_matches('\n'));
            } else {
                buf.push_str(text);
            }

            edit.replace(expr_range, var_name.clone());
            let offset = anchor_stmt.text_range().start();
            match ctx.config.snippet_cap {
                Some(cap) => {
                    let snip =
                        buf.replace(&format!("let {}", var_name), &format!("let $0{}", var_name));
                    edit.insert_snippet(cap, offset, snip)
                }
                None => edit.insert(offset, buf),
            }

            if wrap_in_block {
                edit.insert(anchor_stmt.text_range().end(), " }");
            }
        },
    )
}

/// Check whether the node is a valid expression which can be extracted to a variable.
/// In general that's true for any expression, but in some cases that would produce invalid code.
fn valid_target_expr(node: SyntaxNode) -> Option<ast::Expr> {
    match node.kind() {
        PATH_EXPR | LOOP_EXPR => None,
        BREAK_EXPR => ast::BreakExpr::cast(node).and_then(|e| e.expr()),
        RETURN_EXPR => ast::ReturnExpr::cast(node).and_then(|e| e.expr()),
        BLOCK_EXPR => {
            ast::BlockExpr::cast(node).filter(|it| it.is_standalone()).map(ast::Expr::from)
        }
        _ => ast::Expr::cast(node),
    }
}

/// Returns the syntax node which will follow the freshly extractd var
/// and a boolean indicating whether we have to wrap it within a { } block
/// to produce correct code.
/// It can be a statement, the last in a block expression or a wanna be block
/// expression like a lambda or match arm.
fn anchor_stmt(expr: &ast::Expr) -> Option<(SyntaxNode, bool)> {
    expr.syntax().ancestors().find_map(|node| {
        if let Some(expr) = node.parent().and_then(ast::BlockExpr::cast).and_then(|it| it.expr()) {
            if expr.syntax() == &node {
                mark::hit!(test_extract_var_last_expr);
                return Some((node, false));
            }
        }

        if let Some(parent) = node.parent() {
            if parent.kind() == MATCH_ARM || parent.kind() == LAMBDA_EXPR {
                return Some((node, true));
            }
        }

        if ast::Stmt::cast(node.clone()).is_some() {
            return Some((node, false));
        }

        None
    })
}

#[cfg(test)]
mod tests {
    use test_utils::mark;

    use crate::tests::{check_assist, check_assist_not_applicable, check_assist_target};

    use super::*;

    #[test]
    fn test_extract_var_simple() {
        check_assist(
            extract_variable,
            r#"
fn foo() {
    foo(<|>1 + 1<|>);
}"#,
            r#"
fn foo() {
    let $0var_name = 1 + 1;
    foo(var_name);
}"#,
        );
    }

    #[test]
    fn extract_var_in_comment_is_not_applicable() {
        mark::check!(extract_var_in_comment_is_not_applicable);
        check_assist_not_applicable(extract_variable, "fn main() { 1 + /* <|>comment<|> */ 1; }");
    }

    #[test]
    fn test_extract_var_expr_stmt() {
        mark::check!(test_extract_var_expr_stmt);
        check_assist(
            extract_variable,
            r#"
fn foo() {
    <|>1 + 1<|>;
}"#,
            r#"
fn foo() {
    let $0var_name = 1 + 1;
}"#,
        );
        check_assist(
            extract_variable,
            "
fn foo() {
    <|>{ let x = 0; x }<|>
    something_else();
}",
            "
fn foo() {
    let $0var_name = { let x = 0; x };
    something_else();
}",
        );
    }

    #[test]
    fn test_extract_var_part_of_expr_stmt() {
        check_assist(
            extract_variable,
            "
fn foo() {
    <|>1<|> + 1;
}",
            "
fn foo() {
    let $0var_name = 1;
    var_name + 1;
}",
        );
    }

    #[test]
    fn test_extract_var_last_expr() {
        mark::check!(test_extract_var_last_expr);
        check_assist(
            extract_variable,
            r#"
fn foo() {
    bar(<|>1 + 1<|>)
}
"#,
            r#"
fn foo() {
    let $0var_name = 1 + 1;
    bar(var_name)
}
"#,
        );
        check_assist(
            extract_variable,
            r#"
fn foo() {
    <|>bar(1 + 1)<|>
}
"#,
            r#"
fn foo() {
    let $0var_name = bar(1 + 1);
    var_name
}
"#,
        )
    }

    #[test]
    fn test_extract_var_in_match_arm_no_block() {
        check_assist(
            extract_variable,
            "
fn main() {
    let x = true;
    let tuple = match x {
        true => (<|>2 + 2<|>, true)
        _ => (0, false)
    };
}
",
            "
fn main() {
    let x = true;
    let tuple = match x {
        true => { let $0var_name = 2 + 2; (var_name, true) }
        _ => (0, false)
    };
}
",
        );
    }

    #[test]
    fn test_extract_var_in_match_arm_with_block() {
        check_assist(
            extract_variable,
            "
fn main() {
    let x = true;
    let tuple = match x {
        true => {
            let y = 1;
            (<|>2 + y<|>, true)
        }
        _ => (0, false)
    };
}
",
            "
fn main() {
    let x = true;
    let tuple = match x {
        true => {
            let y = 1;
            let $0var_name = 2 + y;
            (var_name, true)
        }
        _ => (0, false)
    };
}
",
        );
    }

    #[test]
    fn test_extract_var_in_closure_no_block() {
        check_assist(
            extract_variable,
            "
fn main() {
    let lambda = |x: u32| <|>x * 2<|>;
}
",
            "
fn main() {
    let lambda = |x: u32| { let $0var_name = x * 2; var_name };
}
",
        );
    }

    #[test]
    fn test_extract_var_in_closure_with_block() {
        check_assist(
            extract_variable,
            "
fn main() {
    let lambda = |x: u32| { <|>x * 2<|> };
}
",
            "
fn main() {
    let lambda = |x: u32| { let $0var_name = x * 2; var_name };
}
",
        );
    }

    #[test]
    fn test_extract_var_path_simple() {
        check_assist(
            extract_variable,
            "
fn main() {
    let o = <|>Some(true)<|>;
}
",
            "
fn main() {
    let $0var_name = Some(true);
    let o = var_name;
}
",
        );
    }

    #[test]
    fn test_extract_var_path_method() {
        check_assist(
            extract_variable,
            "
fn main() {
    let v = <|>bar.foo()<|>;
}
",
            "
fn main() {
    let $0var_name = bar.foo();
    let v = var_name;
}
",
        );
    }

    #[test]
    fn test_extract_var_return() {
        check_assist(
            extract_variable,
            "
fn foo() -> u32 {
    <|>return 2 + 2<|>;
}
",
            "
fn foo() -> u32 {
    let $0var_name = 2 + 2;
    return var_name;
}
",
        );
    }

    #[test]
    fn test_extract_var_does_not_add_extra_whitespace() {
        check_assist(
            extract_variable,
            "
fn foo() -> u32 {

    <|>return 2 + 2<|>;
}
",
            "
fn foo() -> u32 {

    let $0var_name = 2 + 2;
    return var_name;
}
",
        );

        check_assist(
            extract_variable,
            "
fn foo() -> u32 {

        <|>return 2 + 2<|>;
}
",
            "
fn foo() -> u32 {

        let $0var_name = 2 + 2;
        return var_name;
}
",
        );

        check_assist(
            extract_variable,
            "
fn foo() -> u32 {
    let foo = 1;

    // bar

    <|>return 2 + 2<|>;
}
",
            "
fn foo() -> u32 {
    let foo = 1;

    // bar

    let $0var_name = 2 + 2;
    return var_name;
}
",
        );
    }

    #[test]
    fn test_extract_var_break() {
        check_assist(
            extract_variable,
            "
fn main() {
    let result = loop {
        <|>break 2 + 2<|>;
    };
}
",
            "
fn main() {
    let result = loop {
        let $0var_name = 2 + 2;
        break var_name;
    };
}
",
        );
    }

    #[test]
    fn test_extract_var_for_cast() {
        check_assist(
            extract_variable,
            "
fn main() {
    let v = <|>0f32 as u32<|>;
}
",
            "
fn main() {
    let $0var_name = 0f32 as u32;
    let v = var_name;
}
",
        );
    }

    #[test]
    fn extract_var_field_shorthand() {
        check_assist(
            extract_variable,
            r#"
struct S {
    foo: i32
}

fn main() {
    S { foo: <|>1 + 1<|> }
}
"#,
            r#"
struct S {
    foo: i32
}

fn main() {
    let $0foo = 1 + 1;
    S { foo }
}
"#,
        )
    }

    #[test]
    fn test_extract_var_for_return_not_applicable() {
        check_assist_not_applicable(extract_variable, "fn foo() { <|>return<|>; } ");
    }

    #[test]
    fn test_extract_var_for_break_not_applicable() {
        check_assist_not_applicable(extract_variable, "fn main() { loop { <|>break<|>; }; }");
    }

    // FIXME: This is not quite correct, but good enough(tm) for the sorting heuristic
    #[test]
    fn extract_var_target() {
        check_assist_target(extract_variable, "fn foo() -> u32 { <|>return 2 + 2<|>; }", "2 + 2");

        check_assist_target(
            extract_variable,
            "
fn main() {
    let x = true;
    let tuple = match x {
        true => (<|>2 + 2<|>, true)
        _ => (0, false)
    };
}
",
            "2 + 2",
        );
    }
}
<commit_msg>Cleanup extact variable<commit_after>use ra_syntax::{
    ast::{self, AstNode},
    SyntaxKind::{
        BLOCK_EXPR, BREAK_EXPR, COMMENT, LAMBDA_EXPR, LOOP_EXPR, MATCH_ARM, PATH_EXPR, RETURN_EXPR,
    },
    SyntaxNode,
};
use stdx::format_to;
use test_utils::mark;

use crate::{AssistContext, AssistId, AssistKind, Assists};

// Assist: extract_variable
//
// Extracts subexpression into a variable.
//
// ```
// fn main() {
//     <|>(1 + 2)<|> * 4;
// }
// ```
// ->
// ```
// fn main() {
//     let $0var_name = (1 + 2);
//     var_name * 4;
// }
// ```
pub(crate) fn extract_variable(acc: &mut Assists, ctx: &AssistContext) -> Option<()> {
    if ctx.frange.range.is_empty() {
        return None;
    }
    let node = ctx.covering_element();
    if node.kind() == COMMENT {
        mark::hit!(extract_var_in_comment_is_not_applicable);
        return None;
    }
    let to_extract = node.ancestors().find_map(valid_target_expr)?;
    let anchor = Anchor::from(&to_extract)?;
    let indent = anchor.syntax().prev_sibling_or_token()?.as_token()?.clone();
    let target = to_extract.syntax().text_range();
    acc.add(
        AssistId("extract_variable", AssistKind::RefactorExtract),
        "Extract into variable",
        target,
        move |edit| {
            let field_shorthand =
                match to_extract.syntax().parent().and_then(ast::RecordField::cast) {
                    Some(field) => field.name_ref(),
                    None => None,
                };

            let mut buf = String::new();

            let var_name = match &field_shorthand {
                Some(it) => it.to_string(),
                None => "var_name".to_string(),
            };
            let expr_range = match &field_shorthand {
                Some(it) => it.syntax().text_range().cover(to_extract.syntax().text_range()),
                None => to_extract.syntax().text_range(),
            };

            if let Anchor::WrapInBlock(_) = anchor {
                format_to!(buf, "{{ let {} = ", var_name);
            } else {
                format_to!(buf, "let {} = ", var_name);
            };
            format_to!(buf, "{}", to_extract.syntax());

            if let Anchor::Replace(stmt) = anchor {
                mark::hit!(test_extract_var_expr_stmt);
                if stmt.semicolon_token().is_none() {
                    buf.push_str(";");
                }
                match ctx.config.snippet_cap {
                    Some(cap) => {
                        let snip = buf
                            .replace(&format!("let {}", var_name), &format!("let $0{}", var_name));
                        edit.replace_snippet(cap, expr_range, snip)
                    }
                    None => edit.replace(expr_range, buf),
                }
                return;
            }

            buf.push_str(";");

            // We want to maintain the indent level,
            // but we do not want to duplicate possible
            // extra newlines in the indent block
            let text = indent.text();
            if text.starts_with('\n') {
                buf.push_str("\n");
                buf.push_str(text.trim_start_matches('\n'));
            } else {
                buf.push_str(text);
            }

            edit.replace(expr_range, var_name.clone());
            let offset = anchor.syntax().text_range().start();
            match ctx.config.snippet_cap {
                Some(cap) => {
                    let snip =
                        buf.replace(&format!("let {}", var_name), &format!("let $0{}", var_name));
                    edit.insert_snippet(cap, offset, snip)
                }
                None => edit.insert(offset, buf),
            }

            if let Anchor::WrapInBlock(_) = anchor {
                edit.insert(anchor.syntax().text_range().end(), " }");
            }
        },
    )
}

/// Check whether the node is a valid expression which can be extracted to a variable.
/// In general that's true for any expression, but in some cases that would produce invalid code.
fn valid_target_expr(node: SyntaxNode) -> Option<ast::Expr> {
    match node.kind() {
        PATH_EXPR | LOOP_EXPR => None,
        BREAK_EXPR => ast::BreakExpr::cast(node).and_then(|e| e.expr()),
        RETURN_EXPR => ast::ReturnExpr::cast(node).and_then(|e| e.expr()),
        BLOCK_EXPR => {
            ast::BlockExpr::cast(node).filter(|it| it.is_standalone()).map(ast::Expr::from)
        }
        _ => ast::Expr::cast(node),
    }
}

enum Anchor {
    Before(SyntaxNode),
    Replace(ast::ExprStmt),
    WrapInBlock(SyntaxNode),
}

impl Anchor {
    fn from(to_extract: &ast::Expr) -> Option<Anchor> {
        to_extract.syntax().ancestors().find_map(|node| {
            if let Some(expr) =
                node.parent().and_then(ast::BlockExpr::cast).and_then(|it| it.expr())
            {
                if expr.syntax() == &node {
                    mark::hit!(test_extract_var_last_expr);
                    return Some(Anchor::Before(node));
                }
            }

            if let Some(parent) = node.parent() {
                if parent.kind() == MATCH_ARM || parent.kind() == LAMBDA_EXPR {
                    return Some(Anchor::WrapInBlock(node));
                }
            }

            if let Some(stmt) = ast::Stmt::cast(node.clone()) {
                if let ast::Stmt::ExprStmt(stmt) = stmt {
                    if stmt.expr().as_ref() == Some(to_extract) {
                        return Some(Anchor::Replace(stmt));
                    }
                }
                return Some(Anchor::Before(node));
            }
            None
        })
    }

    fn syntax(&self) -> &SyntaxNode {
        match self {
            Anchor::Before(it) | Anchor::WrapInBlock(it) => it,
            Anchor::Replace(stmt) => stmt.syntax(),
        }
    }
}

#[cfg(test)]
mod tests {
    use test_utils::mark;

    use crate::tests::{check_assist, check_assist_not_applicable, check_assist_target};

    use super::*;

    #[test]
    fn test_extract_var_simple() {
        check_assist(
            extract_variable,
            r#"
fn foo() {
    foo(<|>1 + 1<|>);
}"#,
            r#"
fn foo() {
    let $0var_name = 1 + 1;
    foo(var_name);
}"#,
        );
    }

    #[test]
    fn extract_var_in_comment_is_not_applicable() {
        mark::check!(extract_var_in_comment_is_not_applicable);
        check_assist_not_applicable(extract_variable, "fn main() { 1 + /* <|>comment<|> */ 1; }");
    }

    #[test]
    fn test_extract_var_expr_stmt() {
        mark::check!(test_extract_var_expr_stmt);
        check_assist(
            extract_variable,
            r#"
fn foo() {
    <|>1 + 1<|>;
}"#,
            r#"
fn foo() {
    let $0var_name = 1 + 1;
}"#,
        );
        check_assist(
            extract_variable,
            "
fn foo() {
    <|>{ let x = 0; x }<|>
    something_else();
}",
            "
fn foo() {
    let $0var_name = { let x = 0; x };
    something_else();
}",
        );
    }

    #[test]
    fn test_extract_var_part_of_expr_stmt() {
        check_assist(
            extract_variable,
            "
fn foo() {
    <|>1<|> + 1;
}",
            "
fn foo() {
    let $0var_name = 1;
    var_name + 1;
}",
        );
    }

    #[test]
    fn test_extract_var_last_expr() {
        mark::check!(test_extract_var_last_expr);
        check_assist(
            extract_variable,
            r#"
fn foo() {
    bar(<|>1 + 1<|>)
}
"#,
            r#"
fn foo() {
    let $0var_name = 1 + 1;
    bar(var_name)
}
"#,
        );
        check_assist(
            extract_variable,
            r#"
fn foo() {
    <|>bar(1 + 1)<|>
}
"#,
            r#"
fn foo() {
    let $0var_name = bar(1 + 1);
    var_name
}
"#,
        )
    }

    #[test]
    fn test_extract_var_in_match_arm_no_block() {
        check_assist(
            extract_variable,
            "
fn main() {
    let x = true;
    let tuple = match x {
        true => (<|>2 + 2<|>, true)
        _ => (0, false)
    };
}
",
            "
fn main() {
    let x = true;
    let tuple = match x {
        true => { let $0var_name = 2 + 2; (var_name, true) }
        _ => (0, false)
    };
}
",
        );
    }

    #[test]
    fn test_extract_var_in_match_arm_with_block() {
        check_assist(
            extract_variable,
            "
fn main() {
    let x = true;
    let tuple = match x {
        true => {
            let y = 1;
            (<|>2 + y<|>, true)
        }
        _ => (0, false)
    };
}
",
            "
fn main() {
    let x = true;
    let tuple = match x {
        true => {
            let y = 1;
            let $0var_name = 2 + y;
            (var_name, true)
        }
        _ => (0, false)
    };
}
",
        );
    }

    #[test]
    fn test_extract_var_in_closure_no_block() {
        check_assist(
            extract_variable,
            "
fn main() {
    let lambda = |x: u32| <|>x * 2<|>;
}
",
            "
fn main() {
    let lambda = |x: u32| { let $0var_name = x * 2; var_name };
}
",
        );
    }

    #[test]
    fn test_extract_var_in_closure_with_block() {
        check_assist(
            extract_variable,
            "
fn main() {
    let lambda = |x: u32| { <|>x * 2<|> };
}
",
            "
fn main() {
    let lambda = |x: u32| { let $0var_name = x * 2; var_name };
}
",
        );
    }

    #[test]
    fn test_extract_var_path_simple() {
        check_assist(
            extract_variable,
            "
fn main() {
    let o = <|>Some(true)<|>;
}
",
            "
fn main() {
    let $0var_name = Some(true);
    let o = var_name;
}
",
        );
    }

    #[test]
    fn test_extract_var_path_method() {
        check_assist(
            extract_variable,
            "
fn main() {
    let v = <|>bar.foo()<|>;
}
",
            "
fn main() {
    let $0var_name = bar.foo();
    let v = var_name;
}
",
        );
    }

    #[test]
    fn test_extract_var_return() {
        check_assist(
            extract_variable,
            "
fn foo() -> u32 {
    <|>return 2 + 2<|>;
}
",
            "
fn foo() -> u32 {
    let $0var_name = 2 + 2;
    return var_name;
}
",
        );
    }

    #[test]
    fn test_extract_var_does_not_add_extra_whitespace() {
        check_assist(
            extract_variable,
            "
fn foo() -> u32 {

    <|>return 2 + 2<|>;
}
",
            "
fn foo() -> u32 {

    let $0var_name = 2 + 2;
    return var_name;
}
",
        );

        check_assist(
            extract_variable,
            "
fn foo() -> u32 {

        <|>return 2 + 2<|>;
}
",
            "
fn foo() -> u32 {

        let $0var_name = 2 + 2;
        return var_name;
}
",
        );

        check_assist(
            extract_variable,
            "
fn foo() -> u32 {
    let foo = 1;

    // bar

    <|>return 2 + 2<|>;
}
",
            "
fn foo() -> u32 {
    let foo = 1;

    // bar

    let $0var_name = 2 + 2;
    return var_name;
}
",
        );
    }

    #[test]
    fn test_extract_var_break() {
        check_assist(
            extract_variable,
            "
fn main() {
    let result = loop {
        <|>break 2 + 2<|>;
    };
}
",
            "
fn main() {
    let result = loop {
        let $0var_name = 2 + 2;
        break var_name;
    };
}
",
        );
    }

    #[test]
    fn test_extract_var_for_cast() {
        check_assist(
            extract_variable,
            "
fn main() {
    let v = <|>0f32 as u32<|>;
}
",
            "
fn main() {
    let $0var_name = 0f32 as u32;
    let v = var_name;
}
",
        );
    }

    #[test]
    fn extract_var_field_shorthand() {
        check_assist(
            extract_variable,
            r#"
struct S {
    foo: i32
}

fn main() {
    S { foo: <|>1 + 1<|> }
}
"#,
            r#"
struct S {
    foo: i32
}

fn main() {
    let $0foo = 1 + 1;
    S { foo }
}
"#,
        )
    }

    #[test]
    fn test_extract_var_for_return_not_applicable() {
        check_assist_not_applicable(extract_variable, "fn foo() { <|>return<|>; } ");
    }

    #[test]
    fn test_extract_var_for_break_not_applicable() {
        check_assist_not_applicable(extract_variable, "fn main() { loop { <|>break<|>; }; }");
    }

    // FIXME: This is not quite correct, but good enough(tm) for the sorting heuristic
    #[test]
    fn extract_var_target() {
        check_assist_target(extract_variable, "fn foo() -> u32 { <|>return 2 + 2<|>; }", "2 + 2");

        check_assist_target(
            extract_variable,
            "
fn main() {
    let x = true;
    let tuple = match x {
        true => (<|>2 + 2<|>, true)
        _ => (0, false)
    };
}
",
            "2 + 2",
        );
    }
}
<|endoftext|>


<commit_before>use std::cell::{Cell, Ref, RefCell};
use std::cmp::min;

use cairo::{self, ImageSurface};
use markup5ever::{local_name, LocalName};

use crate::drawing_ctx::DrawingCtx;
use crate::error::{AttributeResultExt, NodeError};
use crate::node::{NodeResult, NodeTrait, NodeType, RsvgNode};
use crate::number_list::{NumberList, NumberListError, NumberListLength};
use crate::parsers::{self, ParseError};
use crate::property_bag::PropertyBag;
use crate::surface_utils::{
    iterators::Pixels,
    shared_surface::SharedImageSurface,
    ImageSurfaceDataExt,
    Pixel,
};
use crate::util::clamp;

use super::context::{FilterContext, FilterOutput, FilterResult};
use super::{Filter, FilterError, PrimitiveWithInput};

/// The `feComponentTransfer` filter primitive.
pub struct ComponentTransfer {
    base: PrimitiveWithInput,
}

/// Pixel components that can be influenced by `feComponentTransfer`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Channel {
    R,
    G,
    B,
    A,
}

/// Component transfer function types.
#[derive(Debug, Clone, Copy)]
enum FunctionType {
    Identity,
    Table,
    Discrete,
    Linear,
    Gamma,
}

/// The `<feFuncX>` element (X is R, G, B or A).
pub struct FuncX {
    channel: Channel,
    function_type: Cell<FunctionType>,
    table_values: RefCell<Vec<f64>>,
    slope: Cell<f64>,
    intercept: Cell<f64>,
    amplitude: Cell<f64>,
    exponent: Cell<f64>,
    offset: Cell<f64>,
}

/// The compute function parameters.
struct FunctionParameters<'a> {
    table_values: Ref<'a, Vec<f64>>,
    slope: f64,
    intercept: f64,
    amplitude: f64,
    exponent: f64,
    offset: f64,
}

/// The compute function type.
type Function = fn(&FunctionParameters<'_>, f64) -> f64;

/// The identity component transfer function.
fn identity(_: &FunctionParameters<'_>, value: f64) -> f64 {
    value
}

/// The table component transfer function.
fn table(params: &FunctionParameters<'_>, value: f64) -> f64 {
    let n = params.table_values.len() - 1;
    let k = (value * (n as f64)).floor() as usize;

    let k = min(k, n); // Just in case.

    if k == n {
        return params.table_values[k];
    }

    let vk = params.table_values[k];
    let vk1 = params.table_values[k + 1];
    let k = k as f64;
    let n = n as f64;

    vk + (value - k / n) * n * (vk1 - vk)
}

/// The discrete component transfer function.
fn discrete(params: &FunctionParameters<'_>, value: f64) -> f64 {
    let n = params.table_values.len();
    let k = (value * (n as f64)).floor() as usize;

    params.table_values[min(k, n - 1)]
}

/// The linear component transfer function.
fn linear(params: &FunctionParameters<'_>, value: f64) -> f64 {
    params.slope * value + params.intercept
}

/// The gamma component transfer function.
fn gamma(params: &FunctionParameters<'_>, value: f64) -> f64 {
    params.amplitude * value.powf(params.exponent) + params.offset
}

impl Default for ComponentTransfer {
    /// Constructs a new `ComponentTransfer` with empty properties.
    #[inline]
    fn default() -> ComponentTransfer {
        ComponentTransfer {
            base: PrimitiveWithInput::new::<Self>(),
        }
    }
}

impl Default for FuncX {
    #[inline]
    fn default() -> Self {
        Self {
            channel: Channel::R,
            function_type: Cell::new(FunctionType::Identity),
            table_values: RefCell::new(Vec::new()),
            slope: Cell::new(1f64),
            intercept: Cell::new(0f64),
            amplitude: Cell::new(1f64),
            exponent: Cell::new(1f64),
            offset: Cell::new(0f64),
        }
    }
}

impl FuncX {
    /// Constructs a new `FuncR` with empty properties.
    #[inline]
    pub fn new_r() -> Self {
        Self {
            channel: Channel::R,
            ..Default::default()
        }
    }

    /// Constructs a new `FuncG` with empty properties.
    #[inline]
    pub fn new_g() -> Self {
        Self {
            channel: Channel::G,
            ..Default::default()
        }
    }

    /// Constructs a new `FuncB` with empty properties.
    #[inline]
    pub fn new_b() -> Self {
        Self {
            channel: Channel::B,
            ..Default::default()
        }
    }

    /// Constructs a new `FuncA` with empty properties.
    #[inline]
    pub fn new_a() -> Self {
        Self {
            channel: Channel::A,
            ..Default::default()
        }
    }

    /// Returns the component transfer function parameters.
    #[inline]
    fn function_parameters(&self) -> FunctionParameters<'_> {
        FunctionParameters {
            table_values: self.table_values.borrow(),
            slope: self.slope.get(),
            intercept: self.intercept.get(),
            amplitude: self.amplitude.get(),
            exponent: self.exponent.get(),
            offset: self.offset.get(),
        }
    }

    /// Returns the component transfer function.
    #[inline]
    fn function(&self) -> Function {
        match self.function_type.get() {
            FunctionType::Identity => identity,
            FunctionType::Table => table,
            FunctionType::Discrete => discrete,
            FunctionType::Linear => linear,
            FunctionType::Gamma => gamma,
        }
    }
}

impl NodeTrait for ComponentTransfer {
    impl_node_as_filter!();

    #[inline]
    fn set_atts(&mut self, parent: Option<&RsvgNode>, pbag: &PropertyBag<'_>) -> NodeResult {
        self.base.set_atts(parent, pbag)
    }
}

impl NodeTrait for FuncX {
    #[inline]
    fn set_atts(&mut self, _parent: Option<&RsvgNode>, pbag: &PropertyBag<'_>) -> NodeResult {
        for (attr, value) in pbag.iter() {
            match attr {
                local_name!("type") => self.function_type.set(FunctionType::parse(attr, value)?),
                local_name!("tableValues") => {
                    let NumberList(v) = NumberList::parse_str(value, NumberListLength::Unbounded)
                        .map_err(|err| {
                        if let NumberListError::Parse(err) = err {
                            NodeError::parse_error(attr, err)
                        } else {
                            panic!("unexpected number list error");
                        }
                    })?;
                    self.table_values.replace(v);
                }
                local_name!("slope") => self.slope.set(
                    parsers::number(value).attribute(attr)?,
                ),
                local_name!("intercept") => self.intercept.set(
                    parsers::number(value).attribute(attr)?,
                ),
                local_name!("amplitude") => self.amplitude.set(
                    parsers::number(value).attribute(attr)?,
                ),
                local_name!("exponent") => self.exponent.set(
                    parsers::number(value).attribute(attr)?,
                ),
                local_name!("offset") => self.offset.set(
                    parsers::number(value).attribute(attr)?,
                ),
                _ => (),
            }
        }

        // The table function type with empty table_values is considered an identity
        // function.
        match self.function_type.get() {
            FunctionType::Table | FunctionType::Discrete => {
                if self.table_values.borrow().is_empty() {
                    self.function_type.set(FunctionType::Identity);
                }
            }
            _ => (),
        }

        Ok(())
    }
}

macro_rules! func_or_default {
    ($func_node:ident, $func_data:ident, $func_default:ident) => {
        match $func_node {
            Some(ref f) => {
                $func_data = f.borrow();
                $func_data.get_impl::<FuncX>()
            }
            _ => &$func_default,
        };
    };
}

impl Filter for ComponentTransfer {
    fn render(
        &self,
        node: &RsvgNode,
        ctx: &FilterContext,
        draw_ctx: &mut DrawingCtx,
    ) -> Result<FilterResult, FilterError> {
        let input = self.base.get_input(ctx, draw_ctx)?;
        let bounds = self
            .base
            .get_bounds(ctx)
            .add_input(&input)
            .into_irect(draw_ctx);

        // Create the output surface.
        let mut output_surface = ImageSurface::create(
            cairo::Format::ARgb32,
            ctx.source_graphic().width(),
            ctx.source_graphic().height(),
        )?;

        // Get a node for every pixel component.
        let get_node = |channel| {
            node.children()
                .rev()
                .filter(|c| match c.borrow().get_type() {
                    NodeType::ComponentTransferFunctionA
                    | NodeType::ComponentTransferFunctionB
                    | NodeType::ComponentTransferFunctionG
                    | NodeType::ComponentTransferFunctionR => true,
                    _ => false,
                })
                .find(|c| c.borrow().get_impl::<FuncX>().channel == channel)
        };

        let func_r_node = get_node(Channel::R);
        let func_g_node = get_node(Channel::G);
        let func_b_node = get_node(Channel::B);
        let func_a_node = get_node(Channel::A);

        for node in [&func_r_node, &func_g_node, &func_b_node, &func_a_node]
            .iter()
            .filter_map(|x| x.as_ref())
        {
            if node.borrow().is_in_error() {
                return Err(FilterError::ChildNodeInError);
            }
        }

        // This is the default node that performs an identity transformation.
        let func_default = FuncX::default();

        // We need to tell the borrow checker that these live long enough
        let func_r_data;
        let func_g_data;
        let func_b_data;
        let func_a_data;

        let func_r = func_or_default!(func_r_node, func_r_data, func_default);
        let func_g = func_or_default!(func_g_node, func_g_data, func_default);
        let func_b = func_or_default!(func_b_node, func_b_data, func_default);
        let func_a = func_or_default!(func_a_node, func_a_data, func_default);

        #[inline]
        fn compute_func<'a>(func: &'a FuncX) -> impl Fn(u8, f64, f64) -> u8 + 'a {
            let compute = func.function();
            let params = func.function_parameters();

            move |value, alpha, new_alpha| {
                let value = f64::from(value) / 255f64;

                let unpremultiplied = if alpha == 0f64 { 0f64 } else { value / alpha };

                let new_value = compute(&params, unpremultiplied);
                let new_value = clamp(new_value, 0f64, 1f64);

                ((new_value * new_alpha * 255f64) + 0.5) as u8
            }
        }

        let compute_r = compute_func(&func_r);
        let compute_g = compute_func(&func_g);
        let compute_b = compute_func(&func_b);

        // Alpha gets special handling since everything else depends on it.
        let compute_a = func_a.function();
        let params_a = func_a.function_parameters();
        let compute_a = |alpha| compute_a(&params_a, alpha);

        // Do the actual processing.
        let output_stride = output_surface.get_stride() as usize;
        {
            let mut output_data = output_surface.get_data().unwrap();

            for (x, y, pixel) in Pixels::new(input.surface(), bounds) {
                let alpha = f64::from(pixel.a) / 255f64;
                let new_alpha = compute_a(alpha);

                let output_pixel = Pixel {
                    r: compute_r(pixel.r, alpha, new_alpha),
                    g: compute_g(pixel.g, alpha, new_alpha),
                    b: compute_b(pixel.b, alpha, new_alpha),
                    a: ((new_alpha * 255f64) + 0.5) as u8,
                };

                output_data.set_pixel(output_stride, output_pixel, x, y);
            }
        }

        Ok(FilterResult {
            name: self.base.result.borrow().clone(),
            output: FilterOutput {
                surface: SharedImageSurface::new(output_surface, input.surface().surface_type())?,
                bounds,
            },
        })
    }

    fn is_affected_by_color_interpolation_filters(&self) -> bool {
        true
    }
}

impl FunctionType {
    fn parse(attr: LocalName, s: &str) -> Result<Self, NodeError> {
        match s {
            "identity" => Ok(FunctionType::Identity),
            "table" => Ok(FunctionType::Table),
            "discrete" => Ok(FunctionType::Discrete),
            "linear" => Ok(FunctionType::Linear),
            "gamma" => Ok(FunctionType::Gamma),
            _ => Err(NodeError::parse_error(
                attr,
                ParseError::new("invalid value"),
            )),
        }
    }
}
<commit_msg>filters/component_transfer: remove interior mutability<commit_after>use std::cmp::min;

use cairo::{self, ImageSurface};
use markup5ever::{local_name, LocalName};

use crate::drawing_ctx::DrawingCtx;
use crate::error::{AttributeResultExt, NodeError};
use crate::node::{NodeResult, NodeTrait, NodeType, RsvgNode};
use crate::number_list::{NumberList, NumberListError, NumberListLength};
use crate::parsers::{self, ParseError};
use crate::property_bag::PropertyBag;
use crate::surface_utils::{
    iterators::Pixels,
    shared_surface::SharedImageSurface,
    ImageSurfaceDataExt,
    Pixel,
};
use crate::util::clamp;

use super::context::{FilterContext, FilterOutput, FilterResult};
use super::{Filter, FilterError, PrimitiveWithInput};

/// The `feComponentTransfer` filter primitive.
pub struct ComponentTransfer {
    base: PrimitiveWithInput,
}

/// Pixel components that can be influenced by `feComponentTransfer`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Channel {
    R,
    G,
    B,
    A,
}

/// Component transfer function types.
#[derive(Debug, Clone, Copy)]
enum FunctionType {
    Identity,
    Table,
    Discrete,
    Linear,
    Gamma,
}

/// The `<feFuncX>` element (X is R, G, B or A).
pub struct FuncX {
    channel: Channel,
    function_type: FunctionType,
    table_values: Vec<f64>,
    slope: f64,
    intercept: f64,
    amplitude: f64,
    exponent: f64,
    offset: f64,
}

/// The compute function parameters.
struct FunctionParameters<'a> {
    table_values: &'a Vec<f64>,
    slope: f64,
    intercept: f64,
    amplitude: f64,
    exponent: f64,
    offset: f64,
}

/// The compute function type.
type Function = fn(&FunctionParameters<'_>, f64) -> f64;

/// The identity component transfer function.
fn identity(_: &FunctionParameters<'_>, value: f64) -> f64 {
    value
}

/// The table component transfer function.
fn table(params: &FunctionParameters<'_>, value: f64) -> f64 {
    let n = params.table_values.len() - 1;
    let k = (value * (n as f64)).floor() as usize;

    let k = min(k, n); // Just in case.

    if k == n {
        return params.table_values[k];
    }

    let vk = params.table_values[k];
    let vk1 = params.table_values[k + 1];
    let k = k as f64;
    let n = n as f64;

    vk + (value - k / n) * n * (vk1 - vk)
}

/// The discrete component transfer function.
fn discrete(params: &FunctionParameters<'_>, value: f64) -> f64 {
    let n = params.table_values.len();
    let k = (value * (n as f64)).floor() as usize;

    params.table_values[min(k, n - 1)]
}

/// The linear component transfer function.
fn linear(params: &FunctionParameters<'_>, value: f64) -> f64 {
    params.slope * value + params.intercept
}

/// The gamma component transfer function.
fn gamma(params: &FunctionParameters<'_>, value: f64) -> f64 {
    params.amplitude * value.powf(params.exponent) + params.offset
}

impl Default for ComponentTransfer {
    /// Constructs a new `ComponentTransfer` with empty properties.
    #[inline]
    fn default() -> ComponentTransfer {
        ComponentTransfer {
            base: PrimitiveWithInput::new::<Self>(),
        }
    }
}

impl Default for FuncX {
    #[inline]
    fn default() -> Self {
        Self {
            channel: Channel::R,
            function_type: FunctionType::Identity,
            table_values: Vec::new(),
            slope: 1.0,
            intercept: 0.0,
            amplitude: 1.0,
            exponent: 1.0,
            offset: 0.0,
        }
    }
}

impl FuncX {
    /// Constructs a new `FuncR` with empty properties.
    #[inline]
    pub fn new_r() -> Self {
        Self {
            channel: Channel::R,
            ..Default::default()
        }
    }

    /// Constructs a new `FuncG` with empty properties.
    #[inline]
    pub fn new_g() -> Self {
        Self {
            channel: Channel::G,
            ..Default::default()
        }
    }

    /// Constructs a new `FuncB` with empty properties.
    #[inline]
    pub fn new_b() -> Self {
        Self {
            channel: Channel::B,
            ..Default::default()
        }
    }

    /// Constructs a new `FuncA` with empty properties.
    #[inline]
    pub fn new_a() -> Self {
        Self {
            channel: Channel::A,
            ..Default::default()
        }
    }

    /// Returns the component transfer function parameters.
    #[inline]
    fn function_parameters(&self) -> FunctionParameters<'_> {
        FunctionParameters {
            table_values: &self.table_values,
            slope: self.slope,
            intercept: self.intercept,
            amplitude: self.amplitude,
            exponent: self.exponent,
            offset: self.offset,
        }
    }

    /// Returns the component transfer function.
    #[inline]
    fn function(&self) -> Function {
        match self.function_type {
            FunctionType::Identity => identity,
            FunctionType::Table => table,
            FunctionType::Discrete => discrete,
            FunctionType::Linear => linear,
            FunctionType::Gamma => gamma,
        }
    }
}

impl NodeTrait for ComponentTransfer {
    impl_node_as_filter!();

    #[inline]
    fn set_atts(&mut self, parent: Option<&RsvgNode>, pbag: &PropertyBag<'_>) -> NodeResult {
        self.base.set_atts(parent, pbag)
    }
}

impl NodeTrait for FuncX {
    #[inline]
    fn set_atts(&mut self, _parent: Option<&RsvgNode>, pbag: &PropertyBag<'_>) -> NodeResult {
        for (attr, value) in pbag.iter() {
            match attr {
                local_name!("type") => self.function_type = FunctionType::parse(attr, value)?,
                local_name!("tableValues") => {
                    let NumberList(v) = NumberList::parse_str(value, NumberListLength::Unbounded)
                        .map_err(|err| {
                        if let NumberListError::Parse(err) = err {
                            NodeError::parse_error(attr, err)
                        } else {
                            panic!("unexpected number list error");
                        }
                    })?;
                    self.table_values = v;
                }
                local_name!("slope") => self.slope = parsers::number(value).attribute(attr)?,
                local_name!("intercept") => {
                    self.intercept = parsers::number(value).attribute(attr)?
                }
                local_name!("amplitude") => {
                    self.amplitude = parsers::number(value).attribute(attr)?
                }
                local_name!("exponent") => {
                    self.exponent = parsers::number(value).attribute(attr)?
                }
                local_name!("offset") => self.offset = parsers::number(value).attribute(attr)?,
                _ => (),
            }
        }

        // The table function type with empty table_values is considered
        // an identity function.
        match self.function_type {
            FunctionType::Table | FunctionType::Discrete => {
                if self.table_values.is_empty() {
                    self.function_type = FunctionType::Identity;
                }
            }
            _ => (),
        }

        Ok(())
    }
}

macro_rules! func_or_default {
    ($func_node:ident, $func_data:ident, $func_default:ident) => {
        match $func_node {
            Some(ref f) => {
                $func_data = f.borrow();
                $func_data.get_impl::<FuncX>()
            }
            _ => &$func_default,
        };
    };
}

impl Filter for ComponentTransfer {
    fn render(
        &self,
        node: &RsvgNode,
        ctx: &FilterContext,
        draw_ctx: &mut DrawingCtx,
    ) -> Result<FilterResult, FilterError> {
        let input = self.base.get_input(ctx, draw_ctx)?;
        let bounds = self
            .base
            .get_bounds(ctx)
            .add_input(&input)
            .into_irect(draw_ctx);

        // Create the output surface.
        let mut output_surface = ImageSurface::create(
            cairo::Format::ARgb32,
            ctx.source_graphic().width(),
            ctx.source_graphic().height(),
        )?;

        // Get a node for every pixel component.
        let get_node = |channel| {
            node.children()
                .rev()
                .filter(|c| match c.borrow().get_type() {
                    NodeType::ComponentTransferFunctionA
                    | NodeType::ComponentTransferFunctionB
                    | NodeType::ComponentTransferFunctionG
                    | NodeType::ComponentTransferFunctionR => true,
                    _ => false,
                })
                .find(|c| c.borrow().get_impl::<FuncX>().channel == channel)
        };

        let func_r_node = get_node(Channel::R);
        let func_g_node = get_node(Channel::G);
        let func_b_node = get_node(Channel::B);
        let func_a_node = get_node(Channel::A);

        for node in [&func_r_node, &func_g_node, &func_b_node, &func_a_node]
            .iter()
            .filter_map(|x| x.as_ref())
        {
            if node.borrow().is_in_error() {
                return Err(FilterError::ChildNodeInError);
            }
        }

        // This is the default node that performs an identity transformation.
        let func_default = FuncX::default();

        // We need to tell the borrow checker that these live long enough
        let func_r_data;
        let func_g_data;
        let func_b_data;
        let func_a_data;

        let func_r = func_or_default!(func_r_node, func_r_data, func_default);
        let func_g = func_or_default!(func_g_node, func_g_data, func_default);
        let func_b = func_or_default!(func_b_node, func_b_data, func_default);
        let func_a = func_or_default!(func_a_node, func_a_data, func_default);

        #[inline]
        fn compute_func<'a>(func: &'a FuncX) -> impl Fn(u8, f64, f64) -> u8 + 'a {
            let compute = func.function();
            let params = func.function_parameters();

            move |value, alpha, new_alpha| {
                let value = f64::from(value) / 255f64;

                let unpremultiplied = if alpha == 0f64 { 0f64 } else { value / alpha };

                let new_value = compute(&params, unpremultiplied);
                let new_value = clamp(new_value, 0f64, 1f64);

                ((new_value * new_alpha * 255f64) + 0.5) as u8
            }
        }

        let compute_r = compute_func(&func_r);
        let compute_g = compute_func(&func_g);
        let compute_b = compute_func(&func_b);

        // Alpha gets special handling since everything else depends on it.
        let compute_a = func_a.function();
        let params_a = func_a.function_parameters();
        let compute_a = |alpha| compute_a(&params_a, alpha);

        // Do the actual processing.
        let output_stride = output_surface.get_stride() as usize;
        {
            let mut output_data = output_surface.get_data().unwrap();

            for (x, y, pixel) in Pixels::new(input.surface(), bounds) {
                let alpha = f64::from(pixel.a) / 255f64;
                let new_alpha = compute_a(alpha);

                let output_pixel = Pixel {
                    r: compute_r(pixel.r, alpha, new_alpha),
                    g: compute_g(pixel.g, alpha, new_alpha),
                    b: compute_b(pixel.b, alpha, new_alpha),
                    a: ((new_alpha * 255f64) + 0.5) as u8,
                };

                output_data.set_pixel(output_stride, output_pixel, x, y);
            }
        }

        Ok(FilterResult {
            name: self.base.result.borrow().clone(),
            output: FilterOutput {
                surface: SharedImageSurface::new(output_surface, input.surface().surface_type())?,
                bounds,
            },
        })
    }

    fn is_affected_by_color_interpolation_filters(&self) -> bool {
        true
    }
}

impl FunctionType {
    fn parse(attr: LocalName, s: &str) -> Result<Self, NodeError> {
        match s {
            "identity" => Ok(FunctionType::Identity),
            "table" => Ok(FunctionType::Table),
            "discrete" => Ok(FunctionType::Discrete),
            "linear" => Ok(FunctionType::Linear),
            "gamma" => Ok(FunctionType::Gamma),
            _ => Err(NodeError::parse_error(
                attr,
                ParseError::new("invalid value"),
            )),
        }
    }
}
<|endoftext|>