Lokathor / fermium

An easy to build and use set of SDL2 bindings.
https://docs.rs/fermium
60 stars 14 forks source link

No `SDL_GetError();` (I think?) #79

Closed Hugo4IT closed 3 years ago

Hugo4IT commented 3 years ago

I could only find SDL_GetErrorMsg(); but I can't get that to work... :(

Could someone (Pick one):

Love this crate so far ❤️

Lokathor commented 3 years ago

SDL_GetError is older and not thread safe.

SDL_GetErrorMsg is thread safe, so it should be used.

fn get_error_string() -> String {
  // allocate our temp buffer
  let mut v = Vec::with_capacity(4096);

  // get the message into the buffer and then set the correct buffer size
  unsafe {
    SDL_GetErrorMsg(v.as_mut_ptr(), v.capacity() as _);
    let mut i = 0;
    let mut p = v.as_mut_ptr();
    while *p != 0 {
      i += 1;
      p = p.add(1);
    }
    v.set_len(i);
  }

  // convert our bytes buffer into a string.
  // this should always be Ok, but in case of SDL2 bugs we can do a fallback.
  match String::from_utf8(v) {
    Ok(string) => string,
    Err(e) => String::from_utf8_lossy(e.as_bytes())
  }
}