How to check for double click in Bevy rust - input

New to bevy and need to implement a double click system into my game and this is what I tried. I got a couple errors specifically relating to the local variable containing Instant. I have properly imported the instant crate but am not sure what else is needed in bevy to make a local var work.
pub fn double_click(
mouse_button_input: Res<Input<MouseButton>>,
mut double_click_time: Local<Instant>,
) {
if mouse_button_input.just_pressed(MouseButton::Left) {
double_click_time = Instant::now();
}
println!("Time: {}", double_click_time.elapsed().as_secs());
}
One error I am getting is at the Instant::now(); and it is
expected struct `bevy::prelude::Local<'_, Instant, >`
found struct `Instant
Also where the system is added it gives error
the trait bound `for<'r, 's> fn(bevy::prelude::Res<'r, bevy::prelude::Input<bevy::prelude::MouseButton>>, bevy::prelude::Local<'s, Instant>) {inventory::double_click}: IntoSystem<(), (), _>` is not satisfied
If there is another way to detect a double click, that works too!

Based on your error and the docs for Local (which say that it implements Deref and DerefMut), you just need to assign to the contents of the Local, and that should fix your compile error:
*double_click_time = Instant::now();
I don't know Bevy, so I don't know if this is actually the best way to handle double clicks.

Thanks, that worked but I figured out another way, I just implememnted the double click timeout into a global struct used for a couple other related things.

Related

Does Rust have hooks for early return on errors?

panic! allows the setting of a custom (albeit global) hook. Is there anything comparable for early returns with the ? operator? I have a function that needs to close some resources in a special way before exiting. I could write a function ok_or_close() that closes the resources before returning the error:
fn opens_resources() -> Result<(), MyError> {
//Opens some stuff.
//Now a bunch of functions that might raise errors.
ok_or_close(foo(), local variables)?;
ok_or_close(bar(), local variables)?;
ok_or_close(baz(), local variables)?;
ok_or_close(Ok(()), local variables)
}
But that seems verbose. What I'd really like to do is this:
fn opens_resources() -> Result<(), MyError> {
//Opens some stuff.
//Now a bunch of functions that might raise errors.
foo()?;
bar()?;
baz()?;
on_err:
//Closes some stuff. Would prefer not to make
// this a function, uses many local variables.
Ok(())
}
Is there a way to do this or a pattern of programming that gets around this?
The closest thing to this would be the Try trait which allows you to implement how ? affect a specific type, but sadly it is still a nightly experiment as stated here
If you're interested in this features I'd recommend you give a +1 at this issue

Kotlin collections map causing a 'Type Checking Has Run Into A Recursive In Kotlin' error

I have 2 classes lets call them A and B, I also have a function that converts an instance of A to an instance of B.
My code that is causing issues is basically:
fun fromAtoB(a: A) = B (fb1 = a.fa1, fb2 = a.fa2, fb3 = a.fa3)
val listOfA: List<A> = ...
val listOfB: listOfA.map { fromAtoB(it) }
This won't build due to the line:
fromAtoB(it)
With the error:
Due to the error Type checking has run into a recursive problem. Easiest workaround: specify types of your declarations explicitly
I Have no clue what I can do to fix this, Google had provided no results that seem to apply to my issue...
Thanks in advance for any help!
EDIT:
Here are the actual source files:
TenantEntity.kt - https://pastebin.com/mdSWiA1Y (Line 51 of this file
is the issue)
TenantDto.kt - https://pastebin.com/83UP9Cwe
ReceiptEntity.kt - https://pastebin.com/BjP2ikg9
ReceiptDto.kt - https://pastebin.com/Kpt9dSAp
This type of problem means that the compiler can't infer what the type of listOfB should be, because you have a recursive call somewhere in its definition. That's curious as I can't see any in your example code, but maybe you left out the offending code inadvertently. Anyways, this problem is usually resolved by doing what the error message suggests, manually specifying the return type like so:
val listOfB: List<B> = listOfA.map { fromAtoB(it) }
Edit:
After trying the real code, I just went after a hunch and changed line 45 in TenantEntity.kt from this:
fun fromDto(dto: TenantDto) = TenantEntity (
to this:
fun fromDto(dto: TenantDto): TenantEntity = TenantEntity (
and the error was gone. I'm not really sure why, but it should compile now.
Second edit:
Upon further inspection, you're going to run into a StackOverflowException with this code, which is ultimately why the compiler couldn't resolve the type. When you call TenantEntity.fromDto(...), that will call ReceiptEntity.fromDto(...), which will in turn call TenantEntity.fromDto(...), and back again, into eternity (or the stack limit). That's not going to work, you'll need to fix your logic there.

Am I forced to create my own Error type?

I want to write a get_members function that returns members from a GitHub team.
pub fn get_members(group_id: &str) -> Result<Vec<User>, Error> {
let client = Client::new();
let query = format!("https://api.github.com/teams/{}/members?access_token={}",
group_id,
config::get_env(config::ENV_TOKEN));
println!("{}", query);
let mut res = try!(client
.get(&query)
.header(UserAgent("my/app".to_owned()))
.send());
let mut body = String::new();
try!(res.read_to_string(&mut body));
try!(json::decode(&body));
}
There are two different types of errors into play. One is hyper::error::Error and the other is rustc_serialize::json::DecoderError.
I thought I could just use implement From<::hyper::error::Error> for Error and From<rustc_serialize::json::DecoderError>. But since neither io::Error nor one of the other two errors is in my crate I'm not allowed to follow that approach.
I wonder what's the way to go here. Do I need to come up with my own AppError Type and then implement the From<> trait for that? Is that the way to go?
Usually yes, using your own error type is the way to go. There are even several crates (of which I was able to find only this one now) which help you to remove the boilerplate. This approach should also be used when you're writing a library, as opposed to an application.
There is an option, however, of using Box<Error> trait object as your error type. Lots of error types in Rust and in third-party libraries implement this trait; therefore, using Result<..., Box<Error>> as a return type should work almost always.

Reuse the description of an existing Error when creating a new Error

I have the following code in Rust, which does not compile, but shows the intent of what I'd like to do.
pub fn parse(cursor: &mut io::Cursor<&[u8]>) -> io::Result<Ack> {
use self::byteorder::{BigEndian, ReadBytesExt};
use self::core::error::Error;
match cursor.read_u16::<BigEndian>() {
Err(byteorder::Error::Io(error)) => Err(error),
Err(error) =>
Err(io::Error::new(io::ErrorKind::Other, error.description(),
None)),
Ok(value) => Ok(Ack { block_number: value })
}
}
Essentially, I want to take the error description of an error returned by the byteorder library and use it to create the description of an error I'll pass back to the user of my library. This fails with packets.rs:166:58: 166:63 error:errordoes not live long enough, and I understand why.
The byteorder library solves this issue by wrapping an std::io::Result in the byteorder::Error::Io constructor. However, I don't want to take this route because I'd have to define my own error type that wraps either an std::io::Error or a byteorder::Error. It seems to me that my users shouldn't know or care that I use the byteorder library, and it shouldn't be part of my interface.
I'm a Rust newbie and don't yet know the idioms and best practices of the language and design. What are my options for dealing with this?
Your problem is in fact in that io::Error::new()'s second parameter is &'static str, while byteorder::Error::description() returns a &'a str where 'a is lifetime of the error object itself which is less than 'static. Hence you can't use it for io::Error's description.
The simplest fix would be moving byteorder::Error description to detail field of io::Error:
Err(error) =>
Err(io::Error::new(
io::ErrorKind::Other,
"byteorder error",
Some(error.description().to_string())
)),
However, you should seriously consider making a custom wrapper error type which encapsulates all "downstream" errors. With properly written FromError instances you should be able to write something like
try!(cursor.read_u16::<BigEndian>()
.map(|value| Ack { block_number: value }))
instead of your whole match. Custom error wrappers will also help you when your program grows and more "downstream" error sources appear - you could just add new enum variants and/or FromError implementations to support these new errors.
I cannot test your code so I can't be sure. Isn't the ref keyword enough?
Err(byteorder::Error::Io(ref error)) => Err(error),

MicrosoftAjaxMinifier doesn't seem to remove "unreachable code"

I'm using this with BundleTransformer from nuget and System.Web.Optimisation in an ASP.Net app. According to various docs this minifier is supposed to "remove unreachable code". I know it's not as aggressive as google closure (which I can't use presently) but I can't get even the simplest cases to work, eg;
function foo() {
}
where foo isn't called from anywhere. I can appreciate the argument that says this might be an exported function but I can't see a way to differentiate that. All my JS code is concatenated so it would be able to say for sure whether that function was needed or not if I can find the right switches.
The only way I've found to omit unnecessary code is to use the debugLookupList property in the web.config for BundleTransformer but that seems like a sledgehammer to crack a nut. It's not very granular.
Does anyone have an example of how to write so-called 'unreachable code' that this minifier will recognise?
Here's a place to test online
I doubt the minifier has any way of knowing if a globally defined function can be removed safely (as it doesn't know the full scope). On the other hand it might not remove any unused functions and might only be interested in unreachable code (i.e. code after a return).
Using the JavaScript Module Pattern, your unused private functions would most likely get hoovered up correctly (although I've not tested this). In the example below, the minifier should only be confident about removing the function called privateFunction. Whether it considers unused functions as unreachable code is another matter.
var AmazingModule = (function() {
var module = {};
function privateFunction() {
// ..
}
module.otherFunction = function() {
// ..
};
return module;
}());
function anotherFunction() {
// ..
}