lcpfs 2026.1.102

LCP File System - A ZFS-inspired copy-on-write filesystem for Rust
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
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
// Copyright 2025 LunaOS Contributors
// SPDX-License-Identifier: Apache-2.0

//! Core types for S3-compatible gateway.
//!
//! This module defines the fundamental data structures for S3 API compatibility,
//! including requests, responses, bucket/object metadata, and errors.

use alloc::collections::BTreeMap;
use alloc::string::{String, ToString};
use alloc::vec::Vec;

// ═══════════════════════════════════════════════════════════════════════════════
// HTTP TYPES
// ═══════════════════════════════════════════════════════════════════════════════

/// HTTP methods.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum HttpMethod {
    /// GET request.
    Get,
    /// PUT request.
    Put,
    /// POST request.
    Post,
    /// DELETE request.
    Delete,
    /// HEAD request.
    Head,
    /// OPTIONS request.
    Options,
}

impl HttpMethod {
    /// Parse from string.
    pub fn from_str(s: &str) -> Option<Self> {
        match s.to_uppercase().as_str() {
            "GET" => Some(HttpMethod::Get),
            "PUT" => Some(HttpMethod::Put),
            "POST" => Some(HttpMethod::Post),
            "DELETE" => Some(HttpMethod::Delete),
            "HEAD" => Some(HttpMethod::Head),
            "OPTIONS" => Some(HttpMethod::Options),
            _ => None,
        }
    }

    /// Convert to string.
    pub fn as_str(&self) -> &'static str {
        match self {
            HttpMethod::Get => "GET",
            HttpMethod::Put => "PUT",
            HttpMethod::Post => "POST",
            HttpMethod::Delete => "DELETE",
            HttpMethod::Head => "HEAD",
            HttpMethod::Options => "OPTIONS",
        }
    }
}

/// HTTP request.
#[derive(Debug, Clone)]
pub struct HttpRequest {
    /// HTTP method.
    pub method: HttpMethod,
    /// Request path (e.g., "/bucket/key").
    pub path: String,
    /// Query string parameters.
    pub query: BTreeMap<String, String>,
    /// HTTP headers.
    pub headers: BTreeMap<String, String>,
    /// Request body.
    pub body: Vec<u8>,
}

impl HttpRequest {
    /// Create a new request.
    pub fn new(method: HttpMethod, path: String) -> Self {
        Self {
            method,
            path,
            query: BTreeMap::new(),
            headers: BTreeMap::new(),
            body: Vec::new(),
        }
    }

    /// Get a header (case-insensitive).
    pub fn header(&self, name: &str) -> Option<&String> {
        let lower = name.to_lowercase();
        self.headers
            .iter()
            .find(|(k, _)| k.to_lowercase() == lower)
            .map(|(_, v)| v)
    }

    /// Get content length.
    pub fn content_length(&self) -> usize {
        self.header("content-length")
            .and_then(|s| s.parse().ok())
            .unwrap_or(0)
    }

    /// Get content type.
    pub fn content_type(&self) -> Option<&String> {
        self.header("content-type")
    }
}

/// HTTP response.
#[derive(Debug, Clone)]
pub struct HttpResponse {
    /// Status code.
    pub status: u16,
    /// HTTP headers.
    pub headers: BTreeMap<String, String>,
    /// Response body.
    pub body: Vec<u8>,
}

impl HttpResponse {
    /// Create a new response.
    pub fn new(status: u16) -> Self {
        Self {
            status,
            headers: BTreeMap::new(),
            body: Vec::new(),
        }
    }

    /// Create an OK response.
    pub fn ok() -> Self {
        Self::new(200)
    }

    /// Create a No Content response.
    pub fn no_content() -> Self {
        Self::new(204)
    }

    /// Create a Not Found response.
    pub fn not_found() -> Self {
        Self::new(404)
    }

    /// Create an error response.
    pub fn error(status: u16, code: &str, message: &str) -> Self {
        let xml = xml_error(code, message);
        let mut resp = Self::new(status);
        resp.body = xml.into_bytes();
        resp.headers
            .insert("Content-Type".into(), "application/xml".into());
        resp
    }

    /// Set a header.
    pub fn with_header(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
        self.headers.insert(name.into(), value.into());
        self
    }

