simbad_resolver/types.rs
1// This Source Code Form is subject to the terms of the Mozilla Public
2// License, v. 2.0. If a copy of the MPL was not distributed with this
3// file, You can obtain one at https://mozilla.org/MPL/2.0/.
4
5//! Resolved-identity types: [`ObjectType`], [`TargetSource`], [`AliasKind`],
6//! [`ResolvedAlias`], [`ResolvedIdentity`], [`PositionMatch`].
7
8use serde::{Deserialize, Serialize};
9
10// ── ObjectType ───────────────────────────────────────────────────────────────
11
12/// Closed object-type enum mapped from SIMBAD `otype`.
13///
14/// Serialized as `snake_case`. Any SIMBAD `otype` outside the closed set maps
15/// to [`ObjectType::Other`] (see [`map_otype`]); the raw string is preserved
16/// separately on [`ResolvedIdentity::otype_raw`] for consumers needing finer
17/// types.
18///
19/// ```
20/// use simbad_resolver::ObjectType;
21///
22/// assert_eq!(ObjectType::Galaxy.as_wire(), "galaxy");
23/// assert_eq!(ObjectType::from_wire("planetary_nebula"), ObjectType::PlanetaryNebula);
24/// assert_eq!(ObjectType::from_wire("bogus"), ObjectType::Other); // unknown → Other
25/// ```
26#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize, Deserialize)]
27#[serde(rename_all = "snake_case")]
28pub enum ObjectType {
29 /// A galaxy (incl. interacting/active galaxy subtypes).
30 Galaxy,
31 /// A planetary nebula.
32 PlanetaryNebula,
33 /// An emission nebula (H II region, emission object).
34 EmissionNebula,
35 /// A reflection nebula.
36 ReflectionNebula,
37 /// A dark/molecular cloud.
38 DarkNebula,
39 /// An open/galactic cluster.
40 OpenCluster,
41 /// A globular cluster.
42 GlobularCluster,
43 /// A supernova remnant.
44 SupernovaRemnant,
45 /// A cluster of galaxies.
46 GalaxyCluster,
47 /// A double/multiple star.
48 DoubleStar,
49 /// A visual asterism.
50 Asterism,
51 /// Any object type outside the closed set above.
52 Other,
53}
54
55impl ObjectType {
56 /// The `snake_case` wire/DB string for this object type.
57 ///
58 /// ```
59 /// use simbad_resolver::ObjectType;
60 ///
61 /// assert_eq!(ObjectType::GalaxyCluster.as_wire(), "galaxy_cluster");
62 /// ```
63 #[must_use]
64 pub fn as_wire(self) -> &'static str {
65 match self {
66 Self::Galaxy => "galaxy",
67 Self::PlanetaryNebula => "planetary_nebula",
68 Self::EmissionNebula => "emission_nebula",
69 Self::ReflectionNebula => "reflection_nebula",
70 Self::DarkNebula => "dark_nebula",
71 Self::OpenCluster => "open_cluster",
72 Self::GlobularCluster => "globular_cluster",
73 Self::SupernovaRemnant => "supernova_remnant",
74 Self::GalaxyCluster => "galaxy_cluster",
75 Self::DoubleStar => "double_star",
76 Self::Asterism => "asterism",
77 Self::Other => "other",
78 }
79 }
80
81 /// Parse a wire/DB string into an [`ObjectType`]. Unknown strings map to
82 /// [`ObjectType::Other`] (closed enum, forward-compatible read).
83 ///
84 /// ```
85 /// use simbad_resolver::ObjectType;
86 ///
87 /// assert_eq!(ObjectType::from_wire("globular_cluster"), ObjectType::GlobularCluster);
88 /// assert_eq!(ObjectType::from_wire("not-a-real-type"), ObjectType::Other);
89 /// ```
90 #[must_use]
91 pub fn from_wire(s: &str) -> Self {
92 match s {
93 "galaxy" => Self::Galaxy,
94 "planetary_nebula" => Self::PlanetaryNebula,
95 "emission_nebula" => Self::EmissionNebula,
96 "reflection_nebula" => Self::ReflectionNebula,
97 "dark_nebula" => Self::DarkNebula,
98 "open_cluster" => Self::OpenCluster,
99 "globular_cluster" => Self::GlobularCluster,
100 "supernova_remnant" => Self::SupernovaRemnant,
101 "galaxy_cluster" => Self::GalaxyCluster,
102 "double_star" => Self::DoubleStar,
103 "asterism" => Self::Asterism,
104 _ => Self::Other,
105 }
106 }
107}
108
109/// Map a raw SIMBAD `otype` string to the closed [`ObjectType`] enum.
110///
111/// SIMBAD `otype` values are short, case-sensitive condensed codes (e.g. `G`
112/// for galaxy, `PN` for planetary nebula, `HII` for an emission/H II region).
113/// The mapping is total: any unrecognised or unmapped `otype` (including the
114/// empty string) returns [`ObjectType::Other`] so an identity is never
115/// dropped for lack of a type.
116///
117/// The recognised codes follow the SIMBAD object-type vocabulary
118/// (<https://simbad.cds.unistra.fr/guide/otypes.htx>); the long-form labels
119/// SIMBAD also emits are accepted as aliases for robustness.
120///
121/// ```
122/// use simbad_resolver::{map_otype, ObjectType};
123///
124/// assert_eq!(map_otype("G"), ObjectType::Galaxy);
125/// assert_eq!(map_otype("HII"), ObjectType::EmissionNebula);
126/// assert_eq!(map_otype("*"), ObjectType::Other); // a plain star falls outside the closed set
127/// ```
128#[must_use]
129pub fn map_otype(otype: &str) -> ObjectType {
130 match otype.trim() {
131 // Galaxies (incl. interacting/active galaxy subtypes).
132 "G" | "GiC" | "GiG" | "GiP" | "IG" | "PaG" | "AGN" | "SBG" | "rG" | "LSB" | "AG?"
133 | "EmG" | "BiC" | "H2G" | "Sy1" | "Sy2" | "SyG" | "Galaxy" => ObjectType::Galaxy,
134 // Planetary nebulae.
135 "PN" | "PN?" | "pA*" | "PlanetaryNebula" => ObjectType::PlanetaryNebula,
136 // Emission nebulae (H II regions, emission objects).
137 "HII" | "EmO" | "ISM" | "RNe?" | "EmissionNebula" => ObjectType::EmissionNebula,
138 // Reflection nebulae.
139 "RNe" | "ReflectionNebula" => ObjectType::ReflectionNebula,
140 // Dark / molecular clouds.
141 "DNe" | "MoC" | "glb" | "cor" | "GNe" | "DarkNebula" => ObjectType::DarkNebula,
142 // Open / galactic clusters.
143 "OpC" | "Cl*" | "As*" | "OpenCluster" => ObjectType::OpenCluster,
144 // Globular clusters.
145 "GlC" | "GlobularCluster" => ObjectType::GlobularCluster,
146 // Supernova remnants.
147 "SNR" | "SNR?" | "SuperNovaRemnant" | "SupernovaRemnant" => ObjectType::SupernovaRemnant,
148 // Clusters of galaxies.
149 "ClG" | "GrG" | "CGG" | "SCG" | "GalaxyCluster" => ObjectType::GalaxyCluster,
150 // Double / multiple stars.
151 "**" | "**?" | "EB*" | "SB*" | "DoubleStar" => ObjectType::DoubleStar,
152 // Asterisms (note: SIMBAD uses `As*` for stellar associations; the
153 // visual-asterism sense is matched by the long-form label only).
154 "Asterism" => ObjectType::Asterism,
155 _ => ObjectType::Other,
156 }
157}
158
159// ── TargetSource ─────────────────────────────────────────────────────────────
160
161/// Provenance of a resolved identity.
162///
163/// The `UserOverride` variant serializes with the hyphenated `user-override`
164/// wire/DB value.
165///
166/// ```
167/// use simbad_resolver::TargetSource;
168///
169/// // A `user-override` row is sticky: nothing lower-precedence may overwrite it.
170/// assert!(TargetSource::UserOverride.may_overwrite(TargetSource::Resolved));
171/// assert!(!TargetSource::Resolved.may_overwrite(TargetSource::UserOverride));
172/// assert_eq!(TargetSource::UserOverride.as_wire(), "user-override");
173/// ```
174#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize, Deserialize)]
175#[serde(rename_all = "snake_case")]
176pub enum TargetSource {
177 /// Loaded from a bundled seed index at first run.
178 Seed,
179 /// Resolved live from SIMBAD.
180 Resolved,
181 /// A manual user correction; wins over `seed`/`resolved`.
182 #[serde(rename = "user-override")]
183 UserOverride,
184}
185
186impl TargetSource {
187 /// The wire/DB string for this source (`UserOverride` is the hyphenated
188 /// `user-override`).
189 ///
190 /// ```
191 /// use simbad_resolver::TargetSource;
192 ///
193 /// assert_eq!(TargetSource::UserOverride.as_wire(), "user-override");
194 /// assert_eq!(TargetSource::Seed.as_wire(), "seed");
195 /// ```
196 #[must_use]
197 pub fn as_wire(self) -> &'static str {
198 match self {
199 Self::Seed => "seed",
200 Self::Resolved => "resolved",
201 Self::UserOverride => "user-override",
202 }
203 }
204
205 /// Parse a wire/DB string into a [`TargetSource`]. Returns `None` for an
206 /// unrecognised value.
207 ///
208 /// ```
209 /// use simbad_resolver::TargetSource;
210 ///
211 /// assert_eq!(TargetSource::from_wire("user-override"), Some(TargetSource::UserOverride));
212 /// assert_eq!(TargetSource::from_wire("bogus"), None);
213 /// ```
214 #[must_use]
215 pub fn from_wire(s: &str) -> Option<Self> {
216 match s {
217 "seed" => Some(Self::Seed),
218 "resolved" => Some(Self::Resolved),
219 "user-override" => Some(Self::UserOverride),
220 _ => None,
221 }
222 }
223
224 /// Source precedence rank for conflicting writes: higher wins.
225 /// `user-override` (2) > `resolved` (1) > `seed` (0).
226 ///
227 /// ```
228 /// use simbad_resolver::TargetSource;
229 ///
230 /// assert!(TargetSource::UserOverride.precedence() > TargetSource::Resolved.precedence());
231 /// assert!(TargetSource::Resolved.precedence() > TargetSource::Seed.precedence());
232 /// ```
233 #[must_use]
234 pub fn precedence(self) -> u8 {
235 match self {
236 Self::Seed => 0,
237 Self::Resolved => 1,
238 Self::UserOverride => 2,
239 }
240 }
241
242 /// Whether a write with `self` as the incoming source may overwrite an
243 /// existing row whose source is `existing`.
244 ///
245 /// A `user-override` row is sticky: a later `resolved`/`seed` result MUST
246 /// NOT overwrite it. An equal-or-higher-precedence incoming source wins
247 /// (re-resolving refreshes a `resolved` row; an override always wins).
248 ///
249 /// This is what [`crate::Cache::upsert`] implementations must honour.
250 ///
251 /// ```
252 /// use simbad_resolver::TargetSource;
253 ///
254 /// assert!(TargetSource::Resolved.may_overwrite(TargetSource::Seed));
255 /// assert!(!TargetSource::Seed.may_overwrite(TargetSource::UserOverride));
256 /// ```
257 #[must_use]
258 pub fn may_overwrite(self, existing: Self) -> bool {
259 self.precedence() >= existing.precedence()
260 }
261}
262
263// ── AliasKind / ResolvedAlias ─────────────────────────────────────────────────
264
265/// The kind of an alias attached to a resolved identity.
266///
267/// ```
268/// use simbad_resolver::AliasKind;
269///
270/// assert_eq!(AliasKind::CommonName.as_wire(), "common_name");
271/// assert_eq!(AliasKind::from_wire("user"), AliasKind::User);
272/// assert_eq!(AliasKind::from_wire("bogus"), AliasKind::Designation); // unrecognised → Designation
273/// ```
274#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize, Deserialize)]
275#[serde(rename_all = "snake_case")]
276pub enum AliasKind {
277 /// A catalog designation (e.g. `M 31`, `NGC 224`).
278 Designation,
279 /// A SIMBAD `NAME …` curated common name (e.g. `Andromeda Galaxy`).
280 CommonName,
281 /// A user-added alias.
282 User,
283}
284
285impl AliasKind {
286 /// The wire/DB string (matches the `target_alias.kind` CHECK constraint).
287 ///
288 /// ```
289 /// use simbad_resolver::AliasKind;
290 ///
291 /// assert_eq!(AliasKind::Designation.as_wire(), "designation");
292 /// ```
293 #[must_use]
294 pub fn as_wire(self) -> &'static str {
295 match self {
296 Self::Designation => "designation",
297 Self::CommonName => "common_name",
298 Self::User => "user",
299 }
300 }
301
302 /// Parse a wire/DB string into an [`AliasKind`]; unknown → `Designation`.
303 ///
304 /// ```
305 /// use simbad_resolver::AliasKind;
306 ///
307 /// assert_eq!(AliasKind::from_wire("common_name"), AliasKind::CommonName);
308 /// ```
309 #[must_use]
310 pub fn from_wire(s: &str) -> Self {
311 match s {
312 "common_name" => Self::CommonName,
313 "user" => Self::User,
314 _ => Self::Designation,
315 }
316 }
317}
318
319/// One alternate designation/name for a resolved identity. The `normalized`
320/// form is the typeahead match surface.
321#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
322pub struct ResolvedAlias {
323 /// Verbatim designation or common name (e.g. `M 31`, `Andromeda Galaxy`).
324 pub alias: String,
325 /// Normalized form for matching ([`crate::normalize::normalize`]).
326 pub normalized: String,
327 /// Whether this alias is a designation or a curated common name.
328 pub kind: AliasKind,
329}
330
331impl ResolvedAlias {
332 /// Build a [`ResolvedAlias`], computing the normalized form from `alias`.
333 ///
334 /// ```
335 /// use simbad_resolver::{AliasKind, ResolvedAlias};
336 ///
337 /// let alias = ResolvedAlias::new("M31", AliasKind::Designation);
338 /// assert_eq!(alias.alias, "M31");
339 /// assert_eq!(alias.normalized, "m 31");
340 /// ```
341 #[must_use]
342 pub fn new(alias: impl Into<String>, kind: AliasKind) -> Self {
343 let alias = alias.into();
344 let normalized = crate::normalize::normalize(&alias);
345 Self { alias, normalized, kind }
346 }
347}
348
349// ── ResolvedIdentity / PositionMatch ──────────────────────────────────────────
350
351/// A fully resolved canonical target identity returned by a [`crate::Resolver`].
352///
353/// Coordinates are ICRS J2000 decimal degrees, sourced from the resolver
354/// backend: a resolver that cannot determine a position returns
355/// [`crate::ResolveError::NotFound`] rather than a placeholder value.
356///
357/// ```
358/// use simbad_resolver::{AliasKind, ObjectType, ResolvedAlias, ResolvedIdentity, TargetSource};
359///
360/// let m31 = ResolvedIdentity {
361/// simbad_oid: Some(1_575_544),
362/// primary_designation: "M 31".to_owned(),
363/// common_name: Some("Andromeda Galaxy".to_owned()),
364/// object_type: ObjectType::Galaxy,
365/// otype_raw: "G".to_owned(),
366/// ra_deg: 10.684_708,
367/// dec_deg: 41.268_75,
368/// v_mag: Some(3.44),
369/// aliases: vec![ResolvedAlias::new("M 31", AliasKind::Designation)],
370/// source: TargetSource::Resolved,
371/// };
372///
373/// // The typed accessor shares one coordinate representation with `skymath`
374/// // consumers; `ra_deg`/`dec_deg` remain the source of truth.
375/// let eq = m31.position().expect("valid ICRS coordinates");
376/// assert!((eq.ra().degrees() - 10.684_708).abs() < 1e-6);
377/// ```
378#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
379pub struct ResolvedIdentity {
380 /// SIMBAD physical-object id (the dedup key) when resolved online; `None`
381 /// for seed/override-only entries until enriched.
382 pub simbad_oid: Option<i64>,
383 /// Canonical display designation.
384 pub primary_designation: String,
385 /// Curated common name (SIMBAD `NAME …`) when one exists.
386 pub common_name: Option<String>,
387 /// Closed object-type enum from the SIMBAD `otype` mapping ([`map_otype`]).
388 pub object_type: ObjectType,
389 /// Raw SIMBAD `otype` string, preserved alongside the mapped
390 /// [`Self::object_type`] for consumers needing finer-grained types.
391 pub otype_raw: String,
392 /// ICRS J2000 right ascension in decimal degrees, `[0, 360)`.
393 pub ra_deg: f64,
394 /// ICRS J2000 declination in decimal degrees, `[-90, 90]`.
395 pub dec_deg: f64,
396 /// Johnson V-band apparent magnitude (SIMBAD `allfluxes.V`) when the object
397 /// has V photometry; `None` otherwise. Many extended/dark objects and
398 /// seed/override-only entries have no V magnitude.
399 pub v_mag: Option<f64>,
400 /// All designations + common names for this object (the typeahead surface).
401 pub aliases: Vec<ResolvedAlias>,
402 /// Provenance of this identity.
403 pub source: TargetSource,
404}
405
406impl ResolvedIdentity {
407 /// This target's sky position as a typed `skymath::Equatorial` coordinate.
408 ///
409 /// SIMBAD TAP `basic.ra`/`basic.dec` are ICRS; at planning grade
410 /// (≤ ~1 arcminute) ICRS is treated as J2000 — this encodes that equivalence
411 /// once so consumers don't re-derive it. The raw [`Self::ra_deg`] /
412 /// [`Self::dec_deg`] fields remain the canonical storage.
413 ///
414 /// # Errors
415 ///
416 /// `skymath::Error::OutOfRange` if the stored values are outside RA
417 /// `[0, 360)` / Dec `[-90, +90]` (malformed cache content).
418 ///
419 /// See the [struct-level example](Self) for a full identity literal; this
420 /// one only shows the accessor:
421 ///
422 /// ```
423 /// # use simbad_resolver::{AliasKind, ObjectType, ResolvedAlias, ResolvedIdentity, TargetSource};
424 /// # let m31 = ResolvedIdentity {
425 /// # simbad_oid: Some(1_575_544), primary_designation: "M 31".to_owned(),
426 /// # common_name: None, object_type: ObjectType::Galaxy, otype_raw: "G".to_owned(),
427 /// # ra_deg: 10.684_708, dec_deg: 41.268_75, v_mag: Some(3.44),
428 /// # aliases: vec![ResolvedAlias::new("M 31", AliasKind::Designation)],
429 /// # source: TargetSource::Resolved,
430 /// # };
431 /// let eq = m31.position()?;
432 /// assert!((eq.ra().degrees() - 10.684_708).abs() < 1e-6);
433 /// # Ok::<(), skymath::Error>(())
434 /// ```
435 pub fn position(&self) -> skymath::Result<skymath::Equatorial> {
436 skymath::Equatorial::j2000(
437 skymath::Angle::from_degrees(self.ra_deg),
438 skymath::Angle::from_degrees(self.dec_deg),
439 )
440 }
441}
442
443/// One result of a position (cone-search) resolution.
444#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
445pub struct PositionMatch {
446 /// The matched identity.
447 pub identity: ResolvedIdentity,
448 /// Angular separation from the query position, in degrees.
449 pub separation_deg: f64,
450}
451
452impl PositionMatch {
453 /// This match's sky position as a typed `skymath::Equatorial` coordinate.
454 ///
455 /// Delegates to [`ResolvedIdentity::position`] on [`Self::identity`].
456 ///
457 /// # Errors
458 ///
459 /// `skymath::Error::OutOfRange` if the identity's stored coordinates are out
460 /// of range.
461 ///
462 /// ```
463 /// use simbad_resolver::{AliasKind, ObjectType, PositionMatch, ResolvedAlias, ResolvedIdentity, TargetSource};
464 ///
465 /// # fn run() -> Result<(), skymath::Error> {
466 /// let identity = ResolvedIdentity {
467 /// simbad_oid: Some(1_575_544), primary_designation: "M 31".to_owned(),
468 /// common_name: None, object_type: ObjectType::Galaxy, otype_raw: "G".to_owned(),
469 /// ra_deg: 10.684_708, dec_deg: 41.268_75, v_mag: Some(3.44),
470 /// aliases: vec![ResolvedAlias::new("M 31", AliasKind::Designation)],
471 /// source: TargetSource::Resolved,
472 /// };
473 /// let m = PositionMatch { identity, separation_deg: 0.001 };
474 /// let eq = m.position()?;
475 /// assert!((eq.dec().degrees() - 41.268_75).abs() < 1e-6);
476 /// # Ok(()) }
477 /// ```
478 pub fn position(&self) -> skymath::Result<skymath::Equatorial> {
479 self.identity.position()
480 }
481}
482
483#[cfg(test)]
484mod tests {
485 use super::*;
486
487 // ── map_otype ──────────────────────────────────────────────────────────
488
489 #[test]
490 fn map_otype_maps_known_codes() {
491 assert_eq!(map_otype("G"), ObjectType::Galaxy);
492 assert_eq!(map_otype("PN"), ObjectType::PlanetaryNebula);
493 assert_eq!(map_otype("HII"), ObjectType::EmissionNebula);
494 assert_eq!(map_otype("RNe"), ObjectType::ReflectionNebula);
495 assert_eq!(map_otype("DNe"), ObjectType::DarkNebula);
496 assert_eq!(map_otype("OpC"), ObjectType::OpenCluster);
497 assert_eq!(map_otype("GlC"), ObjectType::GlobularCluster);
498 assert_eq!(map_otype("SNR"), ObjectType::SupernovaRemnant);
499 assert_eq!(map_otype("ClG"), ObjectType::GalaxyCluster);
500 assert_eq!(map_otype("**"), ObjectType::DoubleStar);
501 assert_eq!(map_otype("Asterism"), ObjectType::Asterism);
502 }
503
504 #[test]
505 fn map_otype_covers_full_otype_vocabulary() {
506 use ObjectType as OT;
507 // Every recognised code + long-form label in the mapping table.
508 let cases: &[(&str, ObjectType)] = &[
509 ("G", OT::Galaxy),
510 ("GiC", OT::Galaxy),
511 ("GiG", OT::Galaxy),
512 ("GiP", OT::Galaxy),
513 ("IG", OT::Galaxy),
514 ("PaG", OT::Galaxy),
515 ("AGN", OT::Galaxy),
516 ("SBG", OT::Galaxy),
517 ("rG", OT::Galaxy),
518 ("LSB", OT::Galaxy),
519 ("AG?", OT::Galaxy),
520 ("EmG", OT::Galaxy),
521 ("BiC", OT::Galaxy),
522 ("H2G", OT::Galaxy),
523 ("Sy1", OT::Galaxy),
524 ("Sy2", OT::Galaxy),
525 ("SyG", OT::Galaxy),
526 ("Galaxy", OT::Galaxy),
527 ("PN", OT::PlanetaryNebula),
528 ("PN?", OT::PlanetaryNebula),
529 ("pA*", OT::PlanetaryNebula),
530 ("PlanetaryNebula", OT::PlanetaryNebula),
531 ("HII", OT::EmissionNebula),
532 ("EmO", OT::EmissionNebula),
533 ("ISM", OT::EmissionNebula),
534 ("RNe?", OT::EmissionNebula),
535 ("EmissionNebula", OT::EmissionNebula),
536 ("RNe", OT::ReflectionNebula),
537 ("ReflectionNebula", OT::ReflectionNebula),
538 ("DNe", OT::DarkNebula),
539 ("MoC", OT::DarkNebula),
540 ("glb", OT::DarkNebula),
541 ("cor", OT::DarkNebula),
542 ("GNe", OT::DarkNebula),
543 ("DarkNebula", OT::DarkNebula),
544 ("OpC", OT::OpenCluster),
545 ("Cl*", OT::OpenCluster),
546 // `As*` is SIMBAD's stellar-association code, intentionally bucketed
547 // as an open cluster (not the visual-asterism sense).
548 ("As*", OT::OpenCluster),
549 ("OpenCluster", OT::OpenCluster),
550 ("GlC", OT::GlobularCluster),
551 ("GlobularCluster", OT::GlobularCluster),
552 ("SNR", OT::SupernovaRemnant),
553 ("SNR?", OT::SupernovaRemnant),
554 ("SuperNovaRemnant", OT::SupernovaRemnant),
555 ("SupernovaRemnant", OT::SupernovaRemnant),
556 ("ClG", OT::GalaxyCluster),
557 ("GrG", OT::GalaxyCluster),
558 ("CGG", OT::GalaxyCluster),
559 ("SCG", OT::GalaxyCluster),
560 ("GalaxyCluster", OT::GalaxyCluster),
561 ("**", OT::DoubleStar),
562 ("**?", OT::DoubleStar),
563 ("EB*", OT::DoubleStar),
564 ("SB*", OT::DoubleStar),
565 ("DoubleStar", OT::DoubleStar),
566 // Only the long-form label maps to the visual-asterism bucket.
567 ("Asterism", OT::Asterism),
568 ];
569 for (code, want) in cases {
570 assert_eq!(map_otype(code), *want, "otype code {code:?} should map to {want:?}");
571 }
572 }
573
574 #[test]
575 fn map_otype_unknown_is_other() {
576 assert_eq!(map_otype("ZZZ"), ObjectType::Other);
577 assert_eq!(map_otype(""), ObjectType::Other);
578 assert_eq!(map_otype("Star"), ObjectType::Other);
579 }
580
581 #[test]
582 fn map_otype_trims_whitespace() {
583 assert_eq!(map_otype(" G "), ObjectType::Galaxy);
584 }
585
586 #[test]
587 fn object_type_serializes_snake_case() {
588 assert_eq!(
589 serde_json::to_string(&ObjectType::PlanetaryNebula).unwrap(),
590 "\"planetary_nebula\""
591 );
592 assert_eq!(
593 serde_json::to_string(&ObjectType::GalaxyCluster).unwrap(),
594 "\"galaxy_cluster\""
595 );
596 assert_eq!(serde_json::to_string(&ObjectType::Other).unwrap(), "\"other\"");
597 }
598
599 #[test]
600 fn object_type_wire_round_trips() {
601 for ot in [
602 ObjectType::Galaxy,
603 ObjectType::PlanetaryNebula,
604 ObjectType::EmissionNebula,
605 ObjectType::ReflectionNebula,
606 ObjectType::DarkNebula,
607 ObjectType::OpenCluster,
608 ObjectType::GlobularCluster,
609 ObjectType::SupernovaRemnant,
610 ObjectType::GalaxyCluster,
611 ObjectType::DoubleStar,
612 ObjectType::Asterism,
613 ObjectType::Other,
614 ] {
615 assert_eq!(ObjectType::from_wire(ot.as_wire()), ot);
616 }
617 assert_eq!(ObjectType::from_wire("bogus"), ObjectType::Other);
618 }
619
620 // ── TargetSource ─────────────────────────────────────────────────────────
621
622 #[test]
623 fn target_source_user_override_is_hyphenated() {
624 assert_eq!(
625 serde_json::to_string(&TargetSource::UserOverride).unwrap(),
626 "\"user-override\""
627 );
628 assert_eq!(serde_json::to_string(&TargetSource::Seed).unwrap(), "\"seed\"");
629 assert_eq!(serde_json::to_string(&TargetSource::Resolved).unwrap(), "\"resolved\"");
630 assert_eq!(
631 serde_json::from_str::<TargetSource>("\"user-override\"").unwrap(),
632 TargetSource::UserOverride
633 );
634 }
635
636 #[test]
637 fn target_source_wire_round_trips() {
638 for src in [TargetSource::Seed, TargetSource::Resolved, TargetSource::UserOverride] {
639 assert_eq!(TargetSource::from_wire(src.as_wire()), Some(src));
640 }
641 assert_eq!(TargetSource::from_wire("bogus"), None);
642 }
643
644 #[test]
645 fn target_source_precedence_and_overwrite() {
646 assert!(TargetSource::Seed.precedence() < TargetSource::Resolved.precedence());
647 assert!(TargetSource::Resolved.precedence() < TargetSource::UserOverride.precedence());
648
649 // Equal-or-higher precedence may overwrite.
650 assert!(TargetSource::Resolved.may_overwrite(TargetSource::Seed));
651 assert!(TargetSource::Resolved.may_overwrite(TargetSource::Resolved));
652 assert!(TargetSource::UserOverride.may_overwrite(TargetSource::Resolved));
653
654 // A user-override row is sticky: lower-precedence incoming sources
655 // must not overwrite it.
656 assert!(!TargetSource::Seed.may_overwrite(TargetSource::UserOverride));
657 assert!(!TargetSource::Resolved.may_overwrite(TargetSource::UserOverride));
658 }
659
660 // ── AliasKind / ResolvedAlias ──────────────────────────────────────────
661
662 #[test]
663 fn alias_kind_wire_round_trips() {
664 for kind in [AliasKind::Designation, AliasKind::CommonName, AliasKind::User] {
665 assert_eq!(AliasKind::from_wire(kind.as_wire()), kind);
666 }
667 assert_eq!(AliasKind::from_wire("bogus"), AliasKind::Designation);
668 }
669
670 #[test]
671 fn resolved_alias_computes_normalized_form() {
672 let alias = ResolvedAlias::new("M31", AliasKind::Designation);
673 assert_eq!(alias.alias, "M31");
674 assert_eq!(alias.normalized, "m 31");
675 }
676}