carla 0.14.1

Rust client library for Carla simulator
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
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
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
//! Error types for CARLA operations.
//!
//! This module provides structured error types that classify failures into actionable categories,
//! enabling users to handle specific error conditions (like connection failures) differently from others.
//!
//! # Error Categories
//!
//! - [`ConnectionError`] - Network issues, timeouts, disconnections (→ reconnect, retry)
//! - [`ResourceError`] - Not found, destroyed, unavailable (→ check availability, recreate)
//! - [`OperationError`] - Spawn failures, physics errors (→ validate preconditions, retry)
//! - [`ValidationError`] - Invalid parameters, out of bounds (→ fix input)
//! - [`MapError`] - Map loading, waypoint issues (→ load different map, fallback)
//! - [`SensorError`] - Data unavailable, configuration errors (→ reconfigure, use fallback)
//! - [`InternalError`] - FFI errors, bugs (→ report issue)
//!
//! # Examples
//!
//! ## Connection Retry with Exponential Backoff
//!
//! ```no_run
//! use carla::{CarlaError, Client, ConnectionError};
//! use std::time::Duration;
//!
//! fn connect_with_retry(host: &str, port: u16, max_retries: u32) -> carla::Result<Client> {
//!     let mut backoff = Duration::from_millis(100);
//!
//!     for attempt in 0..max_retries {
//!         match Client::connect(host, port, None) {
//!             Ok(client) => return Ok(client),
//!             Err(CarlaError::Connection(ConnectionError::Timeout { .. })) => {
//!                 eprintln!(
//!                     "Connection timeout (attempt {}/{}), retrying in {:?}...",
//!                     attempt + 1,
//!                     max_retries,
//!                     backoff
//!                 );
//!                 std::thread::sleep(backoff);
//!                 backoff *= 2; // Exponential backoff
//!             }
//!             Err(e) => return Err(e), // Other errors are not retryable
//!         }
//!     }
//!
//!     Err(CarlaError::Connection(ConnectionError::Timeout {
//!         operation: "connect".to_string(),
//!         duration: backoff,
//!         source: None,
//!     }))
//! }
//! ```
//!
//! ## Spawn with Fallback Locations
//!
//! ```no_run
//! use carla::{CarlaError, OperationError};
//! # use carla::client::{ActorBlueprint, World, Actor};
//!
//! fn spawn_vehicle_with_fallback(
//!     world: &World,
//!     blueprint: &ActorBlueprint,
//! ) -> carla::Result<Actor> {
//!     let spawn_points = world.map().recommended_spawn_points();
//!
//!     for (i, transform) in spawn_points.iter().enumerate() {
//!         match world.spawn_actor(blueprint, transform) {
//!             Ok(actor) => {
//!                 println!("Spawned at spawn point {}", i);
//!                 return Ok(actor);
//!             }
//!             Err(CarlaError::Operation(OperationError::SpawnFailed { reason, .. })) => {
//!                 eprintln!("Spawn point {} failed: {}, trying next...", i, reason);
//!                 continue;
//!             }
//!             Err(e) => return Err(e), // Other errors are fatal
//!         }
//!     }
//!
//!     Err(CarlaError::Operation(OperationError::SpawnFailed {
//!         blueprint: blueprint.id().to_string(),
//!         transform: "all spawn points".to_string(),
//!         reason: "All spawn points exhausted".to_string(),
//!         source: None,
//!     }))
//! }
//! ```

pub mod ffi;

use std::{fmt, time::Duration};

