cloud-sdk 0.39.0

no_std-first provider-neutral cloud SDK foundations.
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
//! no_std fixed-buffer writing helpers for provider crates.

mod encoder;

pub use encoder::{
    SnapshotEncoder, encode_snapshot, encode_snapshot_bounded, measure_snapshot,
    measure_snapshot_bounded,
};

/// Returns the base-10 encoded length of an unsigned integer.
#[must_use]
pub const fn u64_encoded_len(mut value: u64) -> usize {
    let mut len = 1_usize;
    while value >= 10 {
        value /= 10;
        len = len.saturating_add(1);
    }
    len
}

/// Returns the checked percent-encoded length of one component.
pub fn percent_encoded_len<E: Copy>(value: &str, error: E) -> Result<usize, E> {
    let mut len = 0_usize;
    for byte in value.bytes() {
        let width = if is_unreserved(byte) { 1 } else { 3 };
        len = len.checked_add(width).ok_or(error)?;
    }
    Ok(len)
}

/// Returns the checked length of JSON string contents after escaping.
pub fn json_string_escaped_len<E: Copy>(value: &str, error: E) -> Result<usize, E> {
    json_escaped_len(value, error)
}

/// Returns the checked encoded length of a complete JSON string.
pub fn json_string_len<E: Copy>(value: &str, error: E) -> Result<usize, E> {
    json_escaped_len(value, error)?.checked_add(2).ok_or(error)
}

/// Writes one byte into a caller-owned buffer.
pub fn write_byte<E: Copy>(
    output: &mut [u8],
    len: &mut usize,
    byte: u8,
    error: E,
) -> Result<(), E> {
    let next = len.checked_add(1).ok_or(error)?;
    let slot = output.get_mut(*len).ok_or(error)?;
    *slot = byte;
    *len = next;
    Ok(())
}

/// Writes a string into a caller-owned buffer without escaping.
pub fn write_str<E: Copy>(
    output: &mut [u8],
    len: &mut usize,
    value: &str,
    error: E,
) -> Result<(), E> {
    let end = len.checked_add(value.len()).ok_or(error)?;
    let target = output.get_mut(*len..end).ok_or(error)?;
    target.copy_from_slice(value.as_bytes());
    *len = end;
    Ok(())
}

/// Writes a base-10 unsigned integer into a caller-owned buffer.
pub fn write_u64<E: Copy>(
    output: &mut [u8],
    len: &mut usize,
    mut value: u64,
    error: E,
) -> Result<(), E> {
    let required = u64_encoded_len(value);
    ensure_capacity(output, *len, required, error)?;
    if value == 0 {
        return write_byte(output, len, b'0', error);
    }

    let mut digits = [0u8; 20];
    let mut cursor = digits.len();
    while value != 0 {
        cursor = cursor.checked_sub(1).ok_or(error)?;
        let digit = u8::try_from(value % 10).map_err(|_| error)?;
        let slot = digits.get_mut(cursor).ok_or(error)?;
        *slot = b'0'.checked_add(digit).ok_or(error)?;
        value /= 10;
    }

    let encoded = digits.get(cursor..).ok_or(error)?;
    for byte in encoded {
        write_byte(output, len, *byte, error)?;
    }
    Ok(())
}

/// Writes a percent-encoded query component into a caller-owned buffer.
pub fn write_percent_encoded<E: Copy>(
    output: &mut [u8],
    len: &mut usize,
    value: &str,
    error: E,
) -> Result<(), E> {
    let required = percent_encoded_len(value, error)?;
    ensure_capacity(output, *len, required, error)?;
    for byte in value.bytes() {
        if is_unreserved(byte) {
            write_byte(output, len, byte, error)?;
        } else {
            write_byte(output, len, b'%', error)?;
            write_byte(output, len, hex_digit(byte >> 4), error)?;
            write_byte(output, len, hex_digit(byte & 0x0f), error)?;
        }
    }
    Ok(())
}

