Skip to main content

io_webdav/rfc4918/
get.rs

1//! Generic `GET` coroutine (RFC 9110 ยง9.3.1).
2//!
3//! Sends a `GET` against `path` and returns the response body as raw
4//! bytes. iCal/vCard parsing happens upstream in
5//! io-calendar/io-addressbook.
6//!
7//! # Example
8//!
9//! ```rust,no_run
10//! use std::{
11//!     io::{Read, Write},
12//!     net::TcpStream,
13//! };
14//!
15//! use io_webdav::{
16//!     coroutine::{WebdavCoroutine, WebdavCoroutineState, WebdavYield},
17//!     rfc4918::{WebdavAuth, get::Get},
18//! };
19//! use url::Url;
20//!
21//! // Ready stream needed (TCP-connected, TLS-negociated)
22//! let mut stream = TcpStream::connect("dav.example.org:443").unwrap();
23//! let mut buf = [0u8; 4096];
24//!
25//! let base_url: Url = "https://dav.example.org/".parse().unwrap();
26//! let auth = WebdavAuth::None;
27//! let mut coroutine = Get::new(&base_url, &auth, "io-webdav", "/dav/calendars/personal/event-1.ics");
28//! let mut arg = None;
29//!
30//! let ok = loop {
31//!     match coroutine.resume(arg.take()) {
32//!         WebdavCoroutineState::Yielded(WebdavYield::WantsWrite(bytes)) => {
33//!             stream.write_all(&bytes).unwrap();
34//!         }
35//!         WebdavCoroutineState::Yielded(WebdavYield::WantsRead) => {
36//!             let n = stream.read(&mut buf).unwrap();
37//!             arg = Some(&buf[..n]);
38//!         }
39//!         WebdavCoroutineState::Complete(Ok(ok)) => break ok,
40//!         WebdavCoroutineState::Complete(Err(err)) => panic!("{err}"),
41//!     }
42//! };
43//!
44//! println!("{} bytes", ok.body.len());
45//! ```
46
47use alloc::vec::Vec;
48
49use log::trace;
50use url::Url;
51
52use crate::{
53    coroutine::*,
54    rfc4918::{
55        WebdavAuth,
56        request::WebdavRequest,
57        send::{SendError, SendOk, SendRaw},
58    },
59};
60
61/// Coroutine that runs a `GET`.
62#[derive(Debug)]
63pub struct Get {
64    state: State,
65}
66
67impl Get {
68    /// Builds a new `GET` coroutine.
69    pub fn new(base_url: &Url, auth: &WebdavAuth, user_agent: &str, path: &str) -> Self {
70        let request = WebdavRequest::get(base_url, auth, user_agent, path).body(Vec::new());
71        Self {
72            state: State::Send(SendRaw::new(request)),
73        }
74    }
75}
76
77impl WebdavCoroutine for Get {
78    type Yield = WebdavYield;
79    type Return = Result<SendOk<Vec<u8>>, SendError>;
80
81    fn resume(&mut self, arg: Option<&[u8]>) -> WebdavCoroutineState<Self::Yield, Self::Return> {
82        trace!("sending request");
83        match &mut self.state {
84            State::Send(send) => send.resume(arg),
85        }
86    }
87}
88
89#[derive(Debug)]
90enum State {
91    Send(SendRaw),
92}