raceline_optimizer/
lib.rs1#![allow(
2 clippy::explicit_auto_deref,
3 clippy::needless_range_loop,
4 clippy::too_many_arguments
5)]
6
7pub mod bike_dynamics_v1;
8pub mod bike_mintime;
9pub mod bike_mintime_v1;
10pub mod car_mintime;
11pub mod contracts;
12pub mod csv;
13pub mod dense_frenet;
14pub mod ipopt;
15pub mod json;
16pub mod mintime;
17pub mod mintime_common;
18pub mod models;
19pub mod point_mass;
20pub mod progress_contract;
21pub mod section_frame;
22mod section_geometry;
23pub mod solver_api;
24pub mod station;
25pub mod station_generation;
26pub mod trajectory_quality;
27pub mod vehicle_dynamics;
28
29use std::fs;
30use std::io;
31use std::path::Path;
32
33use json::{parse_json_str, JsonError, JsonValue};
34
35pub type JsonObject = Vec<(String, JsonValue)>;
36
37pub trait ToJsonValue {
38 fn to_json_value(&self) -> JsonValue;
39}
40
41pub fn read_json_value(path: impl AsRef<Path>) -> Result<JsonValue, ContractIoError> {
42 let path = path.as_ref();
43 let body = fs::read_to_string(path)?;
44 parse_json_str(&body).map_err(|source| ContractIoError::JsonRead {
45 path: path.to_path_buf(),
46 source,
47 })
48}
49
50pub fn write_pretty_json_file<T: ToJsonValue>(
51 path: impl AsRef<Path>,
52 value: &T,
53) -> Result<(), ContractIoError> {
54 write_json_value(path, &value.to_json_value())
55}
56
57pub fn write_json_value(path: impl AsRef<Path>, value: &JsonValue) -> Result<(), ContractIoError> {
58 let path = path.as_ref();
59 if let Some(parent) = path.parent() {
60 fs::create_dir_all(parent)?;
61 }
62 let mut body = value.to_pretty_string();
63 body.push('\n');
64 fs::write(path, body)?;
65 Ok(())
66}
67
68#[derive(Debug)]
69pub enum ContractIoError {
70 Io(io::Error),
71 JsonRead {
72 path: std::path::PathBuf,
73 source: JsonError,
74 },
75 InvalidContract {
76 path: std::path::PathBuf,
77 message: String,
78 },
79}
80
81impl std::fmt::Display for ContractIoError {
82 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
83 match self {
84 Self::Io(error) => write!(formatter, "I/O error: {error}"),
85 Self::JsonRead { path, source } => {
86 write!(
87 formatter,
88 "failed to parse JSON {}: {source}",
89 path.display()
90 )
91 }
92 Self::InvalidContract { path, message } => {
93 write!(formatter, "invalid contract {}: {message}", path.display())
94 }
95 }
96 }
97}
98
99impl std::error::Error for ContractIoError {}
100
101impl From<io::Error> for ContractIoError {
102 fn from(value: io::Error) -> Self {
103 Self::Io(value)
104 }
105}