/// Writes JSON-string contents with required escaping, without surrounding quotes.
pub fn write_json_string_escaped<E: Copy>(
    output: &mut [u8],
    len: &mut usize,
    value: &str,
    error: E,
) -> Result<(), E> {
    let required = json_escaped_len(value, error)?;
    ensure_capacity(output, *len, required, error)?;
    for byte in value.bytes() {
        match byte {
            b'"' => write_str(output, len, "\\\"", error)?,
            b'\\' => write_str(output, len, "\\\\", error)?,
            b'\n' => write_str(output, len, "\\n", error)?,
            b'\r' => write_str(output, len, "\\r", error)?,
            b'\t' => write_str(output, len, "\\t", error)?,
            0x00..=0x1f => {
                write_str(output, len, "\\u00", error)?;
                write_byte(output, len, hex_digit(byte >> 4), error)?;
                write_byte(output, len, hex_digit(byte & 0x0f), error)?;
            }
            _ => write_byte(output, len, byte, error)?,
        }
    }
    Ok(())
}

/// Writes a complete JSON string with surrounding quotes.
pub fn write_json_string<E: Copy>(
    output: &mut [u8],
    len: &mut usize,
    value: &str,
    error: E,
) -> Result<(), E> {
    let required = json_string_len(value, error)?;
    ensure_capacity(output, *len, required, error)?;
    write_byte(output, len, b'"', error)?;
    write_json_string_escaped(output, len, value, error)?;
    write_byte(output, len, b'"', error)
}

fn json_escaped_len<E: Copy>(value: &str, error: E) -> Result<usize, E> {
    let mut len = 0_usize;
    for byte in value.bytes() {
        let encoded = match byte {
            b'"' | b'\\' | b'\n' | b'\r' | b'\t' => 2,
            0x00..=0x1f => 6,
            _ => 1,
        };
        len = len.checked_add(encoded).ok_or(error)?;
    }
    Ok(len)
}

fn ensure_capacity<E: Copy>(
    output: &[u8],
    len: usize,
    additional: usize,
    error: E,
) -> Result<(), E> {
    let end = len.checked_add(additional).ok_or(error)?;
    output.get(len..end).ok_or(error)?;
    Ok(())
}

/// Writes `&` unless this is the first query pair.
pub fn write_query_separator<E: Copy>(
    output: &mut [u8],
    len: &mut usize,
    first: &mut bool,
    error: E,
) -> Result<(), E> {
    if *first {
        *first = false;
        return Ok(());
    }
    write_byte(output, len, b'&', error)
}

/// Writes a percent-encoded query key/value pair.
pub fn write_query_pair<E: Copy>(
    output: &mut [u8],
    len: &mut usize,
    first: &mut bool,
    key: &str,
    value: &str,
    error: E,
) -> Result<(), E> {
    write_query_separator(output, len, first, error)?;
    write_percent_encoded(output, len, key, error)?;
    write_byte(output, len, b'=', error)?;
    write_percent_encoded(output, len, value, error)
}

/// Writes a percent-encoded query key and base-10 integer value.
pub fn write_query_u64<E: Copy>(
    output: &mut [u8],
    len: &mut usize,
    first: &mut bool,
    key: &str,
    value: u64,
    error: E,
) -> Result<(), E> {
    write_query_separator(output, len, first, error)?;
    write_percent_encoded(output, len, key, error)?;
    write_byte(output, len, b'=', error)?;
    write_u64(output, len, value, error)
}

pub(super) const fn is_unreserved(byte: u8) -> bool {
    matches!(byte, b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'.' | b'_' | b'~')
}

pub(super) const fn hex_digit(nibble: u8) -> u8 {
    match nibble {
        0 => b'0',
        1 => b'1',
        2 => b'2',
        3 => b'3',
        4 => b'4',
        5 => b'5',
        6 => b'6',
        7 => b'7',
        8 => b'8',
        9 => b'9',
        10 => b'A',
        11 => b'B',
        12 => b'C',
        13 => b'D',
        14 => b'E',
        _ => b'F',
    }
}

#[cfg(test)]
mod tests {
    use super::{
        write_json_string, write_percent_encoded, write_query_pair, write_query_u64, write_str,
        write_u64,
    };

