These are chat archives for rust-lang/rust

5th
Apr 2019
Geordon Worley
@vadixidav
Apr 05 00:40
@ozgurakkurt thats a really general question, but some computers have been shown to perform worse when using AVX512 (https://blog.cloudflare.com/on-the-dangers-of-intels-frequency-scaling/ and https://lemire.me/blog/2018/04/19/by-how-much-does-avx-512-slow-down-your-cpu-a-first-experiment/)
it seems counter-intuitive, but sometimes this is the case
it may be preferable to target just AVX-2 and not AVX-512
this will depend on your workload
also, it might be that the benchmark isnt representative of real-world scenarios
so it might be that it IS faster in certian situations, but just not the benchmark you have
Geordon Worley
@vadixidav
Apr 05 00:48
also, if you want to inspect the output assembly: https://godbolt.org/
just use that
Ghost
@ghost~5ca7017bd73408ce4fbcde34
Apr 05 07:24
hai
Martin Schöpf
@csaf4370
Apr 05 10:44

Hi everybody! Using actix-web 0.7: Only partly related, struggeling with my rust knowledge. Here ist my code

pub fn signin(signin_user: Json<SigninUser>, state: State<AppState>) -> FutureResponse<HttpResponse> {
    state.db.send(SigninUser{ 
            username: signin_user.username.clone(),
            password: signin_user.password.clone(),
        })         
        .from_err()
        .and_then(|res| {
            match res {
                Ok(signin_msg) => {
                    println!("status {}, signin_user {}, verified {}", signin_msg.status, signin_msg.signin_user.username, signin_msg.signin_user.verified);
                    if signin_msg.status == 200 && signin_msg.signin_user.verified == false {
                        println!("returning 401 with activate reason");
                        return Ok(HttpResponse::Unauthorized().reason("Aktivieren Sie ihren Account mit der Email in ihrer Mailbox").finish().into());
                    }
                    if signin_msg.status >= 400 {
                        return Ok(HttpResponse::Unauthorized().reason(&signin_msg.message).finish().into());
                    }
                    Ok(HttpResponse::Ok().json(signin_msg))
                },
                Err(_) => Ok(HttpResponse::InternalServerError().into())
            }
        }).responder()
}

the error occurs in the case of msg.status >= 400.

return Ok(HttpResponse::Unauthorized().reason(&signin_msg.message).finish().into());
   |                                                                        ^^^^^^^^^^^^^^^^^^ borrowed value does not live long enough
...
54 |             }
   |             - borrowed value only lives until here

