playground-api 0.5.1

Simple API-binding for The Rust Playground
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
use crate::{endpoints::*, error::Error};
use url::Url;

/// A client for interacting with the Rust playground API.
///
/// Holds the base URL and the `reqwest::Client` struct for all requests.
#[derive(Clone)]
pub struct Client {
    url: Url,
    client: reqwest::Client,
}

impl Client {
    /// Creates a new `Client` instance with the given base URL.
    ///
    /// Parses the provided string into a `Url`. Returns an error if the URL is invalid.
    ///
    /// # Arguments
    ///
    /// * `url` - A string slice representing the base URL of the Rust playground API.
    ///
    /// # Returns
    ///
    /// * `Result<Client, Error>` - On success, returns a `Client` configured with the parsed URL.
    ///   On failure, returns an `Error` if the URL string is invalid.
    pub fn new(url: &str) -> Result<Client, Error> {
        let url = Url::parse(url)?;
        let client = reqwest::Client::new();
        Ok(Client { url, client })
    }

    /// Sends a code execution request to the Rust playground and returns the result.
    ///
    /// This asynchronous method takes and [`ExecuteRequest`] struct containing the code
    /// execution parameters, sends it to the appropriate endpoint on the Rust playground
    /// via a POST request, and returns the execution result.
    ///
    /// # Arguments
    ///
    /// * `request` - A reference to an [`ExecuteRequest`] that includes the code snippet
    ///   and configuration options such as edition, crate type, and whether to run or compile.
    ///
    /// # Returns
    ///
    /// * `Result<ExecuteResponse, Error>` - On success, returns an [`ExecuteResponse`] containing
    ///   the output, errors, and status from the Rust playground. On failure, returns an [`Error`].
    ///
    /// # Errors
    ///
    /// This function will return an error if the HTTP request fails, if the response cannot be parsed,
    /// or if the playground service is unavailable.
    pub async fn execute<'a>(
        &self,
        request: &ExecuteRequest<'a>,
    ) -> Result<ExecuteResponse<'a>, Error> {
        self.post(request).await
    }

    /// Sends a code compilation request to the Rust playground and returns the result.
    ///
    /// This asynchronous method takes a [`CompileRequest`] containing the code and
    /// compilation parameters, sends it to the Rust playground's compile endpoint,
    /// and returns the compilation result.
    ///
    /// # Arguments
    ///
    /// * `request` - A reference to a [`CompileRequest`] that includes the code and metadata
    ///   such as the toolchain edition, crate type, target, and any compiler settings.
    ///
    /// # Returns
    ///
    /// * `Result<CompileResponse, Error>` - On success, returns a [`CompileResponse`] containing
    ///   the compiler output, including success/failure status, messages, and possible warnings or errors.
    ///   On failure, returns an [`Error`] describing the issue.
    ///
    /// # Errors
    ///
    /// Returns an error if the HTTP request fails, if the response cannot be parsed correctly,
    /// or if the playground service encounters an issue.
    pub async fn compile<'a>(
        &self,
        request: &CompileRequest<'a>,
    ) -> Result<CompileResponse<'a>, Error> {
        self.post(request).await
    }

    /// Sends a code formatting request to the Rust playground and returns the formatted result.
    ///
    /// This asynchronous method takes a [`FormatRequest`] containing the Rust code and formatting options,
    /// sends it to the Rust playground's format endpoint, and returns the formatted code or any errors.
    ///
    /// # Arguments
    ///
    /// * `request` - A reference to a [`FormatRequest`] that includes the code to be formatted and
    ///   optional parameters like the edition to use.
    ///
    /// # Returns
    ///
    /// * `Result<FormatResponse, Error>` - On success, returns a [`FormatResponse`] containing the
    ///   formatted code or an error message if the code could not be formatted.
    ///   On failure, returns an [`Error`] representing issues like network failure or parsing problems.
    ///
    /// # Errors
    ///
    /// This function may return an error if the request fails, the response is invalid,
    /// or the Rust playground's formatting service encounters a problem.
    pub async fn format<'a>(
        &self,
        request: &FormatRequest<'a>,
    ) -> Result<FormatResponse<'a>, Error> {
        self.post(request).await
    }

    /// Sends a Clippy linting request to the Rust playground and returns the analysis result.
    ///
    /// This asynchronous method takes a [`ClippyRequest`] containing the Rust code and configuration,
    /// sends it to the Rust playground's Clippy endpoint, and returns any linter warnings, errors,
    /// or suggestions provided by Clippy.
    ///
    /// # Arguments
    ///
    /// * `request` - A reference to a [`ClippyRequest`] that includes the code to be analyzed
    ///   and optional parameters such as edition or crate type.
    ///
    /// # Returns
    ///
    /// * `Result<ClippyResponse, Error>` - On success, returns a [`ClippyResponse`] containing
    ///   Clippy's diagnostic output (warnings, errors, suggestions). On failure, returns an [`Error`]
    ///   describing what went wrong (e.g., network error, bad request, or service issue).
    ///
    /// # Errors
    ///
    /// Returns an error if the request cannot be completed, the response is invalid,
    /// or the Clippy service is unavailable or encounters an internal error.
    pub async fn clippy<'a>(
        &self,
        request: &ClippyRequest<'a>,
    ) -> Result<ClippyResponse<'a>, Error> {
        self.post(request).await
    }

    /// Sends a Miri request to the Rust playground and returns the result of interpreting the code.
    ///
    /// This asynchronous method takes a [`MiriRequest`] containing the Rust code and any
    /// interpreter-specific options, sends it to the Rust playground's Miri endpoint, and
    /// returns the result of running the interpreter on the code.
    ///
    /// # Arguments
    ///
    /// * `request` - A reference to a [`MiriRequest`] that includes the code and metadata
    ///   such as edition, crate type, and other configuration options.
    ///
    /// # Returns
    ///
    /// * `Result<MiriResponse, Error>` - On success, returns a [`MiriResponse`] containing the
    ///   result of the interpretation. On failure, returns an [`Error`] describing the issue.
    ///
    /// # Errors
    ///
    /// Returns an error if the request fails, if the response is invalid, or if the Miri service
    /// encounters an internal issue.
    pub async fn miri<'a>(&self, request: &MiriRequest<'a>) -> Result<MiriResponse<'a>, Error> {
        self.post(request).await
    }

    /// Sends a macro expansion request to the Rust playground and returns the result.
    ///
    /// This asynchronous method takes a [`MacroExpansionRequest`] with Rust code containing macros,
    /// sends it to the Rust playground's macro expansion endpoint, and returns the result
    /// of the expanded macros.
    ///
    /// # Arguments
    ///
    /// * `request` - A reference to a [`MacroExpansionRequest`] that includes the code and any
    ///   configuration options like the edition to use.
    ///
    /// # Returns
    ///
    /// * `Result<MacroExpansionResponse, Error>` - On success, returns a [`MacroExpansionResponse`]
    ///   containing the macro-expanded version of the code. On failure, returns an [`Error`] describing
    ///   the issue.
    ///
    /// # Errors
    ///
    /// Returns an error if the HTTP request fails, if the response is invalid, or if the macro expansion
    /// service encounters an issue.
    pub async fn macro_expansion<'a>(
        &self,
        request: &MacroExpansionRequest<'a>,
    ) -> Result<MacroExpansionResponse<'a>, Error> {
        self.post(request).await
    }

    /// Retrieves the list of available crates from the Rust playground.
    ///
    /// This asynchronous method sends a GET request to the crates endpoint
    /// and returns a list of crates supported by the playground environment.
    ///
    /// # Returns
    ///
    /// * `Result<CratesResponse, Error>` - On success, returns a [`CratesResponse`] containing
    ///   the names and versions of available crates. On failure, returns an [`Error`] describing
    ///   the problem.
    ///
    /// # Errors
    ///
    /// Returns an error if the request fails, if the response cannot be parsed,
    /// or if the crates service is unavailable.
    pub async fn crates<'a>(&self) -> Result<CratesResponse<'a>, Error> {
        self.get(Endpoints::Crates).await
    }

    /// Retrieves the supported versions and metadata of the Rust playground.
    ///
    /// This asynchronous method sends a GET request to the versions endpoint and
    /// returns information about supported Rust versions, targets, and environments.
    ///
    /// # Returns
    ///
    /// * `Result<VersionsResponse, Error>` - On success, returns a [`VersionsResponse`]
    ///   containing version details. On failure, returns an [`Error`] describing what went wrong.
    ///
    /// # Errors
    ///
    /// Returns an error if the request cannot be completed, the response is malformed,
    /// or if the versions service is unavailable.
    pub async fn versions<'a>(&self) -> Result<VersionsResponse<'a>, Error> {
        self.get(Endpoints::Versions).await
    }

    /// Creates a GitHub Gist from the provided Rust playground code.
    ///
    /// This asynchronous method sends a [`GistCreateRequest`] to the Gist creation endpoint
    /// and returns a response containing the Gist URL or error information.
    ///
    /// # Arguments
    ///
    /// * `request` - A reference to a [`GistCreateRequest`] that includes the code to be uploaded
    ///   as a Gist and any additional metadata like description or visibility.
    ///
    /// # Returns
    ///
    /// * `Result<GistResponse, Error>` - On success, returns a [`GistResponse`] containing
    ///   the Gist ID and URL. On failure, returns an [`Error`] describing what went wrong.
    ///
    /// # Errors
    ///
    /// Returns an error if the HTTP request fails, if the response is malformed,
    /// or if the Gist service is unavailable.
    pub async fn gist_create<'a>(
        &self,
        request: &GistCreateRequest<'a>,
    ) -> Result<GistResponse<'a>, Error> {
        self.post(request).await
    }

    /// Retrieves an existing GitHub Gist from the Rust playground.
    ///
    /// This asynchronous method sends a GET request to the Gist retrieval endpoint
    /// using the provided Gist ID and returns the contents of the Gist.
    ///
    /// # Arguments
    ///
    /// * `id` - A `String` representing the unique identifier of the Gist to retrieve.
    ///
    /// # Returns
    ///
    /// * `Result<GistResponse, Error>` - On success, returns a [`GistResponse`] containing
    ///   the Gist's code and metadata. On failure, returns an [`Error`] describing the issue.
    ///
    /// # Errors
    ///
    /// Returns an error if the HTTP request fails, if the response is invalid,
    /// or if the Gist could not be found.
    pub async fn gist_get<'a>(&self, id: &str) -> Result<GistResponse<'a>, Error> {
        self.get(Endpoints::GistGet(id)).await
    }

    /// Sends a POST request with a serialized JSON payload to the specified endpoint,
    /// and deserializes the response into the expected type.
    ///
    /// Used internally to interact with Rust playground endpoints.
    pub async fn post<T, U>(&self, request: &T) -> Result<U, Error>
    where
        T: Request,
        U: Response,
    {
        let endpoint = request.endpoint();
        let url = self.url.join(&endpoint.path())?;
        let res = self.client.post(url).json(request).send().await?;

        if !res.status().is_success() {
            return Err(Error::NoSuccess(res.status().as_u16()));
        }

        let res = res.json::<U>().await?;
        Ok(res)
    }

    /// Sends a GET request to the specified endpoint, and deserializes the response
    /// into the expected type.
    ///
    /// Used internally to interact with Rust playground endpoints.
    pub async fn get<'a, U>(&self, endpoint: Endpoints<'a>) -> Result<U, Error>
    where
        U: Response,
    {
        let url = self.url.join(&endpoint.path())?;
        let res = self.client.get(url).send().await?;

        if !res.status().is_success() {
            return Err(Error::NoSuccess(res.status().as_u16()));
        }

        let res = res.json::<U>().await?;
        Ok(res)
    }
}

