Discussion
Loading...

Post

Log in
  • About
  • Code of conduct
  • Privacy
  • Users
  • Instances
  • About Bonfire
Jan :rust: :ferris:
Jan :rust: :ferris:
@janriemer@floss.social  路  activity timestamp 3 weeks ago

This is why #Rust is not only about memory safety/performance, but about correctness 馃憞

Did you know that in #JavaScript when `fetch`ing the same Request/Response twice will error (when containing a body)!?

It is because bodies are Streams, which can only be read once! You can clone the Request/Response/Body, but this comes with its own caveats (in the worst case the clone will buffer the body fully in memory!).

#RustLang solves this by borrow checking and good API design...

1/3

#WebDev #JS

  • Copy link
  • Flag this post
  • Block
Jan :rust: :ferris:
Jan :rust: :ferris:
@janriemer@floss.social replied  路  activity timestamp 3 weeks ago

For example `reqwest` is a popular crate ("crate" means "library" in Rust) for doing requests.

When actually sending the request (via `send` method), `self` is consumed, which means the request object cannot be used afterwards:
https://docs.rs/reqwest/latest/reqwest/struct.RequestBuilder.html#method.send

Now you might think: Can't we just `clone` it like in JavaScript!?

Well..._maybe_ 馃槈
https://docs.rs/reqwest/latest/reqwest/struct.RequestBuilder.html#method.try_clone

It can only be cloned, if it is _not_ a Stream (unlike JS, bodies don't need to be Streams)!

2/3

RequestBuilder in reqwest - Rust

A builder to construct the properties of a `Request`.

RequestBuilder in reqwest - Rust

A builder to construct the properties of a `Request`.
  • Copy link
  • Flag this comment
  • Block
Jan :rust: :ferris:
Jan :rust: :ferris:
@janriemer@floss.social replied  路  activity timestamp 3 weeks ago

This saves us from potentially reading the underlying stream twice, with the second either already being drained by the first stream or a potentially costly buffering in memory (like in JS)!

Thank you Rust! 鉂わ笍 ferris

Some more links to the relevant JS articles (haven't fit in first toot):

Locked and disturbed streams:

https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch#locked_and_disturbed_streams

Response.clone()

https://developer.mozilla.org/en-US/docs/Web/API/Response/clone

3/3

Response: clone() method - Web APIs | MDNMDN

The clone() method of the Response interface creates a clone of a response object, identical in every way, but stored in a different variable.

Using the Fetch API - Web APIs | MDNMDN

The Fetch API provides a JavaScript interface for making HTTP requests and processing the responses.
  • Copy link
  • Flag this comment
  • Block

bonfire.cafe

A space for Bonfire maintainers and contributors to communicate

bonfire.cafe: About 路 Code of conduct 路 Privacy 路 Users 路 Instances
Bonfire social 路 1.0.1-alpha.41 no JS en
Automatic federation enabled
Log in
  • Explore
  • About
  • Members
  • Code of Conduct