Help Translating this code

I'm translating this C# code


        #region Prefix

        private const string FilePrefix = @"file://";

        private const string HttpPrefix = @"http://";

        private const string Base64Prefix = @"base64://";

        #endregion

        public static async Task<Stream> GetAssetFile(string url)
        {
            if (url.StartsWith(FilePrefix))
            {
                url = url.Replace(FilePrefix, "");
                return File.OpenRead(url);
            }

            if (url.StartsWith(HttpPrefix))
            {
                HttpWebRequest request = RequestHelper.CreateWebRequest(url);
                return (await request.GetResponseAsync()).GetResponseStream();
            }

            if (url.StartsWith(Base64Prefix))
            {
                url = url.Replace(Base64Prefix, "");
                byte[] bytes = Convert.FromBase64String(url);
                return new MemoryStream(bytes, false);
            }

            throw new InvalidOperationException($"Invalid Url:{url}");
        }
    }

I want to translate this into Rust.But I don't know how to set the return value of the function.

I would probably do something like this:

use futures::stream::{BoxStream, TryStreamExt};
use bytes::Bytes;
use anyhow::Result;

async fn get_asset_file(url: &str) -> Result<BoxStream<'static, Result<Bytes>>> {
    if url.starts_with("file://") {
        let path = &url[7..];
        let file = tokio::fs::File::open(path).await?;
        let stream = tokio_util::io::ReaderStream::new(file);

        return Ok(Box::pin(stream.map_err(|e| e.into())));
    }

    if url.starts_with("http://") {
        let stream = reqwest::get("https://www.rust-lang.org").await?.bytes_stream();
        return Ok(Box::pin(stream.map_err(|e| e.into())));
    }

    if url.starts_with("base64://") {
        let data = &url[9..];
        let decoded = base64::decode(data)?;
        let stream = futures::stream::once(async move { Ok(Bytes::from(decoded)) });
        return Ok(Box::pin(stream));
    }

    anyhow::bail!("Invalid url: {}", url)
}
[dependencies]
tokio = { version = "1", features = ["full"] }
tokio-util = { version = "0.6.9", features = ["full"] }
futures = "0.3"
bytes = "1"
anyhow = "1"
reqwest = { version = "0.11", features = ["stream"]}
base64 = "0.13"
1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.