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
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! # CURIEs: Compact URIs
//!
//! CURIEs, [defined by the W3C], are a compact way of representing a URI.
//! A CURIE consists of an optional prefix and a reference, separated by
//! a colon.
//!
//! They are commonly used in JSON-LD, RDF, SPARQL, XML namespaces and other
//! applications.
//!
//! Example CURIEs:
//!
//! * `"foaf:Person"` -- Results in a URI in the namespace represented by
//! the `"foaf"` prefix.
//! * `":Person"` -- Results in a URI in the namespace represented by
//! the `""` prefix.
//! * `"Person"` -- Results in a URI in the default namespace.
//!
//! The last example relies upon there being a default mapping providing
//! a default base URI, while the example before it relies upon there
//! being a prefix which is an empty string.
//!
//! See the [specification] for further details.
//!
//! ## Compact URIs in the Real World
//!
//! In SPARQL (from Wikipedia):
//!
//! ```sparql
//! PREFIX foaf: <http://xmlns.com/foaf/0.1/>
//! SELECT ?name
//! ?email
//! WHERE
//! {
//! ?person a foaf:Person .
//! ?person foaf:name ?name .
//! ?person foaf:mbox ?email .
//! }
//! ```
//!
//! In the Turtle serialization for RDF (from the specification):
//!
//! ```turtle
//! @base <http://example.org/> .
//! @prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .
//! @prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .
//! @prefix foaf: <http://xmlns.com/foaf/0.1/> .
//! @prefix rel: <http://www.perceive.net/schemas/relationship/> .
//!
//! <#green-goblin>
//! rel:enemyOf <#spiderman> ;
//! a foaf:Person ; # in the context of the Marvel universe
//! foaf:name "Green Goblin" .
//!
//! <#spiderman>
//! rel:enemyOf <#green-goblin> ;
//! a foaf:Person ;
//! foaf:name "Spiderman", "Человек-паук"@ru .
//! ```
//!
//! ## Usage
//!
//! ```
//! use curie::PrefixMapping;
//!
//! // Initialize a prefix mapper.
//! let mut mapper = PrefixMapping::default();
//! mapper.add_prefix("foaf", "http://xmlns.com/foaf/0.1/").unwrap();
//!
//! // Set a default prefix
//! mapper.set_default("http://example.com/");
//!
//! // Expand a CURIE and get back the full URI.
//! assert_eq!(mapper.expand_curie_string("Entity"),
//! Ok(String::from("http://example.com/Entity")));
//! assert_eq!(mapper.expand_curie_string("foaf:Agent"),
//! Ok(String::from("http://xmlns.com/foaf/0.1/Agent")));
//! ```
//!
//! When parsing a file, it is likely that the distinction between
//! the prefix and the reference portions of the CURIE will be clear,
//! so to save time during expansion, the [`Curie`] struct can also be
//! used:
//!
//! ```
//! use curie::{Curie, PrefixMapping};
//!
//! // Initialize a prefix mapper.
//! let mut mapper = PrefixMapping::default();
//! mapper.add_prefix("foaf", "http://xmlns.com/foaf/0.1/").unwrap();
//!
//! let curie = Curie::new(Some("foaf"), "Agent");
//!
//! assert_eq!(mapper.expand_curie(&curie),
//! Ok(String::from("http://xmlns.com/foaf/0.1/Agent")));
//! ```
//!
//! Given an IRI is also possible to derive an CURIE.
//!
//! ```
//! use curie::{Curie, PrefixMapping};
//!
//! // Initialize a prefix mapper.
//! let mut mapper = PrefixMapping::default();
//! mapper.add_prefix("foaf", "http://xmlns.com/foaf/0.1/").unwrap();
//!
//! let curie = Curie::new(Some("foaf"), "Agent");
//!
//! assert_eq!(Ok(curie),
//! mapper.shrink_iri("http://xmlns.com/foaf/0.1/Agent"));
//! ```
//!
//! [defined by the W3C]: https://www.w3.org/TR/curie/
//! [specification]: https://www.w3.org/TR/curie/
#![warn(missing_docs)]
#![deny(
trivial_numeric_casts,
unsafe_code,
unstable_features,
unused_import_braces,
unused_qualifications
)]
use std::fmt;
/// Errors that might occur when adding a prefix to a [`PrefixMapping`].
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum InvalidPrefixError {
/// This is a reserved prefix.
///
/// The prefix `"_"` is reserved.
ReservedPrefix,
}
/// Errors that might occur during CURIE expansion.
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum ExpansionError {
/// The prefix on the CURIE has no valid mapping.
Invalid,
/// The CURIE uses a default prefix, but one has not
/// been set.
MissingDefault,
}
/// Maps prefixes to base URIs and allows for the expansion of
/// CURIEs (Compact URIs).
///
/// # Examples
///
/// ```
/// use curie::PrefixMapping;
///
/// // Create using the `Default` trait:
/// let mut mapping = PrefixMapping::default();
/// ```
#[derive(Debug, Default, PartialEq)]
pub struct PrefixMapping {
default: Option<String>,
mapping: indexmap::IndexMap<String, String>,
}
impl PrefixMapping {
/// Set a default prefix.
///
/// This is used during CURIE expansion when there is no
/// prefix, just a reference value.
///
/// # Example:
///
/// ```
/// use curie::{ExpansionError, PrefixMapping};
///
/// let mut mapping = PrefixMapping::default();
///
/// // No default has been configured, so an error will be
/// // signaled.
/// assert_eq!(mapping.expand_curie_string("Entity"),
/// Err(ExpansionError::MissingDefault));
///
/// mapping.set_default("http://example.com/");
///
/// assert_eq!(mapping.expand_curie_string("Entity"),
/// Ok(String::from("http://example.com/Entity")));
/// ```
///
/// # See also
///
/// * [`PrefixMapping::add_prefix()`]
pub fn set_default(&mut self, default: &str) {
self.default = Some(String::from(default));
}
/// Add a prefix to the mapping.
///
/// This allows this prefix to be resolved when a CURIE is expanded.
///
/// # Errors
///
/// Returns [`InvalidPrefixError`] when the `prefix` is invalid. Typically, this is
/// when `prefix` is `_`, which is a reserved prefix.
///
/// # See also
///
/// * [`PrefixMapping::remove_prefix()`]
/// * [`PrefixMapping::set_default()`]
pub fn add_prefix(&mut self, prefix: &str, value: &str) -> Result<(), InvalidPrefixError> {
if prefix == "_" {
Err(InvalidPrefixError::ReservedPrefix)
} else {
self.mapping
.insert(String::from(prefix), String::from(value));
Ok(())
}
}
/// Remove a prefix from the mapping.
///
/// Future calls to [`PrefixMapping::expand_curie_string()`] or [`PrefixMapping::expand_curie()`]
/// that use this `prefix` will result in a [`ExpansionError::Invalid`] error.
///
/// # See also
///
/// * [`PrefixMapping::add_prefix()`]
pub fn remove_prefix(&mut self, prefix: &str) {
self.mapping.remove(prefix);
}
/// Expand a CURIE, returning a complete IRI.
///
/// # Errors
///
/// This will return [`ExpansionError`] if the expansion fails.
///
/// # See also
///
/// * [`PrefixMapping::expand_curie()`]
pub fn expand_curie_string(&self, curie_str: &str) -> Result<String, ExpansionError> {
if let Some(separator_idx) = curie_str.chars().position(|c| c == ':') {
// If we have a separator, try to expand.
let prefix = Some(&curie_str[..separator_idx]);
let reference = &curie_str[separator_idx + 1..];
let curie = Curie::new(prefix, reference);
self.expand_curie(&curie)
} else {
let curie = Curie::new(None, curie_str);
self.expand_curie(&curie)
}
}
/// Expand a parsed [`Curie`], returning a complete IRI.
///
/// # Errors
///
/// This will return [`ExpansionError`] if the expansion fails.
///
/// # See also
///
/// * [`PrefixMapping::expand_curie_string()`]
pub fn expand_curie(&self, curie: &Curie) -> Result<String, ExpansionError> {
self.expand_exploded_curie(curie.prefix, curie.reference)
}
fn expand_exploded_curie(
&self,
prefix: Option<&str>,
reference: &str,
) -> Result<String, ExpansionError> {
if let Some(prefix) = prefix {
if let Some(mapped_prefix) = self.mapping.get(prefix) {
Ok((*mapped_prefix).clone() + reference)
} else {
Err(ExpansionError::Invalid)
}
} else if let Some(ref default) = self.default {
Ok((default).clone() + reference)
} else {
Err(ExpansionError::MissingDefault)
}
}
/// Shrink an IRI, returning a [`Curie`].
///
/// If several base IRIs match the expanded IRI passed as argument, the
/// one that was inserted first is used, even though another base IRI is
/// a better match:
///
/// ```rust
/// use curie::{PrefixMapping, Curie};
///
/// let mut mapping = PrefixMapping::default();
/// mapping.add_prefix("eg", "http://example.com/").unwrap();
/// mapping.add_prefix("egdoc", "http://example.com/document/").unwrap();
///
/// assert_eq!(mapping.shrink_iri("http://example.com/document/thing"),
/// Ok(Curie::new(Some("eg"), "document/thing")));
/// ```
///
/// # Errors
///
/// An error is returned if there is no valid mapping (default or otherwise)
/// that would allow the IRI to be shortened.
pub fn shrink_iri<'a>(&'a self, iri: &'a str) -> Result<Curie<'a>, &'static str> {
if let Some(ref def) = self.default {
if iri.starts_with(def) {
return Ok(Curie::new(None, iri.trim_start_matches(def)));
}
}
for mp in &self.mapping {
if iri.starts_with(mp.1) {
return Ok(Curie::new(Some(mp.0), iri.trim_start_matches(mp.1)));
}
}
Err("Unable to shorten")
}
/// Return an iterator over the prefix mappings.
///
/// The iterator yields IRI mappings in the same order they were inserted.
/// This is useful when testing code that uses this crate.
#[must_use]
pub fn mappings(&self) -> indexmap::map::Iter<String, String> {
self.mapping.iter()
}
}
/// A prefix and reference, already parsed into separate components.
///
/// When parsing a document, the components of the compact URI will already
/// have been parsed and we can avoid storing a string of the full compact
/// URI and having to do that work again when expanding the compact URI.
///
/// The `'c` lifetime parameter will typically be the lifetime of the body
/// of text which is being parsed and contains the compact URIs.
///
/// # Usage:
///
/// ## Creation:
///
/// ```
/// # use curie::Curie;
/// let c = Curie::new(Some("foaf"), "Person");
/// ```
///
/// ## Expansion:
///
/// Expanding a `Curie` requires the use of a properly initialized
/// [`PrefixMapping`].
///
/// ```
/// # use curie::{Curie, PrefixMapping};
/// // Initialize a prefix mapper.
/// let mut mapper = PrefixMapping::default();
/// mapper.add_prefix("foaf", "http://xmlns.com/foaf/0.1/").unwrap();
///
/// let curie = Curie::new(Some("foaf"), "Agent");
///
/// assert_eq!(mapper.expand_curie(&curie),
/// Ok(String::from("http://xmlns.com/foaf/0.1/Agent")));
/// ```
///
/// ## Display / Formatting:
///
/// `Curie` implements the `Debug` and `Display` traits, so it integrates with
/// the Rust standard library facilities.
///
/// ```
/// # use curie::Curie;
/// let curie = Curie::new(Some("foaf"), "Agent");
/// assert_eq!("foaf:Agent", format!("{}", curie));
/// ```
#[derive(Debug, Eq, PartialEq)]
pub struct Curie<'c> {
prefix: Option<&'c str>,
reference: &'c str,
}
impl<'c> Curie<'c> {
/// Construct a `Curie` from a prefix and reference.
#[must_use]
pub fn new(prefix: Option<&'c str>, reference: &'c str) -> Self {
Curie { prefix, reference }
}
}
impl<'c> From<&'c Curie<'c>> for String {
fn from(c: &'c Curie<'c>) -> String {
format!("{c}")
}
}
impl<'c> From<Curie<'c>> for String {
fn from(c: Curie<'c>) -> String {
format!("{c}")
}
}
impl<'c> fmt::Display for Curie<'c> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self.prefix {
Some(prefix) => write!(f, "{}:{}", prefix, self.reference),
None => write!(f, "{}", self.reference),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
const FOAF_VOCAB: &str = "http://xmlns.com/foaf/0.1/";
#[test]
fn add_remove_works() {
let mut pm = PrefixMapping::default();
// No keys should be found.
assert_eq!(pm.mapping.get("foaf"), None);
// Add and look up a key.
assert_eq!(pm.add_prefix("foaf", FOAF_VOCAB), Ok(()));
assert_eq!(pm.mapping.get("foaf"), Some(&String::from(FOAF_VOCAB)));
// Unrelated keys still can not be found.
assert_eq!(pm.mapping.get("rdfs"), None);
// Can't add _ as that's reserved.
assert_eq!(
pm.add_prefix("_", ""),
Err(InvalidPrefixError::ReservedPrefix)
);
// Keys can be removed.
pm.remove_prefix("foaf");
// The "foaf" key should not be found.
assert_eq!(pm.mapping.get("foaf"), None);
}
#[test]
fn display_curie() {
let curie = Curie::new(Some("foaf"), "Agent");
assert_eq!("foaf:Agent", format!("{curie}"));
}
#[test]
fn from_string_curie() {
let curie = Curie::new(Some("foaf"), "Agent");
assert_eq!("foaf:Agent", String::from(curie));
let curie = Curie::new(None, "Agent");
assert_eq!("Agent", String::from(curie));
let curie = Curie::new(Some("foaf"), "Agent");
assert_eq!("foaf:Agent", String::from(&curie));
}
#[test]
fn expand_curie_string() {
let mut mapping = PrefixMapping::default();
let curie = "foaf:Person";
// A CURIE with an unmapped prefix isn't expanded.
assert_eq!(
mapping.expand_curie_string(curie),
Err(ExpansionError::Invalid)
);
// A CURIE without a separator doesn't cause problems. It still
// requires a default though.
assert_eq!(
mapping.expand_curie_string("Person"),
Err(ExpansionError::MissingDefault)
);
mapping.set_default("http://example.com/");
assert_eq!(
mapping.expand_curie_string("Person"),
Ok(String::from("http://example.com/Person"))
);
// Using a colon without a prefix results in using a prefix
// for an empty string.
assert_eq!(
mapping.expand_curie_string(":Person"),
Err(ExpansionError::Invalid)
);
mapping
.add_prefix("", "http://example.com/ExampleDocument#")
.unwrap();
assert_eq!(
mapping.expand_curie_string(":Person"),
Ok(String::from("http://example.com/ExampleDocument#Person"))
);
// And having a default won't allow a prefixed CURIE to
// be expanded with the default.
assert_eq!(
mapping.expand_curie_string(curie),
Err(ExpansionError::Invalid)
);
mapping.add_prefix("foaf", FOAF_VOCAB).unwrap();
// A CURIE with a mapped prefix is expanded correctly.
assert_eq!(
mapping.expand_curie_string(curie),
Ok(String::from("http://xmlns.com/foaf/0.1/Person"))
);
}
#[test]
fn expand_curie() {
let mut mapping = PrefixMapping::default();
mapping.add_prefix("foaf", FOAF_VOCAB).unwrap();
let curie = Curie::new(Some("foaf"), "Agent");
assert_eq!(
mapping.expand_curie(&curie),
Ok(String::from("http://xmlns.com/foaf/0.1/Agent"))
);
}
#[test]
fn expand_curie_default() {
let mut mapping = PrefixMapping::default();
mapping.set_default(FOAF_VOCAB);
let curie = Curie::new(None, "Agent");
assert_eq!(
mapping.expand_curie(&curie),
Ok(String::from("http://xmlns.com/foaf/0.1/Agent"))
);
}
#[test]
fn shrink_iri_prefix() {
let mut mapping = PrefixMapping::default();
mapping.add_prefix("foaf", FOAF_VOCAB).unwrap();
let curie = Curie::new(Some("foaf"), "Agent");
assert_eq!(
mapping.shrink_iri("http://xmlns.com/foaf/0.1/Agent"),
Ok(curie)
);
}
#[test]
fn shrink_iri_precedence() {
let mut mapping = PrefixMapping::default();
mapping.add_prefix("a", "http://example.com/").unwrap();
mapping
.add_prefix("b", "http://example.com/other/")
.unwrap();
assert_eq!(
mapping.shrink_iri("http://example.com/thing"),
Ok(Curie::new(Some("a"), "thing")),
);
assert_eq!(
mapping.shrink_iri("http://example.com/other/thing"),
Ok(Curie::new(Some("a"), "other/thing")),
);
let mut mapping2 = PrefixMapping::default();
mapping2
.add_prefix("b", "http://example.com/other/")
.unwrap();
mapping2.add_prefix("a", "http://example.com/").unwrap();
assert_eq!(
mapping2.shrink_iri("http://example.com/thing"),
Ok(Curie::new(Some("a"), "thing")),
);
assert_eq!(
mapping2.shrink_iri("http://example.com/other/thing"),
Ok(Curie::new(Some("b"), "thing")),
);
}
#[test]
fn split_iri_default() {
let mut mapping = PrefixMapping::default();
mapping.set_default(FOAF_VOCAB);
let curie = Curie::new(None, "Agent");
assert_eq!(
mapping.shrink_iri("http://xmlns.com/foaf/0.1/Agent"),
Ok(curie)
);
}
#[test]
fn prefix_mapping_equality() {
let mut m1 = PrefixMapping::default();
let mut m2 = PrefixMapping::default();
assert_eq!(m1, m2);
m1.set_default(FOAF_VOCAB);
assert_ne!(m1, m2);
m2.set_default(FOAF_VOCAB);
assert_eq!(m1, m2);
m1.add_prefix("foaf", FOAF_VOCAB).unwrap();
assert_ne!(m1, m2);
m2.add_prefix("foaf", FOAF_VOCAB).unwrap();
assert_eq!(m1, m2);
}
}