use crate::{Blob, File};
use std::{ops::Deref, rc::Rc};
use wasm_bindgen::UnwrapThrowExt;
use web_sys::Url;
struct ObjectUrlAllocation {
url: String,
}
impl Drop for ObjectUrlAllocation {
fn drop(&mut self) {
web_sys::Url::revoke_object_url(&self.url).unwrap_throw();
}
}
#[derive(Clone)]
pub struct ObjectUrl {
inner: Rc<ObjectUrlAllocation>,
}
impl From<File> for ObjectUrl {
fn from(file: File) -> Self {
Blob::from(file).into()
}
}
impl From<Blob> for ObjectUrl {
fn from(blob: Blob) -> Self {
web_sys::Blob::from(blob).into()
}
}
impl From<web_sys::Blob> for ObjectUrl {
fn from(blob: web_sys::Blob) -> Self {
let url = Url::create_object_url_with_blob(&blob).unwrap_throw();
let inner = Rc::new(ObjectUrlAllocation { url });
Self { inner }
}
}
impl Deref for ObjectUrl {
type Target = str;
fn deref(&self) -> &Self::Target {
&self.inner.url
}
}