i want to put the message of the signin_msg into the reason. The signature of reason is:
pub fn reason(&mut self, reason: &'static str) -> &mut Self {
is there a way to get where i want?

Thanks in advance

(I posted the question in the actix-web channel, but didn't get a response)

Denis Lisov
@tanriol
Apr 05 11:37
Not really. There are possible workarounds, but they're hacky... and won't work if the message includes username or something like that.
Martin Schöpf
@csaf4370
Apr 05 11:40
@tanriol thanks for your reply. So the only clean solution I can think of would be to create an Error-Enum with static str representations, which are handed over, if the signin_msg matches a specific status? Or is there a better solution?
Denis Lisov
@tanriol
Apr 05 11:44
That's probably what I'd do.
Martin Schöpf
@csaf4370
Apr 05 11:45
@tanriol thanks, than I'll do that.
Akos Vandra
@axos88
Apr 05 15:08

Hi! Is there a way to create a &str using format!() at compile time?.....

I'd like to replace this

  const USER_AGENT: &str = "project/1.0 my@email.com";

with something like this

  const USER_AGENT: &str = compile_time_format!("{}/{} {}", env!("CARGO_PKG_NAME"), env!("CARGO_PKG_VERSION"), env!("CARGO_PKG_AUTHORS"));
I know about concat!(), but it feels like we're back in 2000 :-/
Ingvar Stepanyan
@RReverser
Apr 05 17:05
No, lazy_static is probably the closest you can get to it.
Since format! needs to actually execute code (fmt::Display / fmt::Debug implementations on various types)
So it can't be compile-time
Personally, I find concat! good enough
raja sekar
@rajasekarv
Apr 05 18:57
extern crate downcast_rs;
use downcast_rs::Downcast;
use std::fmt::Debug;

trait Base: Downcast {}
impl_downcast!(Base);

struct Foo<T: Debug>(T);
impl<T:Debug + 'static> Base for Foo<T> {}

fn run<T:Debug>(a: T) {
    println!("{:?}",a);
}

fn main() {
    let mut base: Box<Base> = Box::new(Foo(42));
    if let Some(foo) = base.downcast_ref::<Foo<_>>() {
        run(foo.0);
    } 
}
Is it possible to downcast a trait object to generic struct like this? I am in a situation where I need to match the underlying concrete types with generic type parameters.
Ingvar Stepanyan
@RReverser
Apr 05 18:57
Please use
```
your code
```
(looks like you tried to but wrong quote - you need to use the backquote)
raja sekar
@rajasekarv
Apr 05 18:59
@RReverser thanks for the suggestion
Denis Lisov
@tanriol
Apr 05 20:08
@rajasekarv Do you mean downcasting to some specific Foo<SomeType> that can be determined from the if let body?
Or downcasting as in "if this is Foo<something>, give it to me, whatever the something is"?
The former is possible, the latter is not.
raja sekar
@rajasekarv
Apr 05 20:28
@tanriol I know that former is possible. I was wondering about later. In scala, I can pattern match against classes extending generic abstract class. I am exploring the equivalent in Rust. If I use enum, there are lot of cases consisting of lot of generic type parameters, it didn't seem plausible. Any suggestions?
Ichoran
@Ichoran
Apr 05 20:36
Can you write the working match statement in Scala and, maybe, the non-working equivalent in Rust to better explain what you're after? I don't quite understand.
Maybe it's just a matter of erasure. On the JVM, generic types are erased; given class Foo[A] {}, the underlying representation is class Foo (no generic type at all). But that's not how Rust generics work. They're more akin to C++ template parameters in that regard.
raja sekar
@rajasekarv
Apr 05 20:47
abstract class base[T](val a: A[T], val isSomething: Boolean) 

abstract class DerivedOne[T](a: A[T]) extends base(a, false) {
  def getSomething(output: Int): Seq[Int]
}

class DerivedTwo[K, V, C](
    val id: Int,
    a: A[(K, V)],
    val b: B[K, V, C])
  extends Dependency(a, true)

class DerivedThree[T](rdd: RDD[T]) extends DerivedOne[T](rdd) {
  override def getSomething(output: Int) = List(output)
}

for (b <- r.base) {
  b match {
    case drt: DerivedTwo[_,_,_] => { ... }
    case dro: DerivedOne[_]=> { ... }
    case _: { ... }
  }
}
Something like this. Any workaround?
I am having a hard time figuring out to achieve this in Rust.
David McGillicuddy
@djmcgill
Apr 05 20:56
What's the easiest way to get something that implements std::error::Error? Just for local debugging for now.
I'm missing failure's err_msg right about now

okay, got

pub fn foo() -> impl Future<Item=Bar, Error=Box<dyn std::error::Error>> {
    future::err("foo".to_string().into())
}

working
but interestingly not

pub fn foo() -> impl Future<Item=Bar, Error=Box<dyn Into<std::error::Error>>> {
    future::err("foo".to_string())
}
Denis Lisov
@tanriol
Apr 05 21:41
@rajasekarv Cannot really be done. You cannot have a value of type Foo<not_known_until_runtime>. The best option here would be to have conversion into Foo<&dyn Debug> or something like that, but that's nontrivial.
If you can describe what you're trying to do in more detail, there is probably a better option.
raja sekar
@rajasekarv
Apr 05 22:04
#[macro_use]
extern crate downcast_rs;
use downcast_rs::Downcast;
use std::fmt::Debug;

trait Base: Downcast {}
impl_downcast!(Base);

struct Foo<T>(T);
impl<T:'static> Base for Foo<T> {}

fn run<T: Debug>(a: T) {
    println!("{:?}", a);
}

fn run1<T: Debug+ 'static>(a: T) {
    let mut base: Box<Base> = Box::new(Foo(a));
    if let Some(foo) = base.downcast_ref::<Foo<T>>() {
        run(&foo.0);
    } 

}

fn main() {
    run1(2);
}
Somewhat found the satisfying solution. Thanks for your help.
Ichoran
@Ichoran
Apr 05 22:23
Sorry, got busy, but I'm glad you found something that at least sort of works for you.
Even though traits have a form of inheritance in Rust, kinda, modeling the class hierarchy in your Scala example is probably not the way to go.
raja sekar
@rajasekarv
Apr 05 22:30
I am figuring out how to do things in Rust way. Many things seem hard to do in Rust, but later I generally find something elegant in Idiomatic Rust itself. But I still have a long way to go I guess.
Denis Lisov
@tanriol
Apr 05 22:31
It's usually a good idea to describe what you're trying to do in a human language first. Much easier to find a good solution in Rust for a high-level description than for lower-level code already tuned for a different language.