From e1d6132fc72f899a3be84b3fc059686720d8a6fe Mon Sep 17 00:00:00 2001 From: mark Date: Wed, 26 Nov 2025 16:42:48 +0000 Subject: [PATCH] feat: add xsd:duration codec and data type --- CHANGELOG.md | 1 + README.md | 4 +- lib/src/codecs/codecs.dart | 1 + .../codecs/duration/xsd_duration_codec.dart | 34 +++ lib/src/types/types.dart | 1 + lib/src/types/xsd_duration.dart | 262 ++++++++++++++++++ pubspec.yaml | 1 + test/types/xsd_duration_test.dart | 163 +++++++++++ 8 files changed, 466 insertions(+), 1 deletion(-) create mode 100644 lib/src/codecs/duration/xsd_duration_codec.dart create mode 100644 lib/src/types/xsd_duration.dart create mode 100644 test/types/xsd_duration_test.dart diff --git a/CHANGELOG.md b/CHANGELOG.md index 641e116..153382a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -25,3 +25,4 @@ - Implement `xsd:unsignedLong` data type codec - Implement `xsd:gDay` codec and data type - Implement `xsd:gMonthDay` codec and data type +- Implement `xsd:duration` codec and data type \ No newline at end of file diff --git a/README.md b/README.md index ddd4613..debb153 100644 --- a/README.md +++ b/README.md @@ -50,7 +50,7 @@ This library aims to support the following XSD 1.1 built-in datatypes that are c | `xsd:anyURI` | ✅ | ❌ | `Uri` | `dart:core` | | `xsd:hexBinary` | ✅ | ✅ | `Uint8List` | `dart:typed_data` | | `xsd:base64Binary` | ✅ | ✅ | `Uint8List` | `dart:typed_data` | -| `xsd:duration` | ✅ | ❌ | ??? | ??? | +| `xsd:duration` | ✅ | ✅ | `XsdDuration`[1] | `package:xsd` | | `xsd:yearMonthDuration` | ✅ | ❌ | ??? | ??? | | `xsd:dayTimeDuration` | ✅ | ❌ | ??? | ??? | | `xsd:dateTime` | ✅ | ❌ | ??? | ??? | @@ -70,6 +70,8 @@ This library aims to support the following XSD 1.1 built-in datatypes that are c | `xsd:ENTITIES` | ❌ | ❌ | ❌ | ❌ | | `xsd:NMTOKENS` | ❌ | ❌ | ❌ | ❌ | +[1] **Note:** Although Dart already has a `Duration` class it actually represents an entirely different concept to the ISO8600 / XSD idea of a duration which `XsdDuration` implements. + ## Limitations * **Facets on Built-in Types**: This library focuses on implementing the XSD built-in datatypes as they are defined in the "XML Schema Part 2: Datatypes" specification. This includes their inherent properties, lexical spaces, value spaces, and any *fixed* facets that define them (e.g., the range of `xsd:byte` or the `whiteSpace` behavior of `xsd:token`). diff --git a/lib/src/codecs/codecs.dart b/lib/src/codecs/codecs.dart index 37a92cc..cc4a192 100644 --- a/lib/src/codecs/codecs.dart +++ b/lib/src/codecs/codecs.dart @@ -22,3 +22,4 @@ export 'non_positive_integer/non_positive_integer_codec.dart'; export 'unsigned_long/unsigned_long_codec.dart'; export 'g_day/g_day_codec.dart'; export 'g_month_day/gregorian_month_day_codec.dart'; +export 'duration/xsd_duration_codec.dart'; diff --git a/lib/src/codecs/duration/xsd_duration_codec.dart b/lib/src/codecs/duration/xsd_duration_codec.dart new file mode 100644 index 0000000..bb74e40 --- /dev/null +++ b/lib/src/codecs/duration/xsd_duration_codec.dart @@ -0,0 +1,34 @@ +import 'dart:convert'; + +import '../../types/xsd_duration.dart'; + +/// A [Codec] that converts between [XsdDuration] objects and their XSD string representations. +class XsdDurationCodec extends Codec { + const XsdDurationCodec(); + + @override + Converter get encoder => const XsdDurationEncoder(); + + @override + Converter get decoder => const XsdDurationDecoder(); +} + +/// Encoder for [XsdDurationCodec]. +class XsdDurationEncoder extends Converter { + const XsdDurationEncoder(); + + @override + String convert(XsdDuration input) { + return input.toString(); + } +} + +/// Decoder for [XsdDurationCodec]. +class XsdDurationDecoder extends Converter { + const XsdDurationDecoder(); + + @override + XsdDuration convert(String input) { + return XsdDuration.parse(input); + } +} diff --git a/lib/src/types/types.dart b/lib/src/types/types.dart index 06eb771..5df6444 100644 --- a/lib/src/types/types.dart +++ b/lib/src/types/types.dart @@ -3,3 +3,4 @@ export 'gregorian_year.dart'; export 'gregorian_month.dart'; export 'gregorian_day.dart'; export 'gregorian_month_day.dart'; +export 'xsd_duration.dart'; diff --git a/lib/src/types/xsd_duration.dart b/lib/src/types/xsd_duration.dart new file mode 100644 index 0000000..a6093de --- /dev/null +++ b/lib/src/types/xsd_duration.dart @@ -0,0 +1,262 @@ +import 'package:decimal/decimal.dart'; +import 'package:meta/meta.dart'; + +/// Represents an xsd:duration value. +/// +/// A duration is a period of time as defined by ISO 8601. +/// It consists of two components: +/// - A number of months (which includes years as 12 months). +/// - A number of seconds (which includes days, hours, and minutes). +/// +/// This separation is necessary because the length of a month or year varies, +/// while the length of a day, hour, minute, and second is fixed in this context +/// (ignoring leap seconds, as XSD does). +/// +/// See [XSD duration](https://www.w3.org/TR/xmlschema11-2/#duration). +@immutable +class XsdDuration { + /// The number of months in this duration. + /// + /// This captures the year and month components. + /// Positive for positive durations, negative for negative durations. + final int months; + + /// The number of seconds in this duration. + /// + /// This captures the day, hour, minute, and second components. + /// Positive for positive durations, negative for negative durations. + final Decimal seconds; + + /// Constructs an [XsdDuration]. + /// + /// [months] and [seconds] must have the same sign (both non-negative or both non-positive), + /// unless one of them is zero. + XsdDuration({this.months = 0, Decimal? seconds}) + : seconds = seconds ?? Decimal.zero { + if ((months > 0 && this.seconds < Decimal.zero) || + (months < 0 && this.seconds > Decimal.zero)) { + throw ArgumentError( + 'Months and seconds must have the same sign. Got months: $months, seconds: ${this.seconds}', + ); + } + } + + /// Returns `true` if this duration is negative. + bool get isNegative => months < 0 || seconds < Decimal.zero; + + /// Parses a string in XSD duration format into an [XsdDuration] object. + /// + /// The format is `PnYnMnDTnHnMnS`, where `n` is a number. + /// An optional leading `-` indicates a negative duration. + /// + /// Throws a [FormatException] if the input string is not a valid duration. + static XsdDuration parse(String lexicalForm) { + // Regex for Duration: + // -?P((([0-9]+Y)?([0-9]+M)?([0-9]+D)?(T([0-9]+H)?([0-9]+M)?([0-9]+(\.[0-9]+)?S)?)?)|(T([0-9]+H)?([0-9]+M)?([0-9]+(\.[0-9]+)?S)?)) + // Simplified: -?P... + // We will parse manually or with a simpler regex to extract parts. + + if (lexicalForm.isEmpty) { + throw FormatException('Invalid duration format: empty string'); + } + + bool isNegative = false; + String input = lexicalForm; + if (input.startsWith('-')) { + isNegative = true; + input = input.substring(1); + } + + if (!input.startsWith('P')) { + throw FormatException( + 'Invalid duration format: must start with P (after optional sign)', + lexicalForm, + ); + } + + // Check for empty P (and potentially empty T) + if (input == 'P') { + throw FormatException( + 'Invalid duration format: no components specified', + lexicalForm, + ); + } + + // Split into Date and Time parts + final parts = input.substring(1).split('T'); + if (parts.length > 2) { + throw FormatException( + 'Invalid duration format: multiple T separators', + lexicalForm, + ); + } + + String datePart = parts[0]; + String timePart = parts.length > 1 ? parts[1] : ''; + + if (parts.length > 1 && timePart.isEmpty) { + throw FormatException( + 'Invalid duration format: T present but no time components', + lexicalForm, + ); + } + + // We will consume the string from left to right. + + int parsedMonths = 0; + Decimal parsedSeconds = Decimal.zero; + + // Parse Date Part + if (datePart.isNotEmpty) { + // Y + int yIndex = datePart.indexOf('Y'); + if (yIndex != -1) { + String val = datePart.substring(0, yIndex); + parsedMonths += int.parse(val) * 12; + datePart = datePart.substring(yIndex + 1); + } + + // M + int mIndex = datePart.indexOf('M'); + if (mIndex != -1) { + String val = datePart.substring(0, mIndex); + parsedMonths += int.parse(val); + datePart = datePart.substring(mIndex + 1); + } + + // D + int dIndex = datePart.indexOf('D'); + if (dIndex != -1) { + String val = datePart.substring(0, dIndex); + parsedSeconds += Decimal.parse(val) * Decimal.fromInt(86400); + datePart = datePart.substring(dIndex + 1); + } + + if (datePart.isNotEmpty) { + throw FormatException( + 'Invalid duration format: unexpected characters in date part "$datePart"', + lexicalForm, + ); + } + } + + // Parse Time Part + if (timePart.isNotEmpty) { + // H + int hIndex = timePart.indexOf('H'); + if (hIndex != -1) { + String val = timePart.substring(0, hIndex); + parsedSeconds += Decimal.parse(val) * Decimal.fromInt(3600); + timePart = timePart.substring(hIndex + 1); + } + + // M + int mIndex = timePart.indexOf('M'); + if (mIndex != -1) { + String val = timePart.substring(0, mIndex); + parsedSeconds += Decimal.parse(val) * Decimal.fromInt(60); + timePart = timePart.substring(mIndex + 1); + } + + // S + int sIndex = timePart.indexOf('S'); + if (sIndex != -1) { + String val = timePart.substring(0, sIndex); + parsedSeconds += Decimal.parse(val); + timePart = timePart.substring(sIndex + 1); + } + + if (timePart.isNotEmpty) { + throw FormatException( + 'Invalid duration format: unexpected characters in time part "$timePart"', + lexicalForm, + ); + } + } + + if (isNegative) { + parsedMonths = -parsedMonths; + parsedSeconds = -parsedSeconds; + } + + return XsdDuration(months: parsedMonths, seconds: parsedSeconds); + } + + /// Returns the canonical lexical representation of this [XsdDuration]. + /// + /// The format is `PnYnMnDTnHnMnS`. + /// Zero components are omitted, except if the whole duration is zero, which is `PT0S`. + @override + String toString() { + if (months == 0 && seconds == Decimal.zero) { + return 'PT0S'; + } + + final sb = StringBuffer(); + if (isNegative) { + sb.write('-'); + } + sb.write('P'); + + final absMonths = months.abs(); + final years = absMonths ~/ 12; + final monthPart = absMonths % 12; + + if (years > 0) { + sb.write('${years}Y'); + } + if (monthPart > 0) { + sb.write('${monthPart}M'); + } + + Decimal absSeconds = seconds.abs(); + final days = (absSeconds / Decimal.fromInt(86400)).floor(); + absSeconds -= Decimal.fromBigInt(days) * Decimal.fromInt(86400); + + if (days > BigInt.zero) { + sb.write('${days}D'); + } + + if (absSeconds > Decimal.zero) { + sb.write('T'); + + final hours = (absSeconds / Decimal.fromInt(3600)).floor(); + absSeconds -= Decimal.fromBigInt(hours) * Decimal.fromInt(3600); + + final minutes = (absSeconds / Decimal.fromInt(60)).floor(); + absSeconds -= Decimal.fromBigInt(minutes) * Decimal.fromInt(60); + + if (hours > BigInt.zero) { + sb.write('${hours}H'); + } + if (minutes > BigInt.zero) { + sb.write('${minutes}M'); + } + if (absSeconds > Decimal.zero) { + // Remove trailing zeros and decimal point if integer + String s = absSeconds.toString(); + if (s.contains('.') && s.endsWith('0')) { + // Decimal package toString handles this well usually, but let's be safe if needed. + // Actually Decimal.toString() is usually good. + } + sb.write('${s}S'); + } + } else if (years == 0 && monthPart == 0 && days == BigInt.zero) { + // Should have been handled by the zero check at start, but if we have 0 seconds but non-zero months/days, we don't write T. + // If we are here, it means we had some months/days, so we don't need T part. + } + + return sb.toString(); + } + + @override + bool operator ==(Object other) { + if (identical(this, other)) return true; + return other is XsdDuration && + other.months == months && + other.seconds == seconds; + } + + @override + int get hashCode => Object.hash(months, seconds); +} diff --git a/pubspec.yaml b/pubspec.yaml index c5fe368..a76ab74 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -16,6 +16,7 @@ environment: # Add regular dependencies here. dependencies: convert: ^3.1.2 + decimal: ^3.2.4 intl: ^0.20.2 meta: ^1.17.0 diff --git a/test/types/xsd_duration_test.dart b/test/types/xsd_duration_test.dart new file mode 100644 index 0000000..0436832 --- /dev/null +++ b/test/types/xsd_duration_test.dart @@ -0,0 +1,163 @@ +import 'package:decimal/decimal.dart'; +import 'package:test/test.dart'; +import 'package:xsd/src/types/xsd_duration.dart'; + +void main() { + group('XsdDuration', () { + test('parse valid durations', () { + expect(XsdDuration.parse('P1Y').months, 12); + expect(XsdDuration.parse('P1M').months, 1); + expect(XsdDuration.parse('P12M').months, 12); + expect(XsdDuration.parse('P1Y1M').months, 13); + + expect(XsdDuration.parse('P1D').seconds, Decimal.fromInt(86400)); + expect(XsdDuration.parse('PT1H').seconds, Decimal.fromInt(3600)); + expect(XsdDuration.parse('PT1M').seconds, Decimal.fromInt(60)); + expect(XsdDuration.parse('PT1S').seconds, Decimal.fromInt(1)); + + expect( + XsdDuration.parse('P1DT1H').seconds, + Decimal.fromInt(86400 + 3600), + ); + + final d = XsdDuration.parse('P1Y2M3DT4H5M6.7S'); + expect(d.months, 14); + // 3*86400 + 4*3600 + 5*60 + 6.7 = 259200 + 14400 + 300 + 6.7 = 273906.7 + expect(d.seconds, Decimal.parse('273906.7')); + }); + + test('parse negative durations', () { + final d = XsdDuration.parse('-P1Y'); + expect(d.months, -12); + expect(d.seconds, Decimal.zero); + expect(d.isNegative, isTrue); + + final d2 = XsdDuration.parse('-PT1S'); + expect(d2.months, 0); + expect(d2.seconds, Decimal.fromInt(-1)); + expect(d2.isNegative, isTrue); + }); + + test('parse zero duration', () { + final d = XsdDuration.parse('PT0S'); + expect(d.months, 0); + expect(d.seconds, Decimal.zero); + + final d2 = XsdDuration.parse('P0Y'); + expect(d2.months, 0); + expect(d2.seconds, Decimal.zero); + }); + + test('toString canonical representation', () { + expect(XsdDuration(months: 13).toString(), 'P1Y1M'); + expect(XsdDuration(months: 12).toString(), 'P1Y'); + expect(XsdDuration(months: 1).toString(), 'P1M'); + + expect(XsdDuration(seconds: Decimal.fromInt(86400)).toString(), 'P1D'); + expect(XsdDuration(seconds: Decimal.fromInt(3600)).toString(), 'PT1H'); + expect(XsdDuration(seconds: Decimal.fromInt(60)).toString(), 'PT1M'); + expect(XsdDuration(seconds: Decimal.fromInt(1)).toString(), 'PT1S'); + + expect( + XsdDuration(months: 14, seconds: Decimal.parse('273906.7')).toString(), + 'P1Y2M3DT4H5M6.7S', + ); + + expect(XsdDuration(months: -13).toString(), '-P1Y1M'); + expect(XsdDuration(seconds: Decimal.fromInt(-86400)).toString(), '-P1D'); + + expect(XsdDuration().toString(), 'PT0S'); + }); + + test('equality', () { + expect(XsdDuration(months: 12), XsdDuration(months: 12)); + expect(XsdDuration(months: 12), isNot(XsdDuration(months: 13))); + expect( + XsdDuration(seconds: Decimal.fromInt(10)), + XsdDuration(seconds: Decimal.fromInt(10)), + ); + }); + + test('invalid formats', () { + expect(() => XsdDuration.parse(''), throwsFormatException); + expect(() => XsdDuration.parse('1Y'), throwsFormatException); // Missing P + expect(() => XsdDuration.parse('P'), throwsFormatException); // Empty + expect( + () => XsdDuration.parse('P1Y2Y'), + throwsFormatException, + ); // Duplicate Y (our parser might actually handle this loosely if we just sum, but strictly it should probably fail or we accept it as sum. The current implementation sums them if they appear in order, but if out of order or duplicate? The current parser is simple sequential. Let's check behavior.) + + // The current parser consumes sequentially. If we have P1Y1Y, it finds first Y, then looks for next. + // If the string is not fully consumed, it throws. + // So P1Y1Y: finds 1Y, remaining is 1Y. Next check is M. It won't find M. + // It continues to D, H, M, S. None found. + // Finally checks if string is empty. It is not ('1Y'). So it throws. Correct. + expect(() => XsdDuration.parse('P1Y1Y'), throwsFormatException); + + expect(() => XsdDuration.parse('PT'), throwsFormatException); + expect( + () => XsdDuration.parse('P1H'), + throwsFormatException, + ); // H needs T + }); + + test('constructor validation', () { + expect( + () => XsdDuration(months: 1, seconds: Decimal.fromInt(-1)), + throwsArgumentError, + ); + expect( + () => XsdDuration(months: -1, seconds: Decimal.fromInt(1)), + throwsArgumentError, + ); + expect( + () => XsdDuration(months: 0, seconds: Decimal.fromInt(-1)), + returnsNormally, + ); + }); + + test('roundtrip', () { + // Canonical inputs should roundtrip exactly + final canonicalInputs = [ + 'P1Y', + 'P1M', + 'P1D', + 'PT1H', + 'PT1M', + 'PT1S', + 'P1Y1M', + 'P1DT1H', + 'P1Y2M3DT4H5M6.7S', + '-P1Y', + 'PT0S', + ]; + + for (final input in canonicalInputs) { + expect( + XsdDuration.parse(input).toString(), + input, + reason: 'Failed to roundtrip canonical input: $input', + ); + } + + // Non-canonical inputs should normalize to canonical + final nonCanonicalInputs = { + 'P12M': 'P1Y', + 'PT60S': 'PT1M', + 'PT60M': 'PT1H', + 'PT24H': 'P1D', + 'P0Y': 'PT0S', + '-PT0S': 'PT0S', + 'P0001Y': 'P1Y', // Leading zeros + }; + + nonCanonicalInputs.forEach((input, expectedCanonical) { + expect( + XsdDuration.parse(input).toString(), + expectedCanonical, + reason: 'Failed to normalize input: $input', + ); + }); + }); + }); +}