impl Default for Client {
    /// Creates a `Client` instance with the following url <https://play.rust-lang.org/>
    fn default() -> Self {
        let client = reqwest::Client::new();
        Self {
            url: Url::parse("https://play.rust-lang.org/").unwrap(),
            client,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::Client;
    use crate::endpoints::*;

    #[tokio::test]
    async fn execute() {
        let req = ExecuteRequest::default();

        let client = Client::default();
        let res = client.execute(&req).await;

        println!("{res:?}");
        assert!(res.is_ok())
    }

    #[tokio::test]
    async fn compile() {
        let req = CompileRequest::default();

        let client = Client::default();
        let res = client.compile(&req).await;

        println!("{res:?}");
        assert!(res.is_ok());
    }

    #[tokio::test]
    async fn format() {
        let req = FormatRequest::default();

        let client = Client::default();
        let res = client.format(&req).await;

        println!("{res:?}");
        assert!(res.is_ok());
    }

    #[tokio::test]
    async fn clippy() {
        let req = ClippyRequest::default();

        let client = Client::default();
        let res = client.clippy(&req).await;

        println!("{res:?}");
        assert!(res.is_ok());
    }

    #[tokio::test]
    async fn miri() {
        let req = MiriRequest::default();

        let client = Client::default();
        let res = client.miri(&req).await;

        println!("{res:?}");
        assert!(res.is_ok());
    }

    #[tokio::test]
    async fn macro_expansion() {
        let req = MacroExpansionRequest::default();

        let client = Client::default();
        let res = client.macro_expansion(&req).await;

        println!("{res:?}");
        assert!(res.is_ok());
    }

    #[tokio::test]
    async fn crates() {
        let client = Client::default();
        let res = client.crates().await;

        println!("{res:?}");
        assert!(res.is_ok());
    }

    #[tokio::test]
    async fn version() {
        let client = Client::default();
        let res = client.versions().await;

        println!("{res:?}");
        assert!(res.is_ok());
    }

    #[tokio::test]
    #[ignore = "don't flood rust playground gist with useless gists"]
    async fn gist_create() {
        let req = GistCreateRequest::new("fn main() { println!(\"Hello, world!\"); }".into());

        let client = Client::default();
        let res = client.gist_create(&req).await;

        println!("{res:?}");
        assert!(res.is_ok());
    }

    #[tokio::test]
    async fn gist_get() {
        let id = "ba5e40fb63e78da440797e921bbf2aa6";

        let client = Client::default();
        let res = client.gist_get(id).await;

        println!("{res:?}");
        assert!(res.is_ok());
    }
}