encode method
- RdfDataset dataset, {
- Map<
BlankNodeTerm, String> ? blankNodeLabels, - bool generateNewBlankNodeLabels = true,
If the generateNewBlankNodeLabels
flag is false and blankNodeLabels
is not provided, or does not contain all blank nodes in the dataset,
an exception is thrown to indicate inconsistent blank node labeling.
Implementation
String encode(RdfDataset dataset,
{Map<BlankNodeTerm, String>? blankNodeLabels,
bool generateNewBlankNodeLabels = true}) {
_logger.fine('Serializing dataset to N-Quads');
final canonical = _options.canonical;
// N-Quads ignores baseUri and customPrefixes as it doesn't support
// relative IRIs or prefixed names
// Make sure to have a copy so that changes do not affect the caller's map
final blankNodeIdentifiers = {...(blankNodeLabels ??= {})};
final _BlankNodeLabelFactory counter = generateNewBlankNodeLabels
? _BlankNodeLabelFactoryImpl(blankNodeIdentifiers.values)
: _NoOpBlankNodeCounter();
var lines = <String>[
...dataset.defaultGraph.triples.map((triple) =>
_writeTriple(triple, blankNodeIdentifiers, counter, canonical)),
...dataset.namedGraphs.expand((namedGraph) => namedGraph.graph.triples
.map((quad) => _writeQuad(quad, namedGraph.name, blankNodeIdentifiers,
counter, canonical))),
];
if (canonical) {
// In canonical mode, we need to ensure that blank node labels are consistent
// across different runs and that there are no duplicate quads.
// This is achieved by converting to set and back to a list, followed by sorting the lines after generation.
// The sorting is done in code point order as per RDF 1.1 N-Quads specification.
lines = lines.toSet().toList()..sort();
}
// Join lines with LF and ensure final LF
return lines.join('\n') + (lines.isNotEmpty ? '\n' : '');
}