    #[derive(Clone, Copy, Debug, Eq, PartialEq)]
    enum TestError {
        TooSmall,
    }

    #[test]
    fn writes_decimal_numbers_including_zero() {
        let mut output = [0u8; 24];
        let mut len = 0;
        assert_eq!(
            write_u64(&mut output, &mut len, 0, TestError::TooSmall),
            Ok(())
        );
        assert_eq!(
            write_str(&mut output, &mut len, ",", TestError::TooSmall),
            Ok(())
        );
        assert_eq!(
            write_u64(&mut output, &mut len, u64::MAX, TestError::TooSmall),
            Ok(())
        );
        let written = output
            .get(..len)
            .and_then(|bytes| core::str::from_utf8(bytes).ok());
        assert_eq!(written, Some("0,18446744073709551615"));
    }

    #[test]
    fn reports_too_small_buffers() {
        let mut output = [0u8; 2];
        let mut len = 0;
        assert_eq!(
            write_u64(&mut output, &mut len, 100, TestError::TooSmall),
            Err(TestError::TooSmall)
        );
    }

    #[test]
    fn writes_percent_encoded_components_and_pairs() {
        let mut output = [0u8; 64];
        let mut len = 0;
        assert_eq!(
            write_percent_encoded(&mut output, &mut len, "env=prod", TestError::TooSmall),
            Ok(())
        );
        let encoded = output
            .get(..len)
            .and_then(|bytes| core::str::from_utf8(bytes).ok());
        assert_eq!(encoded, Some("env%3Dprod"));

        let mut output = [0u8; 64];
        let mut len = 0;
        let mut first = true;
        assert_eq!(
            write_query_pair(
                &mut output,
                &mut len,
                &mut first,
                "label_selector",
                "env=prod",
                TestError::TooSmall,
            ),
            Ok(())
        );
        assert_eq!(
            write_query_u64(
                &mut output,
                &mut len,
                &mut first,
                "page",
                0,
                TestError::TooSmall
            ),
            Ok(())
        );
        let query = output
            .get(..len)
            .and_then(|bytes| core::str::from_utf8(bytes).ok());
        assert_eq!(query, Some("label_selector=env%3Dprod&page=0"));
    }

    #[test]
    fn writes_json_strings_with_required_escaping() {
        let mut output = [0u8; 96];
        let mut len = 0;
        assert_eq!(
            write_json_string(
                &mut output,
                &mut len,
                "line\n\"quoted\"\\slash\t\u{001f}",
                TestError::TooSmall,
            ),
            Ok(())
        );
        let json = output
            .get(..len)
            .and_then(|bytes| core::str::from_utf8(bytes).ok());
        assert_eq!(json, Some("\"line\\n\\\"quoted\\\"\\\\slash\\t\\u001F\""));
    }

    #[test]
    fn json_writes_are_atomic_when_capacity_is_insufficient() {
        let mut output = [0xa5_u8; 7];
        let original = output;
        let mut len = 2;
        assert_eq!(
            write_json_string(
                &mut output,
                &mut len,
                "token=classified",
                TestError::TooSmall,
            ),
            Err(TestError::TooSmall)
        );
        assert_eq!(len, 2);
        assert_eq!(output, original);
    }

    #[test]
    fn json_writes_are_atomic_at_every_undersized_capacity() {
        let value = "line\n\"quoted\"\\slash\t\u{001f}";
        let mut complete = [0_u8; 96];
        let mut complete_len = 0;
        assert_eq!(
            write_json_string(&mut complete, &mut complete_len, value, TestError::TooSmall,),
            Ok(())
        );

        for capacity in 0..complete_len {
            let mut output = [0xa5_u8; 96];
            let original = output;
            let mut len = 0;
            assert_eq!(
                write_json_string(
                    output.get_mut(..capacity).unwrap_or_default(),
                    &mut len,
                    value,
                    TestError::TooSmall,
                ),
                Err(TestError::TooSmall)
            );
            assert_eq!(len, 0);
            assert_eq!(output, original);
        }
    }
}