-
I would like to process triples and convert the subjects, predicates and objects to strings (IRIs should be converted without angle brackets). I already got the IRI-string, but I don't know how to get the string in the else-branch. In one of my early attempts this code already worked; is there a trait or type constraint missing? Or is there a better solution? type Input = BufReader<Box<dyn Read>>;
fn process<P>(&self, input: Input, parser: P)
where
P: TripleParser<Input>,
{
let mut ts = parser.parse(input);
let _ = ts.for_each_triple(|t| {
let s = t.s();
let subject: Option<String> = if s.is_iri() {
s.iri().as_deref().map(ToString::to_string)
} else {
Some(s.to_string())
};
eprintln!("subject = {:?}", subject);
});
} The code use sophia version |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
In order to make this work as is, you would need a pretty complicated type bound, but that would not really help, because not many Instead, I suggest the following, where type Input = BufReader<Box<dyn Read>>;
fn process<P>(input: Input, parser: P)
where
P: TripleParser<Input>,
{
let mut ts = parser.parse(input);
let mut buf: Vec<u8> = vec![];
let _ = ts.for_each_triple(|t| {
let s = t.s();
let subject: Option<String> = if s.is_iri() {
s.iri().as_deref().map(ToString::to_string)
} else {
Some(stringify(s))
};
eprintln!("subject = {:?}", subject);
});
}
fn stringify<T: Term>(t: T) -> String {
let mut buf = vec![];
sophia::turtle::serializer::nt::write_term(buf, t);
unsafe { // safe because nt::write_term always produces valid UTF-8
String::from_utf8_unchecked(buf)
}
} |
Beta Was this translation helpful? Give feedback.
In order to make this work as is, you would need a pretty complicated type bound, but that would not really help, because not many
Term
implementations implementDisplay
(which is the condition forto_string
to work).Instead, I suggest the following, where
to_string
is replaced with an ad-hoc function, leveraging the N-Triples serializer for all terms but IRIs.