    /// Set body.
    pub fn with_body(mut self, body: Vec<u8>) -> Self {
        self.body = body;
        self
    }

    /// Set XML body.
    pub fn with_xml(mut self, xml: String) -> Self {
        self.body = xml.into_bytes();
        self.headers
            .insert("Content-Type".into(), "application/xml".into());
        self
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// S3 OPERATIONS
// ═══════════════════════════════════════════════════════════════════════════════

/// S3 operation type.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum S3Operation {
    // Service operations
    /// List all buckets.
    ListBuckets,

    // Bucket operations
    /// Create a bucket.
    CreateBucket,
    /// Delete a bucket.
    DeleteBucket,
    /// Check if bucket exists.
    HeadBucket,
    /// List objects in bucket (v2).
    ListObjectsV2,
    /// Get bucket location.
    GetBucketLocation,
    /// Get bucket versioning status.
    GetBucketVersioning,
    /// Put bucket versioning.
    PutBucketVersioning,

    // Object operations
    /// Upload an object.
    PutObject,
    /// Download an object.
    GetObject,
    /// Delete an object.
    DeleteObject,
    /// Get object metadata.
    HeadObject,
    /// Copy an object.
    CopyObject,
    /// Delete multiple objects.
    DeleteObjects,

    // Multipart upload operations
    /// Initiate multipart upload.
    CreateMultipartUpload,
    /// Upload a part.
    UploadPart,
    /// Complete multipart upload.
    CompleteMultipartUpload,
    /// Abort multipart upload.
    AbortMultipartUpload,
    /// List parts.
    ListParts,
    /// List multipart uploads.
    ListMultipartUploads,

    // Versioning operations
    /// List object versions.
    ListObjectVersions,

    /// Unknown operation.
    Unknown(String),
}

impl S3Operation {
    /// Get the operation name.
    pub fn name(&self) -> &str {
        match self {
            S3Operation::ListBuckets => "ListBuckets",
            S3Operation::CreateBucket => "CreateBucket",
            S3Operation::DeleteBucket => "DeleteBucket",
            S3Operation::HeadBucket => "HeadBucket",
            S3Operation::ListObjectsV2 => "ListObjectsV2",
            S3Operation::GetBucketLocation => "GetBucketLocation",
            S3Operation::GetBucketVersioning => "GetBucketVersioning",
            S3Operation::PutBucketVersioning => "PutBucketVersioning",
            S3Operation::PutObject => "PutObject",
            S3Operation::GetObject => "GetObject",
            S3Operation::DeleteObject => "DeleteObject",
            S3Operation::HeadObject => "HeadObject",
            S3Operation::CopyObject => "CopyObject",
            S3Operation::DeleteObjects => "DeleteObjects",
            S3Operation::CreateMultipartUpload => "CreateMultipartUpload",
            S3Operation::UploadPart => "UploadPart",
            S3Operation::CompleteMultipartUpload => "CompleteMultipartUpload",
            S3Operation::AbortMultipartUpload => "AbortMultipartUpload",
            S3Operation::ListParts => "ListParts",
            S3Operation::ListMultipartUploads => "ListMultipartUploads",
            S3Operation::ListObjectVersions => "ListObjectVersions",
            S3Operation::Unknown(s) => s,
        }
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// S3 REQUEST
// ═══════════════════════════════════════════════════════════════════════════════

/// Parsed S3 request.
#[derive(Debug, Clone)]
pub struct S3Request {
    /// HTTP method.
    pub method: HttpMethod,
    /// Bucket name (if any).
    pub bucket: Option<String>,
    /// Object key (if any).
    pub key: Option<String>,
    /// Detected S3 operation.
    pub operation: S3Operation,
    /// HTTP headers.
    pub headers: BTreeMap<String, String>,
    /// Query parameters.
    pub query: BTreeMap<String, String>,
    /// Request body.
    pub body: Vec<u8>,
}

impl S3Request {
    /// Get a query parameter.
    pub fn query_param(&self, name: &str) -> Option<&String> {
        self.query.get(name)
    }

    /// Get a header (case-insensitive).
    pub fn header(&self, name: &str) -> Option<&String> {
        let lower = name.to_lowercase();
        self.headers
            .iter()
            .find(|(k, _)| k.to_lowercase() == lower)
            .map(|(_, v)| v)
    }

    /// Get the x-amz-copy-source header.
    pub fn copy_source(&self) -> Option<&String> {
        self.header("x-amz-copy-source")
    }

    /// Get the upload ID from query params.
    pub fn upload_id(&self) -> Option<&String> {
        self.query.get("uploadId")
    }

    /// Get the part number from query params.
    pub fn part_number(&self) -> Option<u32> {
        self.query.get("partNumber").and_then(|s| s.parse().ok())
    }

    /// Get the Range header parsed as (start, end).
    pub fn range(&self) -> Option<(u64, Option<u64>)> {
        let range = self.header("range")?;
        parse_range(range)
    }
}

/// Parse HTTP Range header.
fn parse_range(range: &str) -> Option<(u64, Option<u64>)> {
    // Format: bytes=start-end or bytes=start-
    let range = range.strip_prefix("bytes=")?;
    let parts: Vec<&str> = range.split('-').collect();
    if parts.len() != 2 {
        return None;
    }

    let start: u64 = parts[0].parse().ok()?;
    let end = if parts[1].is_empty() {
        None
    } else {
        Some(parts[1].parse().ok()?)
    };

    Some((start, end))
}

// ═══════════════════════════════════════════════════════════════════════════════
// BUCKET AND OBJECT METADATA
// ═══════════════════════════════════════════════════════════════════════════════

/// Bucket information.
#[derive(Debug, Clone)]
pub struct BucketInfo {
    /// Bucket name.
    pub name: String,
    /// Creation date (ISO 8601).
    pub creation_date: String,
}

/// Object metadata.
#[derive(Debug, Clone)]
pub struct S3ObjectMeta {
    /// Object key.
    pub key: String,
    /// Object size in bytes.
    pub size: u64,
    /// ETag (typically MD5 hash).
    pub etag: String,
    /// Last modified (ISO 8601).
    pub last_modified: String,
    /// Storage class.
    pub storage_class: String,
    /// Content type.
    pub content_type: String,
    /// Custom metadata.
    pub metadata: BTreeMap<String, String>,
}

impl S3ObjectMeta {
    /// Create new object metadata.
    pub fn new(key: String, size: u64, etag: String, last_modified: String) -> Self {
        Self {
            key,
            size,
            etag,
            last_modified,
            storage_class: "STANDARD".into(),
            content_type: "application/octet-stream".into(),
            metadata: BTreeMap::new(),
        }
    }
}

/// Object version.
#[derive(Debug, Clone)]
pub struct S3ObjectVersion {
    /// Object key.
    pub key: String,
    /// Version ID.
    pub version_id: String,
    /// Is this the latest version?
    pub is_latest: bool,
    /// Last modified.
    pub last_modified: String,
    /// ETag.
    pub etag: String,
    /// Size.
    pub size: u64,
    /// Storage class.
    pub storage_class: String,
}

// ═══════════════════════════════════════════════════════════════════════════════
// LIST PARAMETERS
// ═══════════════════════════════════════════════════════════════════════════════

/// Parameters for ListObjectsV2.
#[derive(Debug, Clone, Default)]
pub struct ListObjectsParams {
    /// Prefix to filter objects.
    pub prefix: Option<String>,
    /// Delimiter for grouping.
    pub delimiter: Option<String>,
    /// Maximum keys to return.
    pub max_keys: u32,
    /// Continuation token.
    pub continuation_token: Option<String>,
    /// Start after this key.
    pub start_after: Option<String>,
    /// Encoding type.
    pub encoding_type: Option<String>,
}

impl ListObjectsParams {
    /// Parse from query parameters.
    pub fn from_query(query: &BTreeMap<String, String>) -> Self {
        Self {
            prefix: query.get("prefix").cloned(),
            delimiter: query.get("delimiter").cloned(),
            max_keys: query
                .get("max-keys")
                .and_then(|s| s.parse().ok())
                .unwrap_or(1000),
            continuation_token: query.get("continuation-token").cloned(),
            start_after: query.get("start-after").cloned(),
            encoding_type: query.get("encoding-type").cloned(),
        }
    }
}

/// Result of ListObjectsV2.
#[derive(Debug, Clone)]
pub struct ListObjectsResult {
    /// Objects matching the query.
    pub contents: Vec<S3ObjectMeta>,
    /// Common prefixes (when using delimiter).
    pub common_prefixes: Vec<String>,
    /// Is the result truncated?
    pub is_truncated: bool,
    /// Continuation token for next page.
    pub next_continuation_token: Option<String>,
    /// Key count.
    pub key_count: usize,
}

// ═══════════════════════════════════════════════════════════════════════════════
// MULTIPART UPLOAD
// ═══════════════════════════════════════════════════════════════════════════════

/// Multipart upload state.
#[derive(Debug, Clone)]
pub struct MultipartUpload {
    /// Upload ID.
    pub upload_id: String,
    /// Bucket name.
    pub bucket: String,
    /// Object key.
    pub key: String,
    /// Uploaded parts.
    pub parts: BTreeMap<u32, UploadPart>,
    /// Creation time.
    pub initiated: u64,
}

/// An uploaded part.
#[derive(Debug, Clone)]
pub struct UploadPart {
    /// Part number.
    pub part_number: u32,
    /// ETag.
    pub etag: String,
    /// Part size.
    pub size: u64,
    /// Last modified.
    pub last_modified: u64,
}

/// Part specification in complete request.
#[derive(Debug, Clone)]
pub struct CompletePart {
    /// Part number.
    pub part_number: u32,
    /// ETag.
    pub etag: String,
}

// ═══════════════════════════════════════════════════════════════════════════════
// CONFIGURATION
// ═══════════════════════════════════════════════════════════════════════════════

/// S3 gateway configuration.
#[derive(Debug, Clone)]
pub struct S3GatewayConfig {
    /// Listen address.
    pub bind_addr: String,
    /// Port.
    pub port: u16,
    /// Access key for authentication.
    pub access_key: String,
    /// Secret key for authentication.
    pub secret_key: String,
    /// AWS region name.
    pub region: String,
    /// Default dataset for all buckets.
    pub default_dataset: Option<String>,
    /// Bucket name to dataset mapping.
    pub bucket_map: BTreeMap<String, String>,
    /// Enable anonymous access (no auth required).
    pub allow_anonymous: bool,
    /// Enable versioning.
    pub enable_versioning: bool,
}

impl Default for S3GatewayConfig {
    fn default() -> Self {
        Self {
            bind_addr: "0.0.0.0".into(),
            port: 9000,
            access_key: "AKIAIOSFODNN7EXAMPLE".into(),
            secret_key: "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY".into(),
            region: "us-east-1".into(),
            default_dataset: None,
            bucket_map: BTreeMap::new(),
            allow_anonymous: false,
            enable_versioning: true,
        }
    }
}

impl S3GatewayConfig {
    /// Create a new config.
    pub fn new(access_key: String, secret_key: String) -> Self {
        Self {
            access_key,
            secret_key,
            ..Default::default()
        }
    }

    /// Map a bucket to a dataset.
    pub fn map_bucket(&mut self, bucket: &str, dataset: &str) {
        self.bucket_map.insert(bucket.into(), dataset.into());
    }

    /// Get dataset for a bucket.
    pub fn dataset_for_bucket(&self, bucket: &str) -> Option<&String> {
        self.bucket_map
            .get(bucket)
            .or(self.default_dataset.as_ref())
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// ERRORS
// ═══════════════════════════════════════════════════════════════════════════════

/// S3 error.
#[derive(Debug, Clone)]
pub enum S3Error {
    /// Access denied.
    AccessDenied,
    /// Invalid access key.
    InvalidAccessKeyId,
    /// Signature does not match.
    SignatureDoesNotMatch,
    /// Bucket not found.
    NoSuchBucket,
    /// Key not found.
    NoSuchKey,
    /// Bucket already exists.
    BucketAlreadyExists,
    /// Bucket not empty.
    BucketNotEmpty,
    /// Invalid bucket name.
    InvalidBucketName,
    /// Invalid argument.
    InvalidArgument(String),
    /// Invalid part.
    InvalidPart,
    /// Invalid part order.
    InvalidPartOrder,
    /// No such upload.
    NoSuchUpload,
    /// Entity too small.
    EntityTooSmall,
    /// Entity too large.
    EntityTooLarge,
    /// Method not allowed.
    MethodNotAllowed,
    /// Internal error.
    InternalError(String),
    /// Not implemented.
    NotImplemented,
}

impl S3Error {
    /// Get the error code.
    pub fn code(&self) -> &'static str {
        match self {
            S3Error::AccessDenied => "AccessDenied",
            S3Error::InvalidAccessKeyId => "InvalidAccessKeyId",
            S3Error::SignatureDoesNotMatch => "SignatureDoesNotMatch",
            S3Error::NoSuchBucket => "NoSuchBucket",
            S3Error::NoSuchKey => "NoSuchKey",
            S3Error::BucketAlreadyExists => "BucketAlreadyExists",
            S3Error::BucketNotEmpty => "BucketNotEmpty",
            S3Error::InvalidBucketName => "InvalidBucketName",
            S3Error::InvalidArgument(_) => "InvalidArgument",
            S3Error::InvalidPart => "InvalidPart",
            S3Error::InvalidPartOrder => "InvalidPartOrder",
            S3Error::NoSuchUpload => "NoSuchUpload",
            S3Error::EntityTooSmall => "EntityTooSmall",
            S3Error::EntityTooLarge => "EntityTooLarge",
            S3Error::MethodNotAllowed => "MethodNotAllowed",
            S3Error::InternalError(_) => "InternalError",
            S3Error::NotImplemented => "NotImplemented",
        }
    }

    /// Get the error message.
    pub fn message(&self) -> String {
        match self {
            S3Error::AccessDenied => "Access Denied".into(),
            S3Error::InvalidAccessKeyId => "The access key ID you provided does not exist".into(),
            S3Error::SignatureDoesNotMatch => "The signature does not match".into(),
            S3Error::NoSuchBucket => "The specified bucket does not exist".into(),
            S3Error::NoSuchKey => "The specified key does not exist".into(),
            S3Error::BucketAlreadyExists => "The bucket already exists".into(),
            S3Error::BucketNotEmpty => "The bucket is not empty".into(),
            S3Error::InvalidBucketName => "The bucket name is invalid".into(),
            S3Error::InvalidArgument(msg) => msg.clone(),
            S3Error::InvalidPart => "One or more parts specified were not found".into(),
            S3Error::InvalidPartOrder => "Parts must be uploaded in order".into(),
            S3Error::NoSuchUpload => "The upload ID does not exist".into(),
            S3Error::EntityTooSmall => "Part is too small".into(),
            S3Error::EntityTooLarge => "Entity is too large".into(),
            S3Error::MethodNotAllowed => "Method not allowed".into(),
            S3Error::InternalError(msg) => msg.clone(),
            S3Error::NotImplemented => "Not implemented".into(),
        }
    }

    /// Get the HTTP status code.
    pub fn status_code(&self) -> u16 {
        match self {
            S3Error::AccessDenied => 403,
            S3Error::InvalidAccessKeyId => 403,
            S3Error::SignatureDoesNotMatch => 403,
            S3Error::NoSuchBucket => 404,
            S3Error::NoSuchKey => 404,
            S3Error::BucketAlreadyExists => 409,
            S3Error::BucketNotEmpty => 409,
            S3Error::InvalidBucketName => 400,
            S3Error::InvalidArgument(_) => 400,
            S3Error::InvalidPart => 400,
            S3Error::InvalidPartOrder => 400,
            S3Error::NoSuchUpload => 404,
            S3Error::EntityTooSmall => 400,
            S3Error::EntityTooLarge => 400,
            S3Error::MethodNotAllowed => 405,
            S3Error::InternalError(_) => 500,
            S3Error::NotImplemented => 501,
        }
    }

    /// Convert to HTTP response.
    pub fn to_response(&self) -> HttpResponse {
        HttpResponse::error(self.status_code(), self.code(), &self.message())
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// XML HELPERS
// ═══════════════════════════════════════════════════════════════════════════════

/// Generate XML error response.
pub fn xml_error(code: &str, message: &str) -> String {
    alloc::format!(
        "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\
         <Error><Code>{}</Code><Message>{}</Message></Error>",
        xml_escape(code),
        xml_escape(message)
    )
}

/// Escape XML special characters.
pub fn xml_escape(s: &str) -> String {
    let mut result = String::with_capacity(s.len());
    for c in s.chars() {
        match c {
            '<' => result.push_str("&lt;"),
            '>' => result.push_str("&gt;"),
            '&' => result.push_str("&amp;"),
            '"' => result.push_str("&quot;"),
            '\'' => result.push_str("&apos;"),
            _ => result.push(c),
        }
    }
    result
}

// ═══════════════════════════════════════════════════════════════════════════════
// TESTS
// ═══════════════════════════════════════════════════════════════════════════════

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

    #[test]
    fn test_http_method() {
        assert_eq!(HttpMethod::from_str("GET"), Some(HttpMethod::Get));
        assert_eq!(HttpMethod::from_str("put"), Some(HttpMethod::Put));
        assert_eq!(HttpMethod::from_str("INVALID"), None);
        assert_eq!(HttpMethod::Get.as_str(), "GET");
    }

    #[test]
    fn test_http_request() {
        let mut req = HttpRequest::new(HttpMethod::Get, "/bucket/key".into());
        req.headers
            .insert("Content-Type".into(), "text/plain".into());
        req.headers.insert("Content-Length".into(), "100".into());

        assert_eq!(req.content_type(), Some(&"text/plain".to_string()));
        assert_eq!(req.content_length(), 100);
    }

    #[test]
    fn test_http_response() {
        let resp = HttpResponse::ok()
            .with_header("X-Custom", "value")
            .with_body(b"test".to_vec());

        assert_eq!(resp.status, 200);
        assert_eq!(resp.headers.get("X-Custom"), Some(&"value".to_string()));
        assert_eq!(resp.body, b"test");
    }

    #[test]
    fn test_parse_range() {
        assert_eq!(parse_range("bytes=0-100"), Some((0, Some(100))));
        assert_eq!(parse_range("bytes=50-"), Some((50, None)));
        assert_eq!(parse_range("invalid"), None);
    }

    #[test]
    fn test_s3_error() {
        let err = S3Error::NoSuchKey;
        assert_eq!(err.code(), "NoSuchKey");
        assert_eq!(err.status_code(), 404);
    }

    #[test]
    fn test_xml_escape() {
        assert_eq!(xml_escape("<test>"), "&lt;test&gt;");
        assert_eq!(xml_escape("a&b"), "a&amp;b");
        assert_eq!(xml_escape("\"quote\""), "&quot;quote&quot;");
    }

    #[test]
    fn test_xml_error() {
        let xml = xml_error("NoSuchKey", "Key not found");
        assert!(xml.contains("<Code>NoSuchKey</Code>"));
        assert!(xml.contains("<Message>Key not found</Message>"));
    }

    #[test]
    fn test_config_default() {
        let config = S3GatewayConfig::default();
        assert_eq!(config.port, 9000);
        assert_eq!(config.region, "us-east-1");
    }

    #[test]
    fn test_config_bucket_map() {
        let mut config = S3GatewayConfig::default();
        config.map_bucket("mybucket", "tank/data");

        assert_eq!(
            config.dataset_for_bucket("mybucket"),
            Some(&"tank/data".to_string())
        );
        assert_eq!(config.dataset_for_bucket("unknown"), None);
    }

    #[test]
    fn test_list_params() {
        let mut query = BTreeMap::new();
        query.insert("prefix".into(), "folder/".into());
        query.insert("delimiter".into(), "/".into());
        query.insert("max-keys".into(), "100".into());

        let params = ListObjectsParams::from_query(&query);
        assert_eq!(params.prefix, Some("folder/".into()));
        assert_eq!(params.delimiter, Some("/".into()));
        assert_eq!(params.max_keys, 100);
    }

    #[test]
    fn test_object_meta() {
        let meta = S3ObjectMeta::new(
            "test.txt".into(),
            1000,
            "abc123".into(),
            "2024-01-01T00:00:00Z".into(),
        );

        assert_eq!(meta.key, "test.txt");
        assert_eq!(meta.size, 1000);
        assert_eq!(meta.storage_class, "STANDARD");
    }

    #[test]
    fn test_s3_operation_name() {
        assert_eq!(S3Operation::ListBuckets.name(), "ListBuckets");
        assert_eq!(S3Operation::PutObject.name(), "PutObject");
        assert_eq!(S3Operation::Unknown("Foo".into()).name(), "Foo");
    }
}