/// Main error type for all CARLA operations.
///
/// This enum categorizes errors into actionable groups, allowing users to handle
/// specific error conditions with appropriate recovery strategies.
#[derive(Debug, thiserror::Error)]
pub enum CarlaError {
    /// Connection-related errors (network, timeouts, disconnections)
    #[error(transparent)]
    Connection(#[from] ConnectionError),

    /// Resource-related errors (actors, blueprints not found, etc.)
    #[error(transparent)]
    Resource(#[from] ResourceError),

    /// Operation failures (spawn, physics, simulation errors)
    #[error(transparent)]
    Operation(#[from] OperationError),

    /// Validation errors (invalid parameters, out of bounds, etc.)
    #[error(transparent)]
    Validation(#[from] ValidationError),

    /// Map-related errors (loading, waypoints, topology)
    #[error(transparent)]
    Map(#[from] MapError),

    /// Sensor-related errors (data, configuration, listening)
    #[error(transparent)]
    Sensor(#[from] SensorError),

    /// Internal errors (FFI, unexpected states, bugs)
    #[error(transparent)]
    Internal(#[from] InternalError),

    /// I/O errors (file operations)
    #[error(transparent)]
    Io(#[from] std::io::Error),
}

/// Connection and network errors.
///
/// These errors typically indicate transient issues that may be resolved by:
/// - Retrying with exponential backoff
/// - Reconnecting to the server
/// - Checking network connectivity
#[derive(Debug, thiserror::Error)]
pub enum ConnectionError {
    /// Operation timed out waiting for server response.
    ///
    /// This usually indicates:
    /// - Network congestion
    /// - Server overload
    /// - Operation taking longer than expected
    ///
    /// **Recovery**: Retry with longer timeout or exponential backoff
    #[error("Operation '{operation}' timed out after {duration:?}")]
    Timeout {
        /// The operation that timed out
        operation: String,
        /// Duration waited before timeout
        duration: Duration,
        /// Optional source error
        #[source]
        source: Option<Box<dyn std::error::Error + Send + Sync>>,
    },

    /// Lost connection to CARLA server.
    ///
    /// This indicates the connection to the server was lost during an operation.
    ///
    /// **Recovery**: Reconnect to server and retry operation
    #[error("Disconnected from CARLA server: {reason}")]
    Disconnected {
        /// Reason for disconnection
        reason: String,
        /// Optional source error
        #[source]
        source: Option<Box<dyn std::error::Error + Send + Sync>>,
    },

    /// Invalid server endpoint configuration.
    ///
    /// This indicates the host/port combination is invalid or unreachable.
    ///
    /// **Recovery**: Check server configuration and network settings
    #[error("Invalid server endpoint: {host}:{port}")]
    InvalidEndpoint {
        /// Host address
        host: String,
        /// Port number
        port: u16,
        /// Optional source error
        #[source]
        source: Option<Box<dyn std::error::Error + Send + Sync>>,
    },
}

/// Resource not found, unavailable, or destroyed.
///
/// These errors indicate issues with CARLA resources (actors, blueprints, maps, etc.).
///
/// **Recovery strategies**:
/// - Check resource existence before use
/// - Use alternative resources
/// - Recreate destroyed resources
#[derive(Debug, thiserror::Error)]
pub enum ResourceError {
    /// Resource not found (actor, blueprint, map, etc.).
    ///
    /// This usually means:
    /// - Blueprint ID is invalid or not in library
    /// - Actor has been destroyed
    /// - Map is not available on server
    ///
    /// **Recovery**: Use different resource or check availability first
    #[error("{resource_type} not found: {identifier}{}", context.as_ref().map(|c| format!(" ({})", c)).unwrap_or_default())]
    NotFound {
        /// Type of resource that was not found
        resource_type: ResourceType,
        /// Identifier (ID, name, etc.)
        identifier: String,
        /// Optional context information
        context: Option<String>,
    },

    /// Resource already exists (duplicate ID, etc.).
    ///
    /// **Recovery**: Use existing resource or choose different identifier
    #[error("{resource_type} already exists: {identifier}")]
    AlreadyExists {
        /// Type of resource
        resource_type: ResourceType,
        /// Identifier
        identifier: String,
    },

    /// Resource was destroyed/deleted.
    ///
    /// This indicates attempting to use a resource that has been destroyed.
    ///
    /// **Recovery**: Recreate resource if needed
    #[error("{resource_type} was destroyed: {identifier}")]
    Destroyed {
        /// Type of resource
        resource_type: ResourceType,
        /// Identifier
        identifier: String,
    },

    /// Resource temporarily unavailable.
    ///
    /// **Recovery**: Wait and retry, or use alternative resource
    #[error("{resource_type} unavailable: {reason}")]
    Unavailable {
        /// Type of resource
        resource_type: ResourceType,
        /// Reason for unavailability
        reason: String,
    },
}

/// Types of resources in CARLA.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ResourceType {
    /// Actor (vehicle, walker, sensor, etc.)
    Actor,
    /// Blueprint (actor template)
    Blueprint,
    /// Map (world map)
    Map,
    /// Sensor (camera, lidar, etc.)
    Sensor,
    /// Traffic light
    TrafficLight,
    /// Waypoint (navigation point)
    Waypoint,
    /// Episode (simulation instance)
    Episode,
    /// Recording (replay data)
    Recording,
}

/// Operation failures during simulation.
///
/// These errors indicate that a simulation operation failed due to:
/// - Collision with existing objects
/// - Invalid simulation state
/// - Physics constraints
///
/// **Recovery strategies**:
/// - Validate preconditions before operation
/// - Retry with different parameters
/// - Skip operation if not critical
#[derive(Debug, thiserror::Error)]
pub enum OperationError {
    /// Failed to spawn actor.
    ///
    /// Common causes:
    /// - Spawn location collides with existing actor
    /// - Spawn location out of map bounds
    /// - Blueprint configuration invalid
    ///
    /// **Recovery**: Try different spawn location or validate location first
    #[error("Failed to spawn actor '{blueprint}' at {transform}: {reason}")]
    SpawnFailed {
        /// Blueprint ID
        blueprint: String,
        /// Spawn transform (formatted for display)
        transform: String,
        /// Reason for failure
        reason: String,
        /// Optional source error
        #[source]
        source: Option<Box<dyn std::error::Error + Send + Sync>>,
    },

    /// Invalid transform (collision, out of bounds, etc.).
    ///
    /// **Recovery**: Validate transform before use
    #[error("Invalid transform {transform}: {reason}")]
    InvalidTransform {
        /// Transform (formatted for display)
        transform: String,
        /// Reason for invalidity
        reason: String,
    },

    /// Operation requires physics to be enabled.
    ///
    /// **Recovery**: Enable physics on actor before operation
    #[error("Operation '{operation}' requires physics for actor {actor_id}")]
    PhysicsDisabled {
        /// Actor ID
        actor_id: u32,
        /// Operation that requires physics
        operation: String,
    },

    /// General simulation error.
    ///
    /// **Recovery**: Check simulation state and logs
    #[error("Simulation error: {message}")]
    SimulationError {
        /// Error message
        message: String,
        /// Optional source error
        #[source]
        source: Option<Box<dyn std::error::Error + Send + Sync>>,
    },
}

/// Parameter validation errors.
///
/// These errors indicate that user-provided parameters are invalid.
///
/// **Recovery**: Fix parameters and retry
#[derive(Debug, thiserror::Error)]
pub enum ValidationError {
    /// Invalid blueprint ID or configuration.
    ///
    /// **Recovery**: Check blueprint ID and attributes
    #[error("Invalid blueprint '{blueprint_id}': {reason}")]
    InvalidBlueprint {
        /// Blueprint ID
        blueprint_id: String,
        /// Reason for invalidity
        reason: String,
    },

    /// Invalid attribute value.
    ///
    /// **Recovery**: Use valid attribute value from blueprint
    #[error("Invalid attribute '{name}' = '{value}': {reason}")]
    InvalidAttribute {
        /// Attribute name
        name: String,
        /// Attribute value
        value: String,
        /// Reason for invalidity
        reason: String,
    },

    /// Value out of valid range.
    ///
    /// **Recovery**: Use value within specified range
    #[error("Value {value} out of bounds [{min}, {max}] for field '{field}'")]
    OutOfBounds {
        /// Field name
        field: String,
        /// Actual value
        value: String,
        /// Minimum valid value
        min: String,
        /// Maximum valid value
        max: String,
    },

    /// Invalid configuration.
    ///
    /// **Recovery**: Check configuration documentation
    #[error("Invalid configuration for '{setting}': {reason}")]
    InvalidConfiguration {
        /// Configuration setting name
        setting: String,
        /// Reason for invalidity
        reason: String,
    },
}

/// Map-related errors.
///
/// These errors occur during map operations.
///
/// **Recovery strategies**:
/// - Load different map
/// - Use spawn points instead of custom locations
/// - Check map availability on server
#[derive(Debug, thiserror::Error)]
pub enum MapError {
    /// Failed to load map.
    ///
    /// **Recovery**: Check map name and server availability
    #[error("Failed to load map '{map_name}': {reason}")]
    LoadFailed {
        /// Map name
        map_name: String,
        /// Reason for failure
        reason: String,
        /// Optional source error
        #[source]
        source: Option<Box<dyn std::error::Error + Send + Sync>>,
    },

    /// Invalid waypoint location.
    ///
    /// **Recovery**: Use recommended spawn points or validate location
    #[error("Invalid waypoint at {location}: {reason}")]
    InvalidWaypoint {
        /// Location (formatted for display)
        location: String,
        /// Reason for invalidity
        reason: String,
    },

    /// Map topology error.
    ///
    /// **Recovery**: Report issue, may indicate map data corruption
    #[error("Map topology error: {message}")]
    TopologyError {
        /// Error message
        message: String,
    },
}

/// Sensor-related errors.
///
/// These errors occur during sensor operations.
///
/// **Recovery strategies**:
/// - Reconfigure sensor
/// - Use fallback data source
/// - Check sensor availability
#[derive(Debug, thiserror::Error)]
pub enum SensorError {
    /// Sensor data not available.
    ///
    /// **Recovery**: Wait for sensor data or use last known data
    #[error("Sensor data unavailable for sensor {sensor_id}: {reason}")]
    DataUnavailable {
        /// Sensor actor ID
        sensor_id: u32,
        /// Reason for unavailability
        reason: String,
    },

    /// Invalid sensor configuration.
    ///
    /// **Recovery**: Check sensor blueprint attributes
    #[error("Invalid sensor configuration for '{sensor_type}': {reason}")]
    InvalidConfiguration {
        /// Sensor type
        sensor_type: String,
        /// Reason for invalidity
        reason: String,
    },

    /// Failed to start listening to sensor.
    ///
    /// **Recovery**: Check sensor state and try again
    #[error("Failed to listen to sensor {sensor_id}: {reason}")]
    ListenFailed {
        /// Sensor actor ID
        sensor_id: u32,
        /// Reason for failure
        reason: String,
        /// Optional source error
        #[source]
        source: Option<Box<dyn std::error::Error + Send + Sync>>,
    },
}

/// Internal errors (FFI, unexpected states).
///
/// These errors usually indicate bugs or unexpected conditions.
///
/// **Recovery**: Report issue with full error details
#[derive(Debug, thiserror::Error)]
pub enum InternalError {
    /// FFI boundary error.
    ///
    /// **Recovery**: Report issue, may indicate library bug
    #[error("FFI error: {message}")]
    FfiError {
        /// Error message
        message: String,
        /// Optional source error
        #[source]
        source: Option<Box<dyn std::error::Error + Send + Sync>>,
    },

    /// Serialization/deserialization error.
    ///
    /// **Recovery**: Report issue with data format
    #[error("Serialization error in {context}")]
    SerializationError {
        /// Context where serialization failed
        context: String,
        /// Source error
        #[source]
        source: Box<dyn std::error::Error + Send + Sync>,
    },

    /// Unexpected internal state (likely a bug).
    ///
    /// **Recovery**: Report issue with full error details
    #[error("Unexpected state: {description}")]
    UnexpectedState {
        /// Description of unexpected state
        description: String,
    },
}

/// Result type for CARLA operations.
pub type Result<T> = std::result::Result<T, CarlaError>;

impl ResourceType {
    /// Returns the string representation of this resource type.
    pub fn as_str(&self) -> &'static str {
        match self {
            ResourceType::Actor => "Actor",
            ResourceType::Blueprint => "Blueprint",
            ResourceType::Map => "Map",
            ResourceType::Sensor => "Sensor",
            ResourceType::TrafficLight => "TrafficLight",
            ResourceType::Waypoint => "Waypoint",
            ResourceType::Episode => "Episode",
            ResourceType::Recording => "Recording",
        }
    }
}

impl fmt::Display for ResourceType {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_str())
    }
}

impl CarlaError {
    /// Returns `true` if this is a connection-related error.
    ///
    /// # Examples
    ///
    /// ```
    /// # use carla::{CarlaError, ConnectionError};
    /// # use std::time::Duration;
    /// let error: CarlaError = ConnectionError::Timeout {
    ///     operation: "spawn".to_string(),
    ///     duration: Duration::from_secs(5),
    ///     source: None,
    /// }
    /// .into();
    ///
    /// assert!(error.is_connection_error());
    /// ```
    pub fn is_connection_error(&self) -> bool {
        matches!(self, CarlaError::Connection(_))
    }

    /// Returns `true` if this is a timeout error.
    ///
    /// # Examples
    ///
    /// ```
    /// # use carla::{CarlaError, ConnectionError};
    /// # use std::time::Duration;
    /// let error: CarlaError = ConnectionError::Timeout {
    ///     operation: "spawn".to_string(),
    ///     duration: Duration::from_secs(5),
    ///     source: None,
    /// }
    /// .into();
    ///
    /// assert!(error.is_timeout());
    /// ```
    pub fn is_timeout(&self) -> bool {
        matches!(
            self,
            CarlaError::Connection(ConnectionError::Timeout { .. })
        )
    }

    /// Returns `true` if this is a resource not found error.
    ///
    /// # Examples
    ///
    /// ```
    /// # use carla::{CarlaError, ResourceError, ResourceType};
    /// let error: CarlaError = ResourceError::NotFound {
    ///     resource_type: ResourceType::Blueprint,
    ///     identifier: "vehicle.tesla.model3".to_string(),
    ///     context: None,
    /// }
    /// .into();
    ///
    /// assert!(error.is_not_found());
    /// ```
    pub fn is_not_found(&self) -> bool {
        matches!(self, CarlaError::Resource(ResourceError::NotFound { .. }))
    }

    /// Returns `true` if this is a validation error.
    pub fn is_validation_error(&self) -> bool {
        matches!(self, CarlaError::Validation(_))
    }

    /// Returns `true` if this is an operation error.
    pub fn is_operation_error(&self) -> bool {
        matches!(self, CarlaError::Operation(_))
    }

    /// Returns `true` if this is a map-related error.
    pub fn is_map_error(&self) -> bool {
        matches!(self, CarlaError::Map(_))
    }

    /// Returns `true` if this is a sensor-related error.
    pub fn is_sensor_error(&self) -> bool {
        matches!(self, CarlaError::Sensor(_))
    }

    /// Returns `true` if this is an internal error.
    pub fn is_internal_error(&self) -> bool {
        matches!(self, CarlaError::Internal(_))
    }

    /// Returns `true` if this error should be retried.
    ///
    /// This includes:
    /// - Timeout errors
    /// - Disconnection errors
    /// - Some spawn failures
    ///
    /// # Examples
    ///
    /// ```
    /// # use carla::{CarlaError, ConnectionError};
    /// # use std::time::Duration;
    /// let error: CarlaError = ConnectionError::Timeout {
    ///     operation: "spawn".to_string(),
    ///     duration: Duration::from_secs(5),
    ///     source: None,
    /// }
    /// .into();
    ///
    /// assert!(error.is_retriable());
    /// ```
    pub fn is_retriable(&self) -> bool {
        matches!(
            self,
            CarlaError::Connection(ConnectionError::Timeout { .. })
                | CarlaError::Connection(ConnectionError::Disconnected { .. })
                | CarlaError::Operation(OperationError::SpawnFailed { .. })
        )
    }
}

/// Extension trait for adding context to `Result` and `Option` types.
///
/// Provides `.context()` and `.with_context()` methods similar to `anyhow::Context`,
/// but producing [`CarlaError`] values.
///
/// # Examples
///
/// ```
/// use carla::error::{CarlaError, ResultExt};
///
/// let opt: Option<i32> = None;
/// let err = opt.context("value was missing").unwrap_err();
/// assert!(err.is_internal_error());
/// ```
pub trait ResultExt<T> {
    /// Add context to an error, wrapping it as an [`InternalError::UnexpectedState`].
    fn context(self, msg: &str) -> Result<T>;

    /// Add lazily-evaluated context to an error.
    fn with_context<F: FnOnce() -> String>(self, f: F) -> Result<T>;
}

impl<T> ResultExt<T> for Option<T> {
    fn context(self, msg: &str) -> Result<T> {
        self.ok_or_else(|| {
            InternalError::UnexpectedState {
                description: msg.to_string(),
            }
            .into()
        })
    }

    fn with_context<F: FnOnce() -> String>(self, f: F) -> Result<T> {
        self.ok_or_else(|| InternalError::UnexpectedState { description: f() }.into())
    }
}

impl<T, E> ResultExt<T> for std::result::Result<T, E>
where
    E: std::error::Error + Send + Sync + 'static,
{
    fn context(self, msg: &str) -> Result<T> {
        self.map_err(|e| {
            InternalError::FfiError {
                message: format!("{}: {}", msg, e),
                source: Some(Box::new(e)),
            }
            .into()
        })
    }

    fn with_context<F: FnOnce() -> String>(self, f: F) -> Result<T> {
        self.map_err(|e| {
            InternalError::FfiError {
                message: format!("{}: {}", f(), e),
                source: Some(Box::new(e)),
            }
            .into()
        })
    }
}

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

    #[test]
    fn test_connection_timeout_display() {
        let error = ConnectionError::Timeout {
            operation: "spawn_actor".to_string(),
            duration: Duration::from_secs(5),
            source: None,
        };
        assert_eq!(
            format!("{}", error),
            "Operation 'spawn_actor' timed out after 5s"
        );
    }

    #[test]
    fn test_resource_not_found_display() {
        let error = ResourceError::NotFound {
            resource_type: ResourceType::Blueprint,
            identifier: "vehicle.tesla.model3".to_string(),
            context: Some("BlueprintLibrary::find".to_string()),
        };
        assert_eq!(
            format!("{}", error),
            "Blueprint not found: vehicle.tesla.model3 (BlueprintLibrary::find)"
        );
    }

    #[test]
    fn test_error_classification() {
        let error: CarlaError = ResourceError::NotFound {
            resource_type: ResourceType::Blueprint,
            identifier: "test".to_string(),
            context: None,
        }
        .into();

        assert!(error.is_not_found());
        assert!(!error.is_timeout());
        assert!(!error.is_connection_error());
        assert!(!error.is_retriable());
    }

    #[test]
    fn test_timeout_is_retriable() {
        let error: CarlaError = ConnectionError::Timeout {
            operation: "spawn".to_string(),
            duration: Duration::from_secs(5),
            source: None,
        }
        .into();

        assert!(error.is_timeout());
        assert!(error.is_connection_error());
        assert!(error.is_retriable());
    }

    #[test]
    fn test_spawn_failed_is_retriable() {
        let error: CarlaError = OperationError::SpawnFailed {
            blueprint: "vehicle.tesla.model3".to_string(),
            transform: "(0, 0, 0)".to_string(),
            reason: "collision".to_string(),
            source: None,
        }
        .into();

        assert!(error.is_retriable());
        assert!(!error.is_connection_error());
    }

    #[test]
    fn test_resource_type_display() {
        assert_eq!(ResourceType::Actor.as_str(), "Actor");
        assert_eq!(ResourceType::Blueprint.as_str(), "Blueprint");
        assert_eq!(format!("{}", ResourceType::Map), "Map");
    }

    #[test]
    fn test_validation_error_display() {
        let error = ValidationError::OutOfBounds {
            field: "throttle".to_string(),
            value: "1.5".to_string(),
            min: "0.0".to_string(),
            max: "1.0".to_string(),
        };
        assert_eq!(
            format!("{}", error),
            "Value 1.5 out of bounds [0.0, 1.0] for field 'throttle'"
        );
    }

    #[test]
    fn test_io_error_conversion() {
        let io_error = std::io::Error::new(std::io::ErrorKind::NotFound, "file not found");
        let error: CarlaError = io_error.into();
        assert!(matches!(error, CarlaError::Io(_)));
    }

    #[test]
    fn test_is_validation_error() {
        let error: CarlaError = ValidationError::InvalidConfiguration {
            setting: "test".to_string(),
            reason: "bad".to_string(),
        }
        .into();
        assert!(error.is_validation_error());
        assert!(!error.is_operation_error());
    }

    #[test]
    fn test_is_operation_error() {
        let error: CarlaError = OperationError::SimulationError {
            message: "test".to_string(),
            source: None,
        }
        .into();
        assert!(error.is_operation_error());
        assert!(!error.is_validation_error());
    }

    #[test]
    fn test_is_map_error() {
        let error: CarlaError = MapError::TopologyError {
            message: "test".to_string(),
        }
        .into();
        assert!(error.is_map_error());
    }

    #[test]
    fn test_is_sensor_error() {
        let error: CarlaError = SensorError::DataUnavailable {
            sensor_id: 1,
            reason: "test".to_string(),
        }
        .into();
        assert!(error.is_sensor_error());
    }

    #[test]
    fn test_is_internal_error() {
        let error: CarlaError = InternalError::UnexpectedState {
            description: "test".to_string(),
        }
        .into();
        assert!(error.is_internal_error());
    }

    #[test]
    fn test_result_ext_option_context() {
        let opt: Option<i32> = None;
        let err = opt.context("missing value").unwrap_err();
        assert!(err.is_internal_error());
        assert!(format!("{}", err).contains("missing value"));
    }

    #[test]
    fn test_result_ext_option_some() {
        let opt: Option<i32> = Some(42);
        assert_eq!(opt.context("should not fail").unwrap(), 42);
    }

    #[test]
    fn test_result_ext_option_with_context() {
        let opt: Option<i32> = None;
        let err = opt
            .with_context(|| format!("value {} missing", 42))
            .unwrap_err();
        assert!(err.is_internal_error());
        assert!(format!("{}", err).contains("value 42 missing"));
    }

    #[test]
    fn test_result_ext_result_context() {
        let res: std::result::Result<i32, std::io::Error> = Err(std::io::Error::other("io fail"));
        let err = res.context("operation failed").unwrap_err();
        assert!(err.is_internal_error());
        assert!(format!("{}", err).contains("operation failed"));
    }

    #[test]
    fn test_result_ext_result_ok() {
        let res: std::result::Result<i32, std::io::Error> = Ok(42);
        assert_eq!(res.context("should not fail").unwrap(), 42);
    }
}