From f771744032eca24291151b9ff5e6f5d361638fe3 Mon Sep 17 00:00:00 2001 From: mahach666 <79989386+mahach666@users.noreply.github.com> Date: Sat, 5 Dec 2026 06:09:10 +0300 Subject: [PATCH 1/7] Stream RVT downgrade partitions through the writer --- README.md | 1 + src/RvtIO.Cli/DowngradeCommand.cs | 2 +- src/RvtIO/Parsing/PartitionFraming.cs | 151 +++++- src/RvtIO/Writing/ContainerRewriter.cs | 30 +- src/RvtIO/Writing/DowngradeAnalytics.cs | 7 +- .../Writing/DowngradePartitionRewriter.cs | 429 +++++------------- src/RvtIO/Writing/DowngradeWriter.cs | 98 ++-- src/RvtIO/Writing/ElementCensus.cs | 4 +- src/RvtIO/Writing/EnergyAnalysisArchive.cs | 17 +- src/RvtIO/Writing/EnergyAnalysisTracking.cs | 7 +- src/RvtIO/Writing/LegacyAnalyticalMembers.cs | 16 +- src/RvtIO/Writing/LegacyUnitFormats.cs | 15 +- src/RvtIO/Writing/LegacyWireReferences.cs | 4 +- src/RvtIO/Writing/PageCodec.cs | 64 +++ .../RvtIO.Tests/EnergyAnalysisArchiveTests.cs | 5 +- tests/RvtIO.Tests/PageCodecTests.cs | 34 ++ .../RvtIO.Tests/PartitionFramingFuzzTests.cs | 29 ++ 17 files changed, 500 insertions(+), 413 deletions(-) diff --git a/README.md b/README.md index 99148f86..940b22b2 100644 --- a/README.md +++ b/README.md @@ -203,6 +203,7 @@ rvtio downgrade project2027.rvt --target-profile profile2026.rvt --output projec Use a profile saved by the target release. `--check` compares class versions, stored fields, and upgrade identifiers and writes only the optional report. +The element count used in the report reads stored partitions one page at a time. When writing a project for Revit 2020 or 2021, use a complete `.rvt` saved by that release. The writer uses project unit formats for 2020 and unit schema catalogs for 2021. A profile containing only a class table is usable with diff --git a/src/RvtIO.Cli/DowngradeCommand.cs b/src/RvtIO.Cli/DowngradeCommand.cs index 1da5c788..bce6500e 100644 --- a/src/RvtIO.Cli/DowngradeCommand.cs +++ b/src/RvtIO.Cli/DowngradeCommand.cs @@ -104,7 +104,7 @@ internal static int Run(string[] args, TextWriter output, TextWriter error) DowngradeWriter.DowngradeWriteResult written; try { - written = DowngradeWriter.Write(source, profile, outputPath, rule, includeOmittedAnalytics: reportPath is not null, + written = DowngradeWriter.Write(source, profile, outputPath, result, includeOmittedAnalytics: reportPath is not null, restoreLegacyAnalytics: restoreLegacyAnalytics, allowLoss: allowLoss, beforePublish: reportPath is null ? null : prepared => { diff --git a/src/RvtIO/Parsing/PartitionFraming.cs b/src/RvtIO/Parsing/PartitionFraming.cs index d1dbd881..4c887a0c 100644 --- a/src/RvtIO/Parsing/PartitionFraming.cs +++ b/src/RvtIO/Parsing/PartitionFraming.cs @@ -92,13 +92,27 @@ internal sealed record Framed(IReadOnlyList Segments, List /// Walks the stream; sees every record of every block in file order. Returns false /// with the reason in when the framing does not hold. is 4 or 8. internal static bool Walk(byte[] raw, Tags tags, int idWidth, Action onRecord, out string? failure, out int blocks, - List? segmentLengths = null, List? segmentBytes = null) + List? segmentLengths = null, List? segmentBytes = null) => + WalkCore(raw, null, tags, idWidth, onRecord, out failure, out blocks, segmentLengths, segmentBytes); + + // Chain bytes are borrowed from the reader and stay valid only during the callback. + internal sealed record BlockCallbacks(Action Begin, + Action> Chain, Action End); + + internal static bool WalkStream(Stream stored, Tags tags, int idWidth, Action onRecord, + out string? failure, out int blocks, BlockCallbacks? onBlock = null) => + WalkCore(default, stored, tags, idWidth, onRecord, out failure, out blocks, null, null, onBlock); + + private static bool WalkCore(ReadOnlyMemory raw, Stream? stored, Tags tags, int idWidth, Action onRecord, + out string? failure, out int blocks, List? segmentLengths, List? segmentBytes, + BlockCallbacks? onBlock = null) { failure = null; blocks = 0; try { - var input = new Cursor(raw, paged: true); + var pages = stored is null ? null : new PartitionPages(stored); + var input = new Cursor(raw, paged: true, pages); Require(input.U32() == 9 && input.U32() == 0, "format"); var keys = new HashSet(); var scratch = new InflateScratch(); @@ -117,12 +131,15 @@ internal static bool Walk(byte[] raw, Tags tags, int idWidth, Action onR if (expectedOwners == uint.MaxValue) { Require(pointer == 0 && blocks > 0, "terminal-marker"); + pages?.CheckRemainingTails(); // what follows the terminal is no part of the stream (measured: 432 of 434 partition streams of 52 files have bytes after it) return true; } Require((blocks != 0 || pointer == 0) && keys.Add(key), "map-key"); + onBlock?.Begin(blocks, key, expectedOwners); HashSet[] owners = [new(), new(), new()]; uint? chainIndex = null; + uint firstFlags = 0, firstOpaque = 0; long countSum = 0, sizeSum = 0; while (true) { @@ -136,15 +153,20 @@ internal static bool Walk(byte[] raw, Tags tags, int idWidth, Action onR } Require(size >= 8 && size <= int.MaxValue, "segment-length"); uint index = input.U32(); - input.U32(); // the opaque value of the deposit is neither an owner nor a length + uint opaque = input.U32(); // neither an owner nor a length Require(index is >= 101 and <= 103, "segment-index"); int payloadLength = (int)size - 8; ReadOnlyMemory payload = default; if (prefetched) input.SkipPayload(payloadLength); - else payload = input.Take(payloadLength); + else payload = input.TakePayload(payloadLength); Require(input.U16() == tags.SegmentCheckback && input.U32() == size, "segment-checkback"); uint mode = flags & 3; - if (mode is 0 or 2) Require(chainIndex == null, "chain-start"); + if (mode is 0 or 2) + { + Require(chainIndex == null, "chain-start"); + firstFlags = flags & ~3u; + firstOpaque = opaque; + } else Require(chainIndex == index, "chain-continuation"); chainIndex = index; byte[]? decoded = prefetched ? prefetch!.Take() : null; @@ -189,6 +211,7 @@ internal static bool Walk(byte[] raw, Tags tags, int idWidth, Action onR onRecord(new Record(blocks, key, (int)index, owner, extra, memory.Slice(bodyAt, (int)bodySize), memory.Slice(begin, records.Position - begin), inflated + begin)); } Require(actualCount == countSum && actualSize == sizeSum, "chain-counts"); + onBlock?.Chain((int)index, firstFlags, firstOpaque, memory); inflated += memory.Length; chain.SetLength(0); chain.Position = 0; @@ -199,10 +222,11 @@ internal static bool Walk(byte[] raw, Tags tags, int idWidth, Action onR Require(input.U16() == tags.SignatureMarker, "signature-marker"); input.Skip(input.U32()); input.Skip(2L * input.U32()); + onBlock?.End(); blocks++; } } - catch (Exception exception) when (exception is InvalidDataException or SharpZipBaseException or OverflowException) + catch (Exception exception) when (exception is InvalidDataException or EndOfStreamException or SharpZipBaseException or OverflowException) { failure = exception.Message; return false; @@ -344,9 +368,86 @@ private static void Require(bool condition, string reason) if (!condition) throw new InvalidDataException(reason); } - private sealed class Cursor(ReadOnlyMemory bytes, bool paged = false) + private sealed class PartitionPages { - private readonly int length = paged ? PayloadLength(bytes.Span) : bytes.Length; + private const int DataLength = PagedGzipStream.PageDataLength; + private const int Stride = PagedGzipStream.PageStride; + private readonly Stream stored; + private readonly long tailTagLimit; + private readonly byte[] page = new byte[Stride]; + private byte[] member = []; + private long pageStart = -1; + private long nextTail = DataLength; + + internal PartitionPages(Stream stored) + { + this.stored = stored; + long bytes = stored.Length; + Require(bytes % Stride <= DataLength, "page-framing"); + Length = checked((int)(bytes - bytes / Stride * PagedGzipStream.SegmentLength)); + // The last complete tail may have a different tag when the stream ends there. + tailTagLimit = bytes - PagedGzipStream.SegmentLength; + } + + internal int Length { get; } + + internal ReadOnlyMemory ReadMember(int position, int length) + { + if (member.Length < length) member = new byte[length]; + Read(position, member.AsSpan(0, length)); + return member.AsMemory(0, length); + } + + internal void CheckRemainingTails() => CheckTailsBefore(tailTagLimit); + + private void CheckTailsBefore(long offset) + { + Span tag = stackalloc byte[2]; + long limit = Math.Min(offset, tailTagLimit); + while (nextTail < limit) + { + stored.Position = nextTail; + stored.ReadExactly(tag); + CheckTail(tag); + nextTail += Stride; + } + } + + internal void Read(int position, Span value) + { + while (!value.IsEmpty) + { + int within = position % DataLength; + long start = position - within; + if (pageStart != start) + { + long physical = start / DataLength * Stride; + CheckTailsBefore(physical); + bool hasTailTag = nextTail == physical + DataLength && nextTail < tailTagLimit; + int length = hasTailTag ? Stride : (int)Math.Min(DataLength, Length - start); + stored.Position = physical; + stored.ReadExactly(page.AsSpan(0, length)); + if (hasTailTag) + { + CheckTail(page.AsSpan(DataLength, 2)); + nextTail += Stride; + } + pageStart = start; + } + int count = Math.Min(DataLength - within, value.Length); + page.AsSpan(within, count).CopyTo(value); + value = value[count..]; + position += count; + } + } + + private static void CheckTail(ReadOnlySpan tag) => + Require(tag[0] == 0 && (tag[1] & 0x0f) == 0, "page-framing"); + } + + private sealed class Cursor(ReadOnlyMemory bytes, bool paged = false, PartitionPages? pages = null) + { + private readonly int length = pages?.Length ?? (paged ? PayloadLength(bytes.Span) : bytes.Length); internal int Position { get; private set; } internal int Remaining => length - Position; @@ -359,12 +460,26 @@ internal void SkipPayload(int count) Position += count; } + internal ReadOnlyMemory TakePayload(int count) + { + if (pages is null) return Take(count); + int start = Position; + SkipPayload(count); + return pages.ReadMember(start, count); + } + /// The next bytes: a view of the stream where they lie, a copy only when a page tail runs through them. internal ReadOnlyMemory Take(int count) { int start = Position; SkipPayload(count); if (count == 0) return default; + if (pages is not null) + { + var data = new byte[count]; + pages.Read(start, data); + return data; + } if (!paged) return bytes.Slice(start, count); int inPage = start % PagedGzipStream.PageDataLength; @@ -382,8 +497,24 @@ internal ReadOnlyMemory Take(int count) } return value; } - internal ushort U16() => BinaryPrimitives.ReadUInt16LittleEndian(Bytes(2)); - internal uint U32() => BinaryPrimitives.ReadUInt32LittleEndian(Bytes(4)); + internal ushort U16() + { + if (pages is null) return BinaryPrimitives.ReadUInt16LittleEndian(Bytes(2)); + Span value = stackalloc byte[2]; + int start = Position; + SkipPayload(value.Length); + pages.Read(start, value); + return BinaryPrimitives.ReadUInt16LittleEndian(value); + } + internal uint U32() + { + if (pages is null) return BinaryPrimitives.ReadUInt32LittleEndian(Bytes(4)); + Span value = stackalloc byte[4]; + int start = Position; + SkipPayload(value.Length); + pages.Read(start, value); + return BinaryPrimitives.ReadUInt32LittleEndian(value); + } internal ulong U64() => BinaryPrimitives.ReadUInt64LittleEndian(Bytes(8)); internal void Skip(long count) { diff --git a/src/RvtIO/Writing/ContainerRewriter.cs b/src/RvtIO/Writing/ContainerRewriter.cs index 3232414d..035bcaee 100644 --- a/src/RvtIO/Writing/ContainerRewriter.cs +++ b/src/RvtIO/Writing/ContainerRewriter.cs @@ -66,12 +66,18 @@ internal static class ContainerRewriter /// another process (Windows only), or a file cannot be read or written. /// The source directory is damaged, or the written file differs from what was meant to be written. internal static ContainerRewriteResult Rewrite(string sourcePath, string outputPath, IReadOnlyDictionary replacements, - Action? beforeCheck = null, Action? beforePublish = null) + Action? beforeCheck = null, Action? beforePublish = null, + IReadOnlyDictionary>? generated = null) { var replacementByName = new Dictionary(StringComparer.OrdinalIgnoreCase); foreach (var (name, bytes) in replacements) if (!replacementByName.TryAdd(name, bytes)) throw new ArgumentException($"The replacement map names the stream '{name}' twice (names compare without regard to case).", nameof(replacements)); + var generatedByName = new Dictionary>(StringComparer.OrdinalIgnoreCase); + if (generated is not null) + foreach (var (name, write) in generated) + if (replacementByName.ContainsKey(name) || !generatedByName.TryAdd(name, write)) + throw new ArgumentException($"The replacement map names the stream '{name}' twice (names compare without regard to case).", nameof(generated)); string output = Path.GetFullPath(outputPath); if (File.Exists(output) || Directory.Exists(output)) @@ -79,7 +85,7 @@ internal static ContainerRewriteResult Rewrite(string sourcePath, string outputP string temporary = Path.Combine(Path.GetDirectoryName(output)!, $".{Path.GetFileName(output)}.{Guid.NewGuid():N}.tmp"); try { - var result = WriteTemporary(sourcePath, temporary, replacementByName); + var result = WriteTemporary(sourcePath, temporary, replacementByName, generatedByName); beforeCheck?.Invoke(temporary); CheckWritten(temporary, result.Entries, result.RootStorage); beforePublish?.Invoke(); @@ -98,7 +104,8 @@ internal static ContainerRewriteResult Rewrite(string sourcePath, string outputP } } - private static ContainerRewriteResult WriteTemporary(string sourcePath, string temporary, Dictionary replacements) + private static ContainerRewriteResult WriteTemporary(string sourcePath, string temporary, Dictionary replacements, + Dictionary> generated) { using var sourceFile = new FileStream(sourcePath, FileMode.Open, FileAccess.Read, FileShare.Read); using var source = RootStorage.Open(sourceFile, StorageModeFlags.LeaveOpen); @@ -111,13 +118,13 @@ private static ContainerRewriteResult WriteTemporary(string sourcePath, string t { using (var destination = RootStorage.Create(temporaryFile, version, StorageModeFlags.LeaveOpen)) { - Copy(source, destination, "", replacements, used, entries, new byte[BufferLength], 0); + Copy(source, destination, "", replacements, generated, used, entries, new byte[BufferLength], 0); rootMetadata = CopyRootMetadata(source, destination); } temporaryFile.Flush(flushToDisk: true); } - foreach (string name in replacements.Keys) + foreach (string name in replacements.Keys.Concat(generated.Keys)) if (!used.Contains(name)) throw new ArgumentException($"The replacement map names '{name}', which is not a stream of the source.", nameof(replacements)); return new ContainerRewriteResult(entries, used.Count, rootMetadata); @@ -136,7 +143,8 @@ private static OpenMcdf.Version SectorVersion(Stream file) }; } - private static void Copy(Storage from, Storage to, string prefix, Dictionary replacements, HashSet used, + private static void Copy(Storage from, Storage to, string prefix, Dictionary replacements, + Dictionary> generated, HashSet used, Dictionary entries, byte[] buffer, int depth) { if (depth > MaxDepth) throw new InvalidDataException($"The directory nests storages deeper than {MaxDepth} levels at '{prefix}'."); @@ -150,11 +158,19 @@ private static void Copy(Storage from, Storage to, string prefix, Dictionary Read( SchemaDocument schema, byte[]? latest, int width, PartitionFraming.Tags tags, - IEnumerable<(string Path, byte[] Stored)> partitions, IReadOnlySet omitted, + IEnumerable<(string Path, Func Open)> partitions, IReadOnlySet omitted, IReadOnlyDictionary? entitySchemas) { var records = new Dictionary>(); - foreach (var (_, raw) in partitions.OrderBy(p => int.Parse(p.Path.AsSpan("Partitions/".Length), CultureInfo.InvariantCulture))) + foreach (var (_, open) in partitions.OrderBy(p => int.Parse(p.Path.AsSpan("Partitions/".Length), CultureInfo.InvariantCulture))) { - bool success = PartitionFraming.Walk(raw, tags, width, record => + using var partition = open(); + bool success = PartitionFraming.WalkStream(partition, tags, width, record => { if (record.Block != 0 || !omitted.Contains(record.Owner)) return; if (!records.TryGetValue(record.Owner, out var owner)) diff --git a/src/RvtIO/Writing/DowngradePartitionRewriter.cs b/src/RvtIO/Writing/DowngradePartitionRewriter.cs index 8ea6c2d7..7547c177 100644 --- a/src/RvtIO/Writing/DowngradePartitionRewriter.cs +++ b/src/RvtIO/Writing/DowngradePartitionRewriter.cs @@ -1,6 +1,5 @@ using System.Buffers.Binary; using ICSharpCode.SharpZipLib.Checksum; -using ICSharpCode.SharpZipLib.Zip.Compression; using RvtIO.Parsing; namespace RvtIO.Writing; @@ -24,378 +23,156 @@ internal sealed record Addition(ulong Owner, byte[][] Payloads); internal sealed record ProjectEdits( IReadOnlyList Additions, IReadOnlyDictionary<(ulong Owner, int Channel), byte[]> Replacements); - internal static byte[] Rewrite( - byte[] rawStored, + internal static ContainerEntry Rewrite( + Stream stored, Stream destination, PartitionFraming.Tags sourceTags, int sourceWidth, PartitionFraming.Tags targetTags, int targetWidth, R22Transcoder transcoder, - IReadOnlySet? knownDropped, + IReadOnlySet knownDropped, + IReadOnlyDictionary keptCounts, Func? tagFixer, - out IReadOnlySet droppedOwners, ProjectEdits? projectEdits = null) { if (sourceWidth is not (4 or 8) || targetWidth is not (4 or 8)) throw new ArgumentOutOfRangeException(nameof(targetWidth), "Element identifier byte width must be 4 or 8."); - var pageCheck = PageCodec.Verify(rawStored); + var pageCheck = PageCodec.VerifyStream(stored); if (pageCheck.Status is PageCheckStatus.BadPage or PageCheckStatus.BadTail) throw new InvalidDataException($"Partition stream fails page parity at page {pageCheck.Page} ({pageCheck.Status})."); - // Validate source framing first (names failure reasons for diagnostics). - var probe = new List(); - if (!PartitionFraming.Walk(rawStored, sourceTags, sourceWidth, r => probe.Add(r), out string? probeFailure, out _)) - throw new InvalidDataException($"Partition stream framing is invalid: {probeFailure}."); - - byte[] body = PartitionFraming.RemoveTails(rawStored) - ?? throw new InvalidDataException("Partition stream page tails could not be removed."); - - if (body.Length < 8 || BinaryPrimitives.ReadUInt32LittleEndian(body.AsSpan(0, 4)) != 9) - throw new InvalidDataException("Partition stream has no format-9 header."); - - using var rebuilt = new MemoryStream(body.Length); - rebuilt.Write(body, 0, 8); - ulong sourceTerminator = sourceWidth == 8 ? ulong.MaxValue : uint.MaxValue; ulong targetTerminator = targetWidth == 8 ? ulong.MaxValue : uint.MaxValue; - var allDropped = knownDropped is HashSet known ? known : knownDropped is null ? [] : new HashSet(knownDropped); - - int pos = 8; + using var output = new PageCodec.PagedOutput(destination); + output.Write([9, 0, 0, 0, 0, 0, 0, 0]); var addedChannels = new HashSet(); var replacedRecords = new HashSet<(ulong, int)>(); - for (; ; ) - { - int blockStart = pos; - if (pos + 2 > body.Length) throw new InvalidDataException("Partition stream ends inside a block header."); - ushort marker = BinaryPrimitives.ReadUInt16LittleEndian(body.AsSpan(pos, 2)); - if (marker != sourceTags.ContentMarker) throw new InvalidDataException("Partition stream has no content-marker."); - pos += 2; - if (pos + 4 > body.Length) throw new InvalidDataException("Partition stream ends inside a block header."); - uint pointer = BinaryPrimitives.ReadUInt32LittleEndian(body.AsSpan(pos, 4)); - pos += 4; - if (pointer != 0) - { - if (pos + 2 > body.Length) throw new InvalidDataException("Partition stream ends inside a block header."); - if (BinaryPrimitives.ReadUInt16LittleEndian(body.AsSpan(pos, 2)) != sourceTags.ContentKey) - throw new InvalidDataException("Partition stream has no content-key class."); - pos += 2; - } - if (pos + 4 > body.Length) throw new InvalidDataException("Partition stream ends inside a block header."); - uint expectedOwners = BinaryPrimitives.ReadUInt32LittleEndian(body.AsSpan(pos, 4)); - pos += 4; - byte[]? key = null; - if (pointer != 0) - { - if (pos + 16 > body.Length) throw new InvalidDataException("Partition stream ends inside a block key."); - key = body.AsSpan(pos, 16).ToArray(); - pos += 16; - } + bool inProjectBlock = false; - if (expectedOwners == uint.MaxValue) + var blocks = new PartitionFraming.BlockCallbacks( + (index, key, expectedOwners) => { - // Terminal: rewrite marker with target tag, copy pointer/owner count verbatim. - var term = new byte[2 + 4 + 4]; - BinaryPrimitives.WriteUInt16LittleEndian(term.AsSpan(0, 2), targetTags.ContentMarker); - BinaryPrimitives.WriteUInt32LittleEndian(term.AsSpan(2, 4), pointer); - BinaryPrimitives.WriteUInt32LittleEndian(term.AsSpan(6, 4), expectedOwners); - rebuilt.Write(term); - break; - } - - var chains = ReadBlockChains(body, ref pos, sourceTags); - int emptySegmentStart = pos - 18; - - // Signature: skip source, write empty target signature. - if (pos + 2 > body.Length) throw new InvalidDataException("Partition stream ends inside a signature."); - if (BinaryPrimitives.ReadUInt16LittleEndian(body.AsSpan(pos, 2)) != sourceTags.SignatureMarker) - throw new InvalidDataException("Partition stream has no signature-marker."); - pos += 2; - if (pos + 4 > body.Length) throw new InvalidDataException("Partition stream ends inside a signature."); - uint sigBytes = BinaryPrimitives.ReadUInt32LittleEndian(body.AsSpan(pos, 4)); - pos += 4 + checked((int)sigBytes); - if (pos + 4 > body.Length) throw new InvalidDataException("Partition stream ends inside a signature."); - uint sigChars = BinaryPrimitives.ReadUInt32LittleEndian(body.AsSpan(pos, 4)); - pos += 4 + checked((int)(2L * sigChars)); - - // Owners whose data class the target table does not define, or whose payload cannot be - // rewritten in the target grammar, are left out of the block: Revit refuses an unknown - // class tag and a record body left as 0xFFFE ("can't find PersistentClass"), so the - // element's header, data and geometry records all go and the block owner count follows. - // A payload that only fails once the element universe is set (dangling-id rule) - // is also left out: the known set was built before the universe existed. - var freshDropped = DetectDroppedOwners(chains, transcoder, sourceTerminator, sourceWidth); - HashSet dropOwners; - if (knownDropped is null) dropOwners = freshDropped; - else { dropOwners = new HashSet(knownDropped); dropOwners.UnionWith(freshDropped); } - uint writeOwners = expectedOwners; - if (dropOwners.Count > 0) + inProjectBlock = key.Length == 0; + uint count = knownDropped.Count == 0 ? expectedOwners : keptCounts.GetValueOrDefault(index); + if (inProjectBlock && projectEdits is not null) + count = checked(count + (uint)projectEdits.Additions.Count); + WriteHeader(key, count); + }, + (channel, flags, opaque, data) => + WriteConvertedChain(output, new ChainSpan(channel, flags, opaque, data), targetTags, sourceWidth, + targetWidth, transcoder, sourceTerminator, targetTerminator, knownDropped, tagFixer, + inProjectBlock ? projectEdits : null, addedChannels, replacedRecords), + () => { - allDropped.UnionWith(dropOwners); - var kept = new HashSet(); - foreach (var chain in chains) - if (chain.Channel == 101) - foreach (var (owner, _) in ReadRecords(chain.Inflated, 101, sourceWidth)) - if (owner != sourceTerminator && !dropOwners.Contains(owner)) kept.Add(owner); - writeOwners = (uint)kept.Count; - } - if (key is null && projectEdits is not null) - writeOwners = checked(writeOwners + (uint)projectEdits.Additions.Count); - - // Write block header with target tags, the surviving owner count, pointer and key unchanged. - { - var header = new MemoryStream(); - var tag = new byte[2]; - BinaryPrimitives.WriteUInt16LittleEndian(tag, targetTags.ContentMarker); - header.Write(tag); - var ptr = new byte[4]; - BinaryPrimitives.WriteUInt32LittleEndian(ptr, pointer); - header.Write(ptr); - if (pointer != 0) - { - BinaryPrimitives.WriteUInt16LittleEndian(tag, targetTags.ContentKey); - header.Write(tag); - } - var own = new byte[4]; - BinaryPrimitives.WriteUInt32LittleEndian(own, writeOwners); - header.Write(own); - if (key != null) header.Write(key); - rebuilt.Write(header.ToArray()); - } - - foreach (var chain in chains) - WriteConvertedChain(rebuilt, chain, targetTags, sourceWidth, targetWidth, transcoder, sourceTerminator, targetTerminator, - dropOwners, tagFixer, key is null ? projectEdits : null, addedChannels, replacedRecords); - - // Empty segment closing the block. - { - var empty = new byte[18]; - BinaryPrimitives.WriteUInt16LittleEndian(empty.AsSpan(0, 2), targetTags.SegmentMarker); - rebuilt.Write(empty); - } - // Empty signature (bytes no longer signed by Revit). - { - var sig = new byte[2 + 4 + 4]; - BinaryPrimitives.WriteUInt16LittleEndian(sig.AsSpan(0, 2), targetTags.SignatureMarker); - rebuilt.Write(sig); - } - - _ = emptySegmentStart; - _ = blockStart; - } - + Span empty = stackalloc byte[18]; + empty.Clear(); + BinaryPrimitives.WriteUInt16LittleEndian(empty, targetTags.SegmentMarker); + output.Write(empty); + Span signature = stackalloc byte[10]; + signature.Clear(); + BinaryPrimitives.WriteUInt16LittleEndian(signature, targetTags.SignatureMarker); + output.Write(signature); + }); + if (!PartitionFraming.WalkStream(stored, sourceTags, sourceWidth, _ => { }, out var sourceFailure, out _, blocks)) + throw new InvalidDataException($"Partition stream framing is invalid: {sourceFailure}."); + + WriteHeader("", uint.MaxValue); if (projectEdits is not null && (addedChannels.Count != 3 || replacedRecords.Count != projectEdits.Replacements.Count)) throw new InvalidDataException("The partition is missing a channel or record required by the project edits."); - byte[] encoded = PageCodec.EncodePadded(rebuilt.ToArray()); + var entry = output.Finish(); - // Verify with target framing, widths and checksums. - var pageVerify = PageCodec.Verify(encoded); + var pageVerify = PageCodec.VerifyStream(destination); if (pageVerify.Status != PageCheckStatus.Valid) throw new InvalidDataException($"Rewritten partition stream failed page parity ({pageVerify.Status} at page {pageVerify.Page})."); var adler = new Adler32(); - bool ok = PartitionFraming.Walk(encoded, targetTags, targetWidth, record => + bool ok = PartitionFraming.WalkStream(destination, targetTags, targetWidth, record => { - if (record.Owner == targetTerminator && record.Body.Length == 0) return; - if (record.Channel == 101) return; + if (record.Channel == 101 || record.Owner == targetTerminator && record.Body.IsEmpty) return; adler.Reset(); - adler.Update(record.Body.ToArray()); + if (System.Runtime.InteropServices.MemoryMarshal.TryGetArray(record.Body, out var bytes)) + adler.Update(bytes); + else adler.Update(record.Body.ToArray()); if ((uint)adler.Value != record.Extra) throw new InvalidDataException($"Rewritten record (block {record.Block}, channel {record.Channel}, owner {record.Owner}) has a mismatched Adler-32 checksum."); }, out string? failure, out _); if (!ok) throw new InvalidDataException($"Rewritten partition stream failed framing verification: {failure}."); - droppedOwners = allDropped; - return encoded; - } + return entry; - /// The owners whose records cannot be carried into the target: their class has no - /// counterpart, or a data or geometry payload cannot be rewritten in the target grammar. - private static HashSet DetectDroppedOwners(List chains, R22Transcoder transcoder, ulong sourceTerminator, int sourceWidth) - { - var dropOwners = new HashSet(); - foreach (var chain in chains) + void WriteHeader(string key, uint owners) { - if (chain.Channel is not (102 or 103)) continue; - foreach (var (owner, recordBody) in ReadRecords(chain.Inflated, chain.Channel, sourceWidth)) + bool keyed = key.Length != 0; + Span header = stackalloc byte[12]; + BinaryPrimitives.WriteUInt16LittleEndian(header, targetTags.ContentMarker); + BinaryPrimitives.WriteUInt32LittleEndian(header[2..], keyed ? uint.MaxValue : 0); + int countOffset = 6; + if (keyed) { - if (owner == sourceTerminator || recordBody.Length < 2 || dropOwners.Contains(owner)) continue; - int classTag = BinaryPrimitives.ReadUInt16LittleEndian(recordBody.Span); - if (!transcoder.HasSourceClass(classTag)) - { - // A data record must name a class of the file; an unknown geometry tag is - // opaque bytes of a synthetic fixture and keeps the old copy-through. - if (chain.Channel == 102) dropOwners.Add(owner); - continue; - } - if (!transcoder.CanWriteRecord(classTag, isElement: chain.Channel == 102)) - { - dropOwners.Add(owner); - continue; - } - var rewritten = recordBody.ToArray(); - if (transcoder.Payload(rewritten, 0, rewritten.Length, out _) is null) dropOwners.Add(owner); + BinaryPrimitives.WriteUInt16LittleEndian(header[6..], targetTags.ContentKey); + countOffset += 2; } + BinaryPrimitives.WriteUInt32LittleEndian(header[countOffset..], owners); + output.Write(header[..(countOffset + 4)]); + if (keyed) output.Write(Convert.FromHexString(key)); } - return dropOwners; } /// The owners a stored stream holds and the ones a rewrite would leave out. internal sealed record PartitionState(HashSet Owners, HashSet Dropped); - /// - /// The element ids a stored stream holds (the channel-101 owners) and the ids the rewrite would - /// leave out, without rewriting it. The writer uses the two sets to know which references in the - /// written file would point at an element that is gone. - /// internal static PartitionState Inspect( - byte[] rawStored, PartitionFraming.Tags sourceTags, int sourceWidth, R22Transcoder transcoder) + Stream stored, PartitionFraming.Tags tags, int width, R22Transcoder transcoder, + IReadOnlySet? knownDropped = null, Dictionary? keptCounts = null) { - byte[] body = PartitionFraming.RemoveTails(rawStored) - ?? throw new InvalidDataException("Partition stream page tails could not be removed."); - if (body.Length < 8 || BinaryPrimitives.ReadUInt32LittleEndian(body.AsSpan(0, 4)) != 9) - throw new InvalidDataException("Partition stream has no format-9 header."); - - ulong sourceTerminator = sourceWidth == 8 ? ulong.MaxValue : uint.MaxValue; + ulong terminator = width == 8 ? ulong.MaxValue : uint.MaxValue; var owners = new HashSet(); var dropped = new HashSet(); - int pos = 8; - for (; ; ) + var blockDropped = new HashSet(); + var kept = new HashSet(); + int block = -1; + bool countKept = keptCounts != null && knownDropped is { Count: > 0 }; + if (!PartitionFraming.WalkStream(stored, tags, width, record => { - if (pos + 10 > body.Length) throw new InvalidDataException("Partition stream ends inside a block header."); - if (BinaryPrimitives.ReadUInt16LittleEndian(body.AsSpan(pos, 2)) != sourceTags.ContentMarker) - throw new InvalidDataException("Partition stream has no content-marker."); - pos += 2; - uint pointer = BinaryPrimitives.ReadUInt32LittleEndian(body.AsSpan(pos, 4)); - pos += 4; - if (pointer != 0) + if (record.Block != block) { - if (pos + 2 > body.Length || BinaryPrimitives.ReadUInt16LittleEndian(body.AsSpan(pos, 2)) != sourceTags.ContentKey) - throw new InvalidDataException("Partition stream has no content-key class."); - pos += 2; + if (countKept && block >= 0) keptCounts![block] = (uint)kept.Count; + block = record.Block; + blockDropped.Clear(); + kept.Clear(); } - if (pos + 4 > body.Length) throw new InvalidDataException("Partition stream ends inside a block header."); - uint ownerCount = BinaryPrimitives.ReadUInt32LittleEndian(body.AsSpan(pos, 4)); - pos += 4; - if (pointer != 0) - { - if (pos + 16 > body.Length) throw new InvalidDataException("Partition stream ends inside a block key."); - pos += 16; - } - if (ownerCount == uint.MaxValue) break; - - var chains = ReadBlockChains(body, ref pos, sourceTags); - foreach (var chain in chains) - { - if (chain.Channel is not (101 or 102 or 103)) continue; - foreach (var (owner, _) in ReadRecords(chain.Inflated, chain.Channel, sourceWidth)) - if (owner != sourceTerminator) owners.Add(owner); - } - dropped.UnionWith(DetectDroppedOwners(chains, transcoder, sourceTerminator, sourceWidth)); - - // Signature: skip it as the rewrite does. - if (pos + 2 > body.Length || BinaryPrimitives.ReadUInt16LittleEndian(body.AsSpan(pos, 2)) != sourceTags.SignatureMarker) - throw new InvalidDataException("Partition stream has no signature-marker."); - pos += 2; - if (pos + 4 > body.Length) throw new InvalidDataException("Partition stream ends inside a signature."); - pos += 4 + checked((int)BinaryPrimitives.ReadUInt32LittleEndian(body.AsSpan(pos, 4))); - if (pos + 4 > body.Length) throw new InvalidDataException("Partition stream ends inside a signature."); - pos += 4 + checked((int)(2L * BinaryPrimitives.ReadUInt32LittleEndian(body.AsSpan(pos, 4)))); - } - return new PartitionState(owners, dropped); - } - - private sealed record ChainSpan(int Channel, uint UpperFlags, uint Opaque, byte[] Inflated); - - /// The records of an inflated chain: owner and body, in stored order. - private static IEnumerable<(ulong Owner, ReadOnlyMemory Body)> ReadRecords(byte[] inflated, int channel, int width) - { - int at = 0; - while (at + width + 4 <= inflated.Length) - { - ulong owner = width == 8 - ? BinaryPrimitives.ReadUInt64LittleEndian(inflated.AsSpan(at, 8)) - : BinaryPrimitives.ReadUInt32LittleEndian(inflated.AsSpan(at, 4)); - at += width + (channel != 101 ? 4 : 0); - if (at + 4 > inflated.Length) yield break; - int size = BinaryPrimitives.ReadUInt32LittleEndian(inflated.AsSpan(at, 4)) is var raw && raw <= int.MaxValue ? (int)raw : -1; - if (size < 0) yield break; - at += 4; - if (at + (long)size + 4 > inflated.Length) yield break; - yield return (owner, new ReadOnlyMemory(inflated, at, size)); - at += size + 4; - } - } - - private static List ReadBlockChains(byte[] body, ref int pos, PartitionFraming.Tags tags) - { - var chains = new List(); - using var inflated = new MemoryStream(); - int channel = 0; - uint firstFlags = 0, firstOpaque = 0; - bool inChain = false; - - while (true) - { - if (pos + 2 > body.Length) throw new InvalidDataException("Partition stream ends inside a segment."); - if (BinaryPrimitives.ReadUInt16LittleEndian(body.AsSpan(pos, 2)) != tags.SegmentMarker) - throw new InvalidDataException("Partition stream has no segment-marker."); - pos += 2; - if (pos + 4 + 4 + 4 + 4 > body.Length) throw new InvalidDataException("Partition stream ends inside a segment header."); - uint flags = BinaryPrimitives.ReadUInt32LittleEndian(body.AsSpan(pos, 4)); pos += 4; - pos += 4; // count (verified on rewrite, not needed for parsing) - uint size = BinaryPrimitives.ReadUInt32LittleEndian(body.AsSpan(pos, 4)); pos += 4; - pos += 4; // unc - if (size == 0) + if (record.Owner == terminator) return; + owners.Add(record.Owner); + if (record.Channel == 101) { - if ((flags & 3) != 0) throw new InvalidDataException("Partition stream empty segment is chained."); - break; + if (countKept && !knownDropped!.Contains(record.Owner)) kept.Add(record.Owner); + return; } - if (pos + 8 > body.Length) throw new InvalidDataException("Partition stream ends inside a segment header."); - uint index = BinaryPrimitives.ReadUInt32LittleEndian(body.AsSpan(pos, 4)); pos += 4; - uint opaque = BinaryPrimitives.ReadUInt32LittleEndian(body.AsSpan(pos, 4)); pos += 4; - int payloadLength = checked((int)size - 8); - if (pos + payloadLength + 6 > body.Length) throw new InvalidDataException("Partition stream ends inside a segment."); - InflateGzipMember(body, pos, payloadLength, inflated, resetFirst: (flags & 3) is 0 or 2); - pos += payloadLength + 6; // SegmentCheckback + size (validated on rewrite) - - uint mode = flags & 3; - if (mode is 0 or 2) + if (record.Body.Length < 2 || blockDropped.Contains(record.Owner)) return; + int tag = BinaryPrimitives.ReadUInt16LittleEndian(record.Body.Span); + bool isElement = record.Channel == 102; + bool shouldDrop = isElement; + if (transcoder.HasSourceClass(tag)) { - if (inChain) throw new InvalidDataException("Partition stream chain starts inside a chain."); - inChain = true; - firstFlags = flags & ~3u; - firstOpaque = opaque; - channel = (int)index; + shouldDrop = !transcoder.CanWriteRecord(tag, isElement); + if (!shouldDrop) + { + byte[] body = record.Body.ToArray(); + shouldDrop = transcoder.Payload(body, 0, body.Length, out _) is null; + } } - else if (!inChain) throw new InvalidDataException("Partition stream chain continuation starts no chain."); - if (mode is 0 or 1) + if (shouldDrop) { - inChain = false; - chains.Add(new ChainSpan(channel, firstFlags, firstOpaque, inflated.ToArray())); + blockDropped.Add(record.Owner); + dropped.Add(record.Owner); } - } - if (inChain) throw new InvalidDataException("Partition stream ends inside a chain."); - return chains; + }, out var failure, out _)) + throw new InvalidDataException($"Partition stream framing is invalid: {failure}."); + if (countKept && block >= 0) keptCounts![block] = (uint)kept.Count; + return new PartitionState(owners, dropped); } - private static void InflateGzipMember(byte[] source, int offset, int length, MemoryStream destination, bool resetFirst) - { - if (resetFirst) - { - destination.SetLength(0); - destination.Position = 0; - } - var inflater = new Inflater(noHeader: true); - inflater.SetInput(source, offset + 10, length - 18); - byte[] buffer = new byte[32_768]; - while (!inflater.IsFinished) - { - int count = inflater.Inflate(buffer); - if (count == 0 && !inflater.IsFinished) - throw new InvalidDataException("Unexpected end of deflate member while reading partition segment."); - destination.Write(buffer, 0, count); - } - } + private sealed record ChainSpan(int Channel, uint UpperFlags, uint Opaque, ReadOnlyMemory Inflated); private static void WriteConvertedChain( - MemoryStream output, + PageCodec.PagedOutput output, ChainSpan chain, PartitionFraming.Tags targetTags, int sourceWidth, @@ -424,30 +201,28 @@ void FlushBatch() batchBodyBytes = 0; } - byte[] inf = chain.Inflated; + ReadOnlySpan inf = chain.Inflated.Span; int at = 0; while (at < inf.Length) { // The owner is written in the width of the whole stream, source and target alike. if (at + sourceWidth > inf.Length) throw new InvalidDataException("Partition record ends inside its owner."); ulong owner = sourceWidth == 8 - ? BinaryPrimitives.ReadUInt64LittleEndian(inf.AsSpan(at, 8)) - : BinaryPrimitives.ReadUInt32LittleEndian(inf.AsSpan(at, 4)); + ? BinaryPrimitives.ReadUInt64LittleEndian(inf.Slice(at, 8)) + : BinaryPrimitives.ReadUInt32LittleEndian(inf.Slice(at, 4)); at += sourceWidth; uint extra = 0; bool hasExtra = chain.Channel != 101; if (hasExtra) { if (at + 4 > inf.Length) throw new InvalidDataException("Partition record ends inside its checksum."); - extra = BinaryPrimitives.ReadUInt32LittleEndian(inf.AsSpan(at, 4)); + extra = BinaryPrimitives.ReadUInt32LittleEndian(inf.Slice(at, 4)); at += 4; } if (at + 4 > inf.Length) throw new InvalidDataException("Partition record ends inside its length."); - int bodySize = checked((int)BinaryPrimitives.ReadUInt32LittleEndian(inf.AsSpan(at, 4))); + int bodySize = checked((int)BinaryPrimitives.ReadUInt32LittleEndian(inf.Slice(at, 4))); int bodyAt = at + 4; if (bodyAt + bodySize + 4 > inf.Length) throw new InvalidDataException("Partition record ends inside its body."); - byte[] body = new byte[bodySize]; - Buffer.BlockCopy(inf, bodyAt, body, 0, bodySize); at = bodyAt + bodySize + 4; _ = extra; @@ -482,6 +257,7 @@ void FlushBatch() throw new DowngradeRefusedException("id-beyond-32-bits", $"Element id {owner} does not fit in 32 bits and cannot be downgraded to a 4-byte release."); newOwner = owner; + var rawBody = inf.Slice(bodyAt, bodySize); byte[]? converted; if (projectEdits?.Replacements.TryGetValue((owner, chain.Channel), out var edit) == true) { @@ -490,6 +266,7 @@ void FlushBatch() } else { + byte[] body = rawBody.ToArray(); converted = bodySize >= 2 ? transcoder.Payload(body, 0, bodySize, out _) : null; if (converted is not null && tagFixer is not null && tagFixer(body, converted) is { } fixedBody) converted = fixedBody; @@ -499,7 +276,7 @@ void FlushBatch() // A body that cannot be rewritten on its own (an unknown nested structure) keeps its bytes // behind an unknown class tag; the element stays framed and is left out by readers. converted = new byte[bodySize >= 2 ? bodySize : 2]; - if (bodySize >= 2) Buffer.BlockCopy(body, 2, converted, 2, bodySize - 2); + if (bodySize >= 2) rawBody[2..].CopyTo(converted.AsSpan(2)); BinaryPrimitives.WriteUInt16LittleEndian(converted.AsSpan(0, 2), R22Transcoder.UnknownTag); } newBody = converted; @@ -546,10 +323,8 @@ void WriteRecord(ulong owner, byte[] recordBody, uint checksum) } } - private static int DetectSourceWidth(ChainSpan chain, ulong sourceTerminator) => sourceTerminator == ulong.MaxValue ? 8 : 4; - private static void WriteSplitRecord( - MemoryStream output, + PageCodec.PagedOutput output, PartitionFraming.Tags tags, ChainSpan chain, ReadOnlySpan recordHeader, @@ -576,7 +351,7 @@ private static void WriteSplitRecord( } private static void WriteSegment( - MemoryStream output, + PageCodec.PagedOutput output, PartitionFraming.Tags tags, uint flags, uint recordCount, diff --git a/src/RvtIO/Writing/DowngradeWriter.cs b/src/RvtIO/Writing/DowngradeWriter.cs index de4500e2..3fe19b9a 100644 --- a/src/RvtIO/Writing/DowngradeWriter.cs +++ b/src/RvtIO/Writing/DowngradeWriter.cs @@ -30,9 +30,15 @@ internal sealed record DowngradeWriteResult( internal static DowngradeWriteResult Write( string sourcePath, string profilePath, string outputPath, GuidRule rule, bool includeOmittedAnalytics = false, - bool restoreLegacyAnalytics = false, bool allowLoss = false, Action? beforePublish = null) + bool restoreLegacyAnalytics = false, bool allowLoss = false, Action? beforePublish = null) => + Write(sourcePath, profilePath, outputPath, DowngradePlanner.Plan(sourcePath, profilePath, rule), + includeOmittedAnalytics, restoreLegacyAnalytics, allowLoss, beforePublish); + + internal static DowngradeWriteResult Write( + string sourcePath, string profilePath, string outputPath, DowngradePlanner.Result planResult, + bool includeOmittedAnalytics = false, bool restoreLegacyAnalytics = false, bool allowLoss = false, + Action? beforePublish = null) { - var planResult = DowngradePlanner.Plan(sourcePath, profilePath, rule); if (restoreLegacyAnalytics && (planResult.SourceRelease < 2023 || planResult.TargetRelease != 2022)) throw new DowngradeRefusedException("unsupported-analytical-restore", "Legacy analytical restoration requires a Revit 2023 or newer source and its historical Revit 2022 project as the target profile."); @@ -53,13 +59,13 @@ private static DowngradeWriteResult Transcode( byte[] sourceBfi; byte[]? sourceContents; bool isProject; - List<(string Path, byte[] Stored)> sourcePartitions = []; + List<(string Path, Func Open)> sourcePartitions = []; List<(string Name, byte[] Stored)> sourceGlobalStreams = []; byte[]? sourceElemTableStored = null; byte[]? sourceHistoryStored = null; byte[] sourceBfiProfile; byte[]? profileContents, profileLatest = null; - using (var sourceRoot = RootStorage.OpenRead(sourcePath)) + using var sourceRoot = RootStorage.OpenRead(sourcePath); { sourceSchemaBytes = PagedGzipStream.Read(sourceRoot, "Formats", "Latest") ?? throw new RvtInputException("truncated-or-damaged", $"The class table (Formats/Latest) of the source file '{Path.GetFileName(sourcePath)}' is missing or cannot be read."); @@ -74,10 +80,7 @@ private static DowngradeWriteResult Transcode( { if (entry.Type != EntryType.Stream) continue; if (!int.TryParse(entry.Name, System.Globalization.NumberStyles.None, System.Globalization.CultureInfo.InvariantCulture, out _)) continue; - using var s = partStorage.OpenStream(entry.Name); - var raw = new byte[checked((int)s.Length)]; - s.ReadExactly(raw); - sourcePartitions.Add(("Partitions/" + entry.Name, raw)); + sourcePartitions.Add(("Partitions/" + entry.Name, () => partStorage.OpenStream(entry.Name))); } if (sourceRoot.TryOpenStorage("Global", out var globalStorage)) { @@ -134,9 +137,10 @@ private static DowngradeWriteResult Transcode( // Clear references at the same transition as the omission, while their old owners are known. var knownOwners = new HashSet(); var knownDropped = new HashSet(); - foreach (var (_, raw) in sourcePartitions) + foreach (var (_, open) in sourcePartitions) { - var state = DowngradePartitionRewriter.Inspect(raw, sourceTags, sourceWidth, transcoder); + using var partition = open(); + var state = DowngradePartitionRewriter.Inspect(partition, sourceTags, sourceWidth, transcoder); knownOwners.UnionWith(state.Owners); knownDropped.UnionWith(state.Dropped); } @@ -163,12 +167,19 @@ private static DowngradeWriteResult Transcode( // A payload that only fails once the universe is set (dangling-id rule) leaves // its owner out as well: close the dropped set before writing, or the rewrite // keeps an unknown 0xFFFE tag the older release refuses with verifyClass. + var survivingOwnersByPartition = new Dictionary>(StringComparer.OrdinalIgnoreCase); + bool dropsConverged = false; for (int iter = 0; iter < 10; iter++) { var added = new HashSet(); - foreach (var (_, raw) in sourcePartitions) - { - var restate = DowngradePartitionRewriter.Inspect(raw, sourceTags, sourceWidth, transcoder); + survivingOwnersByPartition.Clear(); + foreach (var (path, open) in sourcePartitions) + { + using var partition = open(); + var ownersByBlock = new Dictionary(); + var restate = DowngradePartitionRewriter.Inspect(partition, sourceTags, sourceWidth, transcoder, + knownDropped, ownersByBlock); + survivingOwnersByPartition.Add(path, ownersByBlock); knownOwners.UnionWith(restate.Owners); foreach (var id in restate.Dropped) if (!knownDropped.Contains(id)) added.Add(id); @@ -182,7 +193,11 @@ private static DowngradeWriteResult Transcode( if (!knownDropped.Contains(uid) && knownDropped.Contains(uown)) added.Add(uid); } } - if (added.Count == 0) break; + if (added.Count == 0) + { + dropsConverged = true; + break; + } knownDropped.UnionWith(added); transcoder.SetDroppedElementIds(knownDropped); } @@ -366,10 +381,11 @@ private static DowngradeWriteResult Transcode( "Legacy analytical restoration requires a project with one numbered partition and its element history."); try { + using var partition = sourcePartitions[0].Open(); restored = LegacyAnalyticalMembers.Restore(profilePath, sourceDoc, profileDoc, PagedGzipStream.Decompress(sourceElemTableStored) ?? throw new InvalidDataException("Missing source element table."), PagedGzipStream.Decompress(sourceHistoryStored) ?? throw new InvalidDataException("Missing source episode history."), - latest, sourcePartitions[0].Stored, sourceWidth, droppedOwners, analysis, transcoder, replacements); + latest, partition, sourceWidth, droppedOwners, analysis, transcoder, replacements); } catch (Exception exception) when (exception is IOException or InvalidDataException or ArgumentException or OverflowException) { @@ -419,8 +435,9 @@ private static DowngradeWriteResult Transcode( { try { + using var partition = sourcePartitions[0].Open(); wireReferences = LegacyWireReferences.Prepare(sourceDoc, profileDoc, sourceTags, sourceWidth, - sourcePartitions[0].Stored, transcoder, knownDropped); + partition, transcoder, knownDropped); } catch (Exception exception) when (exception is InvalidDataException or ArgumentException or OverflowException) { @@ -428,17 +445,17 @@ private static DowngradeWriteResult Transcode( } } - int plannedDrops = knownDropped.Count; - foreach (var (path, raw) in sourcePartitions) + var generated = new Dictionary>(StringComparer.OrdinalIgnoreCase); + foreach (var (path, open) in sourcePartitions) { - byte[] rewritten; + DowngradePartitionRewriter.ProjectEdits? edits = restored?.Edits; try { - var edits = restored?.Edits; if (isProject && planResult.TargetRelease == 2023 && sourcePartitions.Count == 1) { + using var partition = open(); var picks = LegacyAnalyticalMembers.RestoreOpeningEdgePicks(sourceDoc, profileDoc, sourceTags, - sourceWidth, raw, entitySchemas, knownDropped, transcoder); + sourceWidth, partition, entitySchemas, knownDropped, transcoder); if (picks.Count != 0) edits = new([], picks); } var added = defaults?.PartitionPath == path ? defaults.Elements.AsEnumerable() : []; @@ -457,8 +474,7 @@ private static DowngradeWriteResult Transcode( edits = new(edits?.Additions ?? [], bodies); } - rewritten = DowngradePartitionRewriter.Rewrite(raw, sourceTags, sourceWidth, targetTags, targetWidth, - transcoder, knownDropped, tagFixer, out _, edits); + generated.Add(path, destination => RewritePartition(path, open, destination, edits)); } catch (DowngradeRefusedException) { throw; } catch (Exception exception) when (exception is InvalidDataException or ArgumentException or OverflowException) @@ -466,15 +482,10 @@ private static DowngradeWriteResult Transcode( throw new DowngradeRefusedException("partition-transcode-failed", $"Partition stream '{path}' cannot be transcoded to release {planResult.TargetRelease}: {exception.Message}"); } - replacements[path] = rewritten; } - if (knownDropped.Count != plannedDrops) - throw new DowngradeRefusedException("partition-transcode-failed", - "Additional omitted elements were detected after writing the element table."); Dictionary? omittedProjectElements = null; if (droppedOwners.Count != 0 || planResult.TargetRelease <= 2022) { - using var sourceRoot = RootStorage.OpenRead(sourcePath); omittedProjectElements = ElementCensus.CountByClass(sourceRoot, sourceDoc, out _, droppedOwners); } var omittedOwners = new HashSet(droppedOwners); @@ -498,7 +509,8 @@ private static DowngradeWriteResult Transcode( $"The conversion omits records for {omittedOwners.Count} owners. Use --allow-loss with --report to write the file and review the omissions."); var result = new DowngradeWriteResult(outputPath, planResult.SourceRelease, planResult.TargetRelease, plan.Edits.Count, - replacements.Count, omittedProjectElements, omittedOwners.Order().ToArray(), includeOmittedAnalytics && analysis.Count != 0 ? analysis : null, + replacements.Count + generated.Count, omittedProjectElements, omittedOwners.Order().ToArray(), + includeOmittedAnalytics && analysis.Count != 0 ? analysis : null, restoreLegacyAnalytics ? restored?.Members ?? [] : null, restoreLegacyAnalytics ? restored?.PointSupports ?? [] : null, restoreLegacyAnalytics ? restored?.Panels ?? [] : null, restoreLegacyAnalytics ? restored?.Openings ?? [] : null, restoreLegacyAnalytics ? restored?.LineSupports ?? [] : null, @@ -507,9 +519,35 @@ private static DowngradeWriteResult Transcode( ContainerRewriter.Rewrite(sourcePath, outputPath, replacements, temporary => Verify(temporary, planResult.TargetRelease, profileSchemaBytes), - beforePublish is null ? null : () => beforePublish(result)); + beforePublish is null ? null : () => beforePublish(result), generated); return result; + ContainerEntry RewritePartition(string path, Func open, Stream destination, + DowngradePartitionRewriter.ProjectEdits? edits) + { + try + { + using var partition = open(); + var keptCounts = survivingOwnersByPartition[path]; + if (!dropsConverged) + { + // The last planning pass used the drop set from before the last update. + keptCounts.Clear(); + var state = DowngradePartitionRewriter.Inspect(partition, sourceTags, sourceWidth, transcoder, + knownDropped, keptCounts); + if (!state.Dropped.IsSubsetOf(knownDropped)) + throw new InvalidDataException("Additional omitted elements were detected after writing the element table."); + } + return DowngradePartitionRewriter.Rewrite(partition, destination, sourceTags, sourceWidth, + targetTags, targetWidth, transcoder, knownDropped, keptCounts, tagFixer, edits); + } + catch (Exception exception) when (exception is InvalidDataException or ArgumentException or OverflowException) + { + throw new DowngradeRefusedException("partition-transcode-failed", + $"Partition stream '{path}' cannot be transcoded to release {planResult.TargetRelease}: {exception.Message}"); + } + } + void Subtract(string name, int count) { if (count == 0 || omittedProjectElements is null) return; diff --git a/src/RvtIO/Writing/ElementCensus.cs b/src/RvtIO/Writing/ElementCensus.cs index cde9d76f..c3a19c6e 100644 --- a/src/RvtIO/Writing/ElementCensus.cs +++ b/src/RvtIO/Writing/ElementCensus.cs @@ -34,10 +34,8 @@ internal static class ElementCensus foreach (string name in names) { using var stream = storage.OpenStream(name); - var raw = new byte[stream.Length]; - stream.ReadExactly(raw); bool bad = false; - bool ok = PartitionFraming.Walk(raw, tags, width, record => + bool ok = PartitionFraming.WalkStream(stream, tags, width, record => { if (record.Block != 0 || record.Channel != 102 || record.Owner == terminator || onlyOwners is not null && !onlyOwners.Contains(record.Owner)) return; diff --git a/src/RvtIO/Writing/EnergyAnalysisArchive.cs b/src/RvtIO/Writing/EnergyAnalysisArchive.cs index 8990c663..da7aac86 100644 --- a/src/RvtIO/Writing/EnergyAnalysisArchive.cs +++ b/src/RvtIO/Writing/EnergyAnalysisArchive.cs @@ -28,7 +28,7 @@ internal string Encode() internal sealed record Attachment(string Partition, ulong Owner, byte[] Body); internal static Content? Capture(SchemaDocument doc, byte[] classTable, int release, int width, - PartitionFraming.Tags tags, IReadOnlyList<(string Path, byte[] Stored)> partitions) + PartitionFraming.Tags tags, IReadOnlyList<(string Path, Func Open)> partitions) { // shortcut: one partition supplies an unambiguous current record for each element. if (partitions.Count != 1) return null; @@ -38,8 +38,8 @@ internal sealed record Attachment(string Partition, ulong Owner, byte[] Body); if (classes.Count == 0) return null; var records = new Dictionary(); - foreach (var (_, stored) in partitions) - Walk(stored, tags, width, r => + foreach (var (_, open) in partitions) + Walk(open, tags, width, r => { if (r.Block == 0 && r.Channel == 102 && r.Body.Length >= 2 && classes.TryGetValue(BinaryPrimitives.ReadUInt16LittleEndian(r.Body.Span), out string? name)) @@ -49,7 +49,7 @@ internal sealed record Attachment(string Partition, ulong Owner, byte[] Body); } internal static Attachment? Prepare(Content content, SchemaDocument sourceDoc, SchemaDocument targetDoc, - PartitionFraming.Tags sourceTags, int sourceWidth, IReadOnlyList<(string Path, byte[] Stored)> partitions, + PartitionFraming.Tags sourceTags, int sourceWidth, IReadOnlyList<(string Path, Func Open)> partitions, R22Transcoder transcoder, Dictionary replacements, IReadOnlySet? dropped = null) { const string latestPath = "Global/Latest"; @@ -63,8 +63,8 @@ internal sealed record Attachment(string Partition, ulong Owner, byte[] Body); return null; var candidates = new Dictionary(); - foreach (var (path, stored) in partitions) - Walk(stored, sourceTags, sourceWidth, r => + foreach (var (path, open) in partitions) + Walk(open, sourceTags, sourceWidth, r => { if (r.Block == 0 && r.Channel == 102 && r.Body.Length >= 2 && BinaryPrimitives.ReadUInt16LittleEndian(r.Body.Span) == projectInfo) @@ -174,9 +174,10 @@ internal sealed record Attachment(string Partition, ulong Owner, byte[] Body); private static byte[] Text(string value) => [.. BitConverter.GetBytes(value.Length), .. Encoding.Unicode.GetBytes(value)]; private static byte[] Pointer(int tag) => [.. BitConverter.GetBytes(uint.MaxValue), .. BitConverter.GetBytes(checked((ushort)tag))]; - private static void Walk(byte[] stored, PartitionFraming.Tags tags, int width, Action visit) + private static void Walk(Func open, PartitionFraming.Tags tags, int width, Action visit) { - if (!PartitionFraming.Walk(stored, tags, width, visit, out var failure, out _)) + using var stored = open(); + if (!PartitionFraming.WalkStream(stored, tags, width, visit, out var failure, out _)) throw new InvalidDataException($"Cannot read the energy archive source partition: {failure}."); } } diff --git a/src/RvtIO/Writing/EnergyAnalysisTracking.cs b/src/RvtIO/Writing/EnergyAnalysisTracking.cs index ea5612ed..40e197d5 100644 --- a/src/RvtIO/Writing/EnergyAnalysisTracking.cs +++ b/src/RvtIO/Writing/EnergyAnalysisTracking.cs @@ -9,7 +9,7 @@ internal static class EnergyAnalysisTracking private const string Latest = "Global/Latest"; internal static void Restore(SchemaDocument source, SchemaDocument target, PartitionFraming.Tags tags, int width, - IReadOnlyList<(string Path, byte[] Stored)> partitions, IReadOnlyList<(long Id, long Owning)> rows, + IReadOnlyList<(string Path, Func Open)> partitions, IReadOnlyList<(long Id, long Owning)> rows, IReadOnlySet dropped, Dictionary replacements) { if (!replacements.TryGetValue(Latest, out var stored) @@ -29,9 +29,10 @@ internal static void Restore(SchemaDocument source, SchemaDocument target, Parti if (categories.Count == 0) return; var ids = new Dictionary>(); - foreach (var (_, raw) in partitions) + foreach (var (_, open) in partitions) { - if (!PartitionFraming.Walk(raw, tags, width, record => + using var partition = open(); + if (!PartitionFraming.WalkStream(partition, tags, width, record => { if (record.Block != 0 || record.Channel != 102 || !members.Contains(record.Owner) || record.Body.Length < sizeof(ushort) diff --git a/src/RvtIO/Writing/LegacyAnalyticalMembers.cs b/src/RvtIO/Writing/LegacyAnalyticalMembers.cs index 5ff2396f..db9a5e0a 100644 --- a/src/RvtIO/Writing/LegacyAnalyticalMembers.cs +++ b/src/RvtIO/Writing/LegacyAnalyticalMembers.cs @@ -32,7 +32,7 @@ private sealed class Snapshot internal readonly int RowWidth; private readonly Dictionary<(long Id, int Channel), WideBlockWalker.Walk?> _decoded = new(); - internal Snapshot(SchemaDocument schema, byte[] table, byte[] history, byte[]? latest, byte[] partition, int width) + internal Snapshot(SchemaDocument schema, byte[] table, byte[] history, byte[]? latest, Stream partition, int width) { var formats = new FormatsSchema(schema); Table = table; @@ -45,7 +45,7 @@ internal Snapshot(SchemaDocument schema, byte[] table, byte[] history, byte[]? l if (latest is not null && EntitySchemaReader.Read(latest, schema) is { } entities) Walker.UseEntitySchemas(entities, passUnknown: true); var tags = PartitionFraming.TagsOf(formats) ?? throw new InvalidDataException("Missing partition framing classes."); - if (!PartitionFraming.Walk(partition, tags, width, record => + if (!PartitionFraming.WalkStream(partition, tags, width, record => { if (record.Block != 0 || record.Body.Length < 2 || record.Owner > long.MaxValue) return; long id = (long)record.Owner; @@ -72,7 +72,7 @@ internal Snapshot(SchemaDocument schema, byte[] table, byte[] history, byte[]? l } internal static Dictionary<(ulong Owner, int Channel), byte[]> RestoreOpeningEdgePicks( - SchemaDocument source, SchemaDocument target, PartitionFraming.Tags tags, int width, byte[] partition, + SchemaDocument source, SchemaDocument target, PartitionFraming.Tags tags, int width, Stream partition, IReadOnlyDictionary? entitySchemas, IReadOnlySet dropped, R22Transcoder transcoder) { var edits = new Dictionary<(ulong Owner, int Channel), byte[]>(); @@ -82,7 +82,7 @@ internal Snapshot(SchemaDocument schema, byte[] table, byte[] history, byte[]? l var openings = new Dictionary(); var supports = new Dictionary(); - if (!PartitionFraming.Walk(partition, tags, width, record => + if (!PartitionFraming.WalkStream(partition, tags, width, record => { if (record.Block != 0 || record.Channel != 102 || record.Body.Length < sizeof(ushort) || dropped.Contains(record.Owner)) return; @@ -93,7 +93,7 @@ internal Snapshot(SchemaDocument schema, byte[] table, byte[] history, byte[]? l if (openings.Count == 0 || supports.Count == 0) return edits; var geometry = new Dictionary(); - if (!PartitionFraming.Walk(partition, tags, width, record => + if (!PartitionFraming.WalkStream(partition, tags, width, record => { if (record.Block == 0 && record.Channel == 103 && record.Body.Length >= sizeof(ushort) && (openings.ContainsKey(record.Owner) || supports.ContainsKey(record.Owner))) @@ -158,7 +158,7 @@ static WideBlockWalker Walker(SchemaDocument schema) => } internal static Result? Restore(string profilePath, SchemaDocument sourceSchema, SchemaDocument targetSchema, - byte[] sourceTable, byte[] sourceHistory, byte[]? sourceLatest, byte[] sourcePartition, int sourceWidth, + byte[] sourceTable, byte[] sourceHistory, byte[]? sourceLatest, Stream sourcePartition, int sourceWidth, IReadOnlySet dropped, IReadOnlyList analysis, R22Transcoder transcoder, Dictionary replacements) { @@ -168,10 +168,8 @@ static WideBlockWalker Walker(SchemaDocument schema) => if (streams.Length != 1) throw new InvalidDataException("The historical project must have one numbered partition."); using var stream = partitions.OpenStream(streams[0].Name); - var raw = new byte[checked((int)stream.Length)]; - stream.ReadExactly(raw); var current = new Snapshot(sourceSchema, sourceTable, sourceHistory, sourceLatest, sourcePartition, sourceWidth); - var previous = new Snapshot(targetSchema, Read("ElemTable"), Read("History"), Read("Latest"), raw, 4); + var previous = new Snapshot(targetSchema, Read("ElemTable"), Read("History"), Read("Latest"), stream, 4); if (!current.History.Guids.AsEnumerable().Reverse().Take(previous.History.Guids.Count) .SequenceEqual(previous.History.Guids.AsEnumerable().Reverse(), StringComparer.OrdinalIgnoreCase)) throw new InvalidDataException("The target profile is not an earlier revision in the source project history."); diff --git a/src/RvtIO/Writing/LegacyUnitFormats.cs b/src/RvtIO/Writing/LegacyUnitFormats.cs index 58afae0f..9c386ee4 100644 --- a/src/RvtIO/Writing/LegacyUnitFormats.cs +++ b/src/RvtIO/Writing/LegacyUnitFormats.cs @@ -9,7 +9,7 @@ internal sealed record Edit(string Partition, ulong Owner, byte[] Body); internal static Edit? Prepare(string profilePath, SchemaDocument source, SchemaDocument profile, PartitionFraming.Tags sourceTags, int sourceWidth, PartitionFraming.Tags profileTags, - IReadOnlyList<(string Path, byte[] Stored)> sourcePartitions, R22Transcoder transcoder, + IReadOnlyList<(string Path, Func Open)> sourcePartitions, R22Transcoder transcoder, IReadOnlySet dropped) { if (sourcePartitions.Count != 1 || @@ -19,8 +19,9 @@ internal sealed record Edit(string Partition, ulong Owner, byte[] Body); profile.Classes.FirstOrDefault(c => c.Name == "UnitsElem") is not { } profileClass) return null; - var (path, raw) = sourcePartitions[0]; - var element = FindUnits(raw, sourceTags, sourceWidth, sourceClass.Id); + var (path, open) = sourcePartitions[0]; + using var input = open(); + var element = FindUnits(input, sourceTags, sourceWidth, sourceClass.Id); if (element is not { } current || dropped.Contains(current.Owner) || transcoder.Payload(current.Body, 0, current.Body.Length, out _) is not { } projected) return null; @@ -31,18 +32,16 @@ internal sealed record Edit(string Partition, ulong Owner, byte[] Body); int.TryParse(e.Name, System.Globalization.NumberStyles.None, System.Globalization.CultureInfo.InvariantCulture, out _)).ToArray(); if (entries.Length != 1) return null; using var stream = partitions.OpenStream(entries[0].Name); - var bytes = new byte[checked((int)stream.Length)]; - stream.ReadExactly(bytes); - var savedFormats = FindUnits(bytes, profileTags, sizeof(int), profileClass.Id); + var savedFormats = FindUnits(stream, profileTags, sizeof(int), profileClass.Id); return savedFormats is { } saved && Fill(profile, projected, saved.Body) is { } body ? new(path, current.Owner, body) : null; } - private static (ulong Owner, byte[] Body)? FindUnits(byte[] partition, PartitionFraming.Tags tags, int width, int classId) + private static (ulong Owner, byte[] Body)? FindUnits(Stream partition, PartitionFraming.Tags tags, int width, int classId) { (ulong Owner, byte[] Body)? result = null; bool repeated = false; - if (!PartitionFraming.Walk(partition, tags, width, record => + if (!PartitionFraming.WalkStream(partition, tags, width, record => { if (record.Block != 0 || record.Channel != 102 || record.Body.Length < sizeof(ushort) || BitConverter.ToUInt16(record.Body.Span) != classId) return; diff --git a/src/RvtIO/Writing/LegacyWireReferences.cs b/src/RvtIO/Writing/LegacyWireReferences.cs index 5f237c56..a5228d5c 100644 --- a/src/RvtIO/Writing/LegacyWireReferences.cs +++ b/src/RvtIO/Writing/LegacyWireReferences.cs @@ -14,7 +14,7 @@ private static readonly (string Field, string Modern, string Legacy)[] Definitio internal static Dictionary<(ulong, int), byte[]> Prepare( SchemaDocument source, SchemaDocument target, PartitionFraming.Tags tags, int width, - byte[] partition, R22Transcoder transcoder, IReadOnlySet dropped) + Stream partition, R22Transcoder transcoder, IReadOnlySet dropped) { var edits = new Dictionary<(ulong, int), byte[]>(); var sourceWire = source.Classes.FirstOrDefault(c => c.Name == "RbsWireType"); @@ -31,7 +31,7 @@ private static readonly (string Field, string Modern, string Legacy)[] Definitio var legacy = new Dictionary(); var wires = new Dictionary(); var catalogues = new Dictionary(); - if (!PartitionFraming.Walk(partition, tags, width, record => + if (!PartitionFraming.WalkStream(partition, tags, width, record => { if (record.Block != 0 || record.Channel != 102 || record.Body.Length < sizeof(ushort)) return; int tag = BinaryPrimitives.ReadUInt16LittleEndian(record.Body.Span); diff --git a/src/RvtIO/Writing/PageCodec.cs b/src/RvtIO/Writing/PageCodec.cs index 4af84602..c79f48cb 100644 --- a/src/RvtIO/Writing/PageCodec.cs +++ b/src/RvtIO/Writing/PageCodec.cs @@ -95,6 +95,70 @@ internal static byte[] EncodePadded(ReadOnlySpan content) return Encode(padded); } + /// Writes the same padded pages as with one page of working storage. + internal sealed class PagedOutput(Stream output) : IDisposable + { + private readonly byte[] page = new byte[PagedGzipStream.PageStride]; + private readonly System.Security.Cryptography.IncrementalHash hash = + System.Security.Cryptography.IncrementalHash.CreateHash(System.Security.Cryptography.HashAlgorithmName.SHA256); + private int used; + private long length; + + internal void Write(ReadOnlySpan bytes) + { + while (!bytes.IsEmpty) + { + int take = Math.Min(bytes.Length, PagedGzipStream.PageDataLength - used); + bytes[..take].CopyTo(page.AsSpan(used)); + used += take; + bytes = bytes[take..]; + if (used == PagedGzipStream.PageDataLength) + { + Seal(page, FullPageLanes); + WriteStored(page); + used = 0; + } + } + } + + internal ContainerEntry Finish() + { + var (lanes, codeBits, parityBits, tap) = TailLayout(Math.Max(used, MinTailLength)); + int tailLength = (lanes * codeBits + 7) / 8; + page.AsSpan(used, tailLength - used).Clear(); + var tail = page.AsSpan(0, tailLength); + Seal(tail, lanes, codeBits, parityBits, tap); + WriteStored(tail); + return new ContainerEntry(true, length, Convert.ToHexString(hash.GetHashAndReset())); + } + + private void WriteStored(ReadOnlySpan data) + { + output.Write(data); + hash.AppendData(data); + length += data.Length; + } + + public void Dispose() => hash.Dispose(); + } + + internal static PageCheck VerifyStream(Stream stored) + { + stored.Position = 0; + long remaining = stored.Length; + var buffer = new byte[PagedGzipStream.PageStride]; + int page = 0; + for (; remaining >= buffer.Length; page++, remaining -= buffer.Length) + { + stored.ReadExactly(buffer); + if (!IsSealed(buffer, FullPageLanes)) + return new PageCheck(PageCheckStatus.BadPage, page); + } + var tail = buffer.AsSpan(0, (int)remaining); + stored.ReadExactly(tail); + return new PageCheck(Verify(tail).Status, page); + } + /// Number of zero bytes to append to content of this length so that accepts it: 0 when the last /// page already holds to bytes, otherwise enough to make it /// bytes. diff --git a/tests/RvtIO.Tests/EnergyAnalysisArchiveTests.cs b/tests/RvtIO.Tests/EnergyAnalysisArchiveTests.cs index e7cae094..9c246b39 100644 --- a/tests/RvtIO.Tests/EnergyAnalysisArchiveTests.cs +++ b/tests/RvtIO.Tests/EnergyAnalysisArchiveTests.cs @@ -46,12 +46,13 @@ static SchemaField Field(string name, byte type, byte mods = 0, int? reference = byte[] original = TaggedBody(24, [0, 0, 0, 0, 7, 0, 0, 0]); byte[] project = TaggedBody(23, [0, 0, 0, 0]); byte[] latest = TaggedBody(17, [255, 255, 255, 255, 16, 0, 0, 0, 0, 0]); - var partitions = new[] { (partition, BuildPartitionStream(4, tags, new SpecBlock(false, + var stored = BuildPartitionStream(4, tags, new SpecBlock(false, [ new SpecChain(101, [new(2, project), new(3, original), new(uint.MaxValue, [])]), new SpecChain(102, [new(2, project), new(3, original), new(uint.MaxValue, [])]), new SpecChain(103, [new(2, project), new(3, original), new(uint.MaxValue, [])]), - ]))) }; + ])); + var partitions = new (string Path, Func Open)[] { (partition, () => new MemoryStream(stored, writable: false)) }; byte[] classTable = [19, 83, 255, 32]; var content = Assert.IsType( EnergyAnalysisArchive.Capture(doc, classTable, 2023, 4, tags, partitions)); diff --git a/tests/RvtIO.Tests/PageCodecTests.cs b/tests/RvtIO.Tests/PageCodecTests.cs index 1326dcde..a437152f 100644 --- a/tests/RvtIO.Tests/PageCodecTests.cs +++ b/tests/RvtIO.Tests/PageCodecTests.cs @@ -9,6 +9,40 @@ public class PageCodecTests private const int PageData = PagedGzipStream.PageDataLength; private const int PageStride = PagedGzipStream.PageStride; + [Theory] + [InlineData(0)] + [InlineData(43)] + [InlineData(44)] + [InlineData(PageData - 1)] + [InlineData(PageData)] + [InlineData(PageData + 1)] + [InlineData(2 * PageData + 173)] + public void PagedOutputMatchesTheArrayEncoder(int length) + { + byte[] content = Random(length, 123); + byte[] expected = PageCodec.EncodePadded(content); + using var destination = new MemoryStream(); + using var output = new PageCodec.PagedOutput(destination); + for (int offset = 0; offset < content.Length; offset += 313) + output.Write(content.AsSpan(offset, Math.Min(313, content.Length - offset))); + var entry = output.Finish(); + + Assert.Equal(expected, destination.ToArray()); + Assert.Equal(expected.Length, entry.Length); + Assert.Equal(Convert.ToHexString(System.Security.Cryptography.SHA256.HashData(expected)), entry.Sha256); + Assert.Equal(PageCodec.Verify(expected), PageCodec.VerifyStream(destination)); + } + + [Fact] + public void VerifyStreamReportsTheFirstCorruptFullPage() + { + byte[] stored = PageCodec.EncodePadded(Random(3 * PageData, 123)); + stored[PageStride + 32] ^= 1; + using var stream = new MemoryStream(stored, writable: false); + + Assert.Equal(new PageCheck(PageCheckStatus.BadPage, 1), PageCodec.VerifyStream(stream)); + } + private static byte[] Random(int length, int seed) { var data = new byte[length]; diff --git a/tests/RvtIO.Tests/PartitionFramingFuzzTests.cs b/tests/RvtIO.Tests/PartitionFramingFuzzTests.cs index 742840b0..a1ba1ee2 100644 --- a/tests/RvtIO.Tests/PartitionFramingFuzzTests.cs +++ b/tests/RvtIO.Tests/PartitionFramingFuzzTests.cs @@ -99,6 +99,35 @@ public void Walk_ReadsGzipMembersAcrossPageTailsAndRejectsCorruptTails() AssertRejectedByTheTails(raw, "tag of the first tail"); } + [Fact] + public void Walk_StreamReadsPageSizedRangesAndChecksTailsAfterTheTerminal() + { + byte[] raw = PaddedLargeStream(); + byte[] body = RandomBytes(2 * PagedGzipStream.PageDataLength, 42); + using var stored = new PageSizedReads(raw); + var channels = new List(); + Assert.True(PartitionFraming.WalkStream(stored, FramingTags(), 4, record => + { + Assert.Equal(1001ul, record.Owner); + Assert.True(body.AsSpan().SequenceEqual(record.Body.Span)); + channels.Add(record.Channel); + }, out var failure, out _), failure); + Assert.Equal(new[] { 101, 102, 103 }, channels); + + raw[TailOffsets(raw.Length)[^1] + 1] = 1; + Assert.False(PartitionFraming.WalkStream(stored, FramingTags(), 4, _ => { }, out failure, out _)); + Assert.Equal("page-framing", failure); + } + + private sealed class PageSizedReads(byte[] bytes) : MemoryStream(bytes, writable: false) + { + public override int Read(Span buffer) + { + Assert.InRange(buffer.Length, 1, PagedGzipStream.PageStride); + return base.Read(buffer); + } + } + [Fact] public void Walk_ChecksTheTagOfEveryPageTailBeforeItReadsARecord() { From 391ecf13d1d377d7901547c03cb7dd47cdbe8dd1 Mon Sep 17 00:00:00 2001 From: mahach666 <79989386+mahach666@users.noreply.github.com> Date: Sat, 5 Dec 2026 07:19:17 +0300 Subject: [PATCH 2/7] Preserve worksharing metadata and reuse downgrade buffers --- README.md | 2 + src/RvtIO/Parsing/PagedGzipStream.cs | 5 +- src/RvtIO/Parsing/PartitionFraming.cs | 11 ++- src/RvtIO/Parsing/R22Transcoder.cs | 66 +++++++++++----- src/RvtIO/Writing/ArchiveContents.cs | 46 +++++++++-- src/RvtIO/Writing/BasicFileInfoPatcher.cs | 37 ++++++--- .../Writing/DowngradePartitionRewriter.cs | 49 ++++++------ src/RvtIO/Writing/DowngradeWriter.cs | 14 ++-- src/RvtIO/Writing/ElementCensus.cs | 5 +- src/RvtIO/Writing/GzipMember.cs | 4 +- src/RvtIO/Writing/TagCellRewriter.cs | 10 +-- tests/RvtIO.Tests/ArchiveContentsTests.cs | 77 +++++++++++++++++-- tests/RvtIO.Tests/DowngradeWriterTests.cs | 18 ++++- tests/RvtIO.Tests/GzipMemberTests.cs | 11 +++ .../RvtIO.Tests/PartitionFramingFuzzTests.cs | 18 +++++ tests/RvtIO.Tests/R22TranscoderTests.cs | 12 +++ 16 files changed, 290 insertions(+), 95 deletions(-) diff --git a/README.md b/README.md index 940b22b2..923e787f 100644 --- a/README.md +++ b/README.md @@ -217,6 +217,8 @@ Older Revit releases cannot represent every newer record. A conversion with known omitted record owners requires `--allow-loss` and a JSON `--report`. The report lists affected record owners and known project and analytical omissions. When a report is requested, the CLI publishes the RVT after saving the report. +With a recognized archive header in both files, the writer converts the +source document storage index and keeps its worksharing data. Review the report and open the output in the target Revit release before relying on it. `--restore-legacy-analytics` applies only when writing Revit 2022 from a Revit 2023 or later project. It requires an earlier Revit 2022 revision of the diff --git a/src/RvtIO/Parsing/PagedGzipStream.cs b/src/RvtIO/Parsing/PagedGzipStream.cs index 5afe6a7b..2cb1fb95 100644 --- a/src/RvtIO/Parsing/PagedGzipStream.cs +++ b/src/RvtIO/Parsing/PagedGzipStream.cs @@ -64,13 +64,14 @@ internal static class PagedGzipStream if (body == null) return null; int start = IsGzipHeader(body, 0) ? 0 : IsGzipHeader(body, PrefixLength) ? PrefixLength : -1; if (start < 0) return null; - return Inflate(body, start); + return InflateMember(body, start); } /// Inflates one gzip member and requires its CRC-32 and length trailer right after the deflate data. /// GZipStream cannot be used: it does not fail on a member cut before the trailer. - private static byte[]? Inflate(byte[] body, int start) + internal static byte[]? InflateMember(byte[] body, int start) { + if (start < 0 || start > body.Length - 18 || !IsGzipHeader(body, start)) return null; int deflateStart = HeaderEnd(body, start); if (deflateStart < 0) return null; var inflater = new Inflater(noHeader: true); diff --git a/src/RvtIO/Parsing/PartitionFraming.cs b/src/RvtIO/Parsing/PartitionFraming.cs index 4c887a0c..e67e3ca8 100644 --- a/src/RvtIO/Parsing/PartitionFraming.cs +++ b/src/RvtIO/Parsing/PartitionFraming.cs @@ -100,12 +100,12 @@ internal sealed record BlockCallbacks(Action Begin, Action> Chain, Action End); internal static bool WalkStream(Stream stored, Tags tags, int idWidth, Action onRecord, - out string? failure, out int blocks, BlockCallbacks? onBlock = null) => - WalkCore(default, stored, tags, idWidth, onRecord, out failure, out blocks, null, null, onBlock); + out string? failure, out int blocks, BlockCallbacks? onBlock = null, MemoryStream? chainBuffer = null) => + WalkCore(default, stored, tags, idWidth, onRecord, out failure, out blocks, null, null, onBlock, chainBuffer); private static bool WalkCore(ReadOnlyMemory raw, Stream? stored, Tags tags, int idWidth, Action onRecord, out string? failure, out int blocks, List? segmentLengths, List? segmentBytes, - BlockCallbacks? onBlock = null) + BlockCallbacks? onBlock = null, MemoryStream? chainBuffer = null) { failure = null; blocks = 0; @@ -119,7 +119,10 @@ private static bool WalkCore(ReadOnlyMemory raw, Stream? stored, Tags tags using var prefetch = segmentBytes == null || OperatingSystem.IsBrowser() ? null : new SegmentPrefetch(tags); long inflated = 0; // output of all finished chains // One buffer for every chain of the stream: a chain is read by onRecord while it lies there and is gone with the next. - using var chain = new MemoryStream(); + using var ownedBuffer = chainBuffer is null ? new MemoryStream() : null; + var chain = chainBuffer ?? ownedBuffer!; + chain.SetLength(0); + chain.Position = 0; while (true) { Require(input.U16() == tags.ContentMarker, "content-marker"); diff --git a/src/RvtIO/Parsing/R22Transcoder.cs b/src/RvtIO/Parsing/R22Transcoder.cs index aecf0874..0263ff27 100644 --- a/src/RvtIO/Parsing/R22Transcoder.cs +++ b/src/RvtIO/Parsing/R22Transcoder.cs @@ -1,4 +1,5 @@ using System.Buffers.Binary; +using System.Runtime.InteropServices; using RvtIO.BuiltIns; namespace RvtIO.Parsing; @@ -550,7 +551,9 @@ private sealed class Context(byte[] data, int pos, int end) /// The 64-bit scalars being read take the place of 32-bit 2022 fields. public bool Narrow; /// The field being read ("Declaring.field"), for failure messages. - public string? Field; + public string? FieldName; + public string? FieldDeclaring; + public string FieldLocation => FieldName is null ? "" : " at " + (FieldDeclaring ?? "?") + "." + FieldName; /// The last ForgeTypeId text read (a parameter group type id). public string? LastForgeText; /// The built-in parameter group element id the current ParamDef names (its source has a type id instead). @@ -574,6 +577,11 @@ private sealed class Context(byte[] data, int pos, int end) /// The payload (class tag first) in the 2022 layout, or null when it cannot be rewritten. internal byte[]? Payload(byte[] data, int offset, int size) => Payload(data, offset, size, out _); + internal byte[]? Payload(ReadOnlyMemory data) => + MemoryMarshal.TryGetArray(data, out var segment) + ? Payload(segment.Array!, segment.Offset, segment.Count) + : Payload(data.ToArray(), 0, data.Length); + /// The payload in the 2022 layout with every byte after the object copied unchanged (a stream that holds one /// class object followed by opaque data), or null when the object cannot be rewritten. internal byte[]? PayloadWithTail(byte[] data, int offset, int size, out string? failure) @@ -649,7 +657,7 @@ private sealed class Context(byte[] data, int pos, int end) } catch (Fail fail) { - failure = _source[rootClass].Name + ": " + fail.Message + (c.Field is null ? "" : " at " + c.Field); + failure = _source[rootClass].Name + ": " + fail.Message + c.FieldLocation; return null; } try @@ -688,7 +696,7 @@ private sealed class Context(byte[] data, int pos, int end) } catch (Fail fail) { - failure = _source[rootClass].Name + ": " + fail.Message + (c.Field is null ? "" : " at " + c.Field); + failure = _source[rootClass].Name + ": " + fail.Message + c.FieldLocation; return null; } } @@ -756,7 +764,8 @@ private static void RekeyArchive(byte[] payload, List 0 ? c.ObjectStarts[0] : objectEnd; + if (n == 0) return Apply(c.D, offset, objectEnd, c.Edits); + int rootEnd = c.ObjectStarts[0]; var bySlot = new List[n + 1]; for (int i = 0; i <= n; i++) bySlot[i] = []; foreach (var edit in c.Edits) @@ -796,47 +805,64 @@ void Children(int slot) Children(-1); for (int i = 0; i < order.Count; i++) Children(order[i]); - using var output = new MemoryStream(); - output.Write(Apply(c.D, offset, rootEnd, bySlot[0])); + int length = EditedLength(rootEnd - offset, bySlot[0]); + foreach (int q in order) + { + int end = q + 1 < n ? c.ObjectStarts[q + 1] : objectEnd; + length = checked(length + EditedLength(end - c.ObjectStarts[q], bySlot[q + 1])); + } + var output = new byte[length]; + int written = ApplyTo(c.D, offset, rootEnd, bySlot[0], output); foreach (int q in order) { int start = c.ObjectStarts[q]; int end = q + 1 < n ? c.ObjectStarts[q + 1] : objectEnd; - output.Write(Apply(c.D, start, end, bySlot[q + 1])); + written += ApplyTo(c.D, start, end, bySlot[q + 1], output.AsSpan(written)); } - return output.ToArray(); + return output; + } + + private static int EditedLength(int length, List edits) + { + foreach (var edit in edits) + length = checked(length + edit.Replacement.Length - (edit.End - edit.Start)); + return length; } /// The bytes [start, end) with the edits applied (insertions sort before the replacement that starts at the same place). private static byte[] Apply(byte[] data, int start, int end, List edits) + { + var output = new byte[EditedLength(end - start, edits)]; + ApplyTo(data, start, end, edits, output); + return output; + } + + private static int ApplyTo(byte[] data, int start, int end, List edits, Span output) { // The edits are added as the bytes are read, so they come nearly in order: an insertion sort moves few of them, and // it keeps the order of equal ones as the ordering by two keys did. A loop also stays in compiled code in the // browser, where the ordering of a list of structs by its keys runs through the interpreter. var ordered = edits.ToArray(); - int growth = 0; for (int i = 0; i < ordered.Length; i++) { var edit = ordered[i]; - growth = checked(growth + edit.Replacement.Length - (edit.End - edit.Start)); int j = i - 1; for (; j >= 0 && After(ordered[j], edit); j--) ordered[j + 1] = ordered[j]; ordered[j + 1] = edit; } - var output = new byte[end - start + growth]; int at = 0, source = start; foreach (var e in ordered) { int gap = e.Start - source; if (gap < 0 || e.End > end) throw new Fail("overlapping edits"); - Buffer.BlockCopy(data, source, output, at, gap); + data.AsSpan(source, gap).CopyTo(output[at..]); at += gap; - Buffer.BlockCopy(e.Replacement, 0, output, at, e.Replacement.Length); + e.Replacement.AsSpan().CopyTo(output[at..]); at += e.Replacement.Length; source = e.End; } - Buffer.BlockCopy(data, source, output, at, end - source); - return output; + data.AsSpan(source, end - source).CopyTo(output[at..]); + return at + (end - source); // an edit that starts later, or a replacement against an insertion at the same place static bool After(Edit a, Edit b) => a.Start > b.Start || a.Start == b.Start && a.End > a.Start && !(b.End > b.Start); @@ -982,7 +1008,7 @@ private void ReadFields(Context c, int sourceClass, int depth) }); if (composeFields) c.NeedsValidation = true; int regionStart = c.Pos, regionEdits = c.Edits.Count; - var spans = new (int Start, int End, int EditFrom, int EditTo)[plan.Source.Length]; + var spans = composeFields ? new (int Start, int End, int EditFrom, int EditTo)[plan.Source.Length] : null; (byte First, byte Last)? includedBarEnds = null; Dictionary? browserOrganizations = null; string? esSpec = null; @@ -1047,7 +1073,6 @@ byte[] MissingField(int index) c.GroupElementId = ParameterGroupElementIds.GetValueOrDefault(cutGroup, -1); c.Edits.RemoveRange(editFrom, c.Edits.Count - editFrom); c.Edits.Add(new(start, c.Pos, [])); - spans[i] = (-1, -1, 0, 0); continue; } if (!composeFields) @@ -1077,7 +1102,7 @@ byte[] MissingField(int index) c.Narrow = false; if (depth == 0 && plan.Source[i].Declaring.Name == "ParamDef" && plan.Source[i].Field.Name == "m_groupTypeId" && c.LastForgeText is { } group) c.GroupElementId = ParameterGroupElementIds.GetValueOrDefault(group, -1); - spans[i] = (start, c.Pos, editFrom, c.Edits.Count); + if (spans != null) spans[i] = (start, c.Pos, editFrom, c.Edits.Count); if (c.Queue.Count != queued) { // the objects of the pointers follow in the order of the fields; at the top level @@ -1092,7 +1117,7 @@ byte[] MissingField(int index) lastQueuing = k; } } - if (!composeFields) + if (spans == null) { for (int j = last + 1; j < plan.Target.Length; j++) if (!plan.TargetPresent[j]) c.Edits.Add(new(c.Pos, c.Pos, MissingField(j), c.Slot)); @@ -1215,7 +1240,8 @@ private static int Take(Context c, int n) private void ReadField(Context c, string? declaring, SchemaField f, int depth) { - c.Field = (declaring ?? "?") + "." + f.Name; + c.FieldDeclaring = declaring; + c.FieldName = f.Name; int hi = f.Mods >> 4; if (hi == 6) { ReadScalar(c, declaring, f, depth); return; } if (hi == 1) diff --git a/src/RvtIO/Writing/ArchiveContents.cs b/src/RvtIO/Writing/ArchiveContents.cs index 88f0afb6..a5951d5b 100644 --- a/src/RvtIO/Writing/ArchiveContents.cs +++ b/src/RvtIO/Writing/ArchiveContents.cs @@ -1,34 +1,64 @@ using System.Buffers.Binary; +using RvtIO.Parsing; namespace RvtIO.Writing; /// -/// The Contents stream holds the archive version and a tagged -/// DocumentStorageIndex. A Revit release can share an archive version with -/// its predecessor while assigning a different class tag to the index. -/// The target profile supplies the compatible header and index together. +/// Rewrites the document storage index in Contents using the target archive header +/// and the source model's storage and worksharing metadata. /// internal static class ArchiveContents { internal const uint Magic = 0x05221962; private const int VersionOffset = 4; + private const int HeaderLength = 8; + private const string IndexClass = "DocumentStorageIndexImpl"; /// True when the bytes are an archive header and its version is read. internal static bool TryReadVersion(byte[]? contents, out uint version) { version = 0; - if (contents is null || contents.Length < VersionOffset + 4) return false; + if (contents is null || contents.Length < HeaderLength) return false; if (BinaryPrimitives.ReadUInt32LittleEndian(contents) != Magic) return false; version = BinaryPrimitives.ReadUInt32LittleEndian(contents.AsSpan(VersionOffset, 4)); return true; } - /// Uses a recognised profile header of the same or an older archive version. - internal static byte[]? ForTarget(byte[]? sourceContents, byte[]? profileContents) + internal static byte[]? ForTarget(byte[]? sourceContents, byte[]? profileContents, + SchemaDocument sourceDoc, SchemaDocument targetDoc, R22Transcoder transcoder) { if (!TryReadVersion(profileContents, out uint target)) return sourceContents; if (!TryReadVersion(sourceContents, out uint source)) return null; - return target <= source ? profileContents : sourceContents; + if (target > source) return sourceContents; + + var (sourceIndex, _) = ReadIndex(sourceContents!, sourceDoc, "source"); + var (_, targetHeader) = ReadIndex(profileContents!, targetDoc, "target profile"); + byte[]? index = transcoder.PayloadWithTail(sourceIndex, 0, sourceIndex.Length, out string? failure); + if (index is null) + throw new DowngradeRefusedException("contents-transcode-failed", + $"Contents cannot be rewritten for the target release: {failure}"); + + return PageCodec.EncodePadded([.. targetHeader, .. GzipMember.Write(index)]); + } + + private static (byte[] Index, byte[] Header) ReadIndex(byte[] stored, SchemaDocument document, string role) + { + if (PageCodec.Verify(stored).Status is PageCheckStatus.BadPage or PageCheckStatus.BadTail) + throw new DowngradeRefusedException("contents-transcode-failed", $"Contents in the {role} fails page parity."); + byte[]? body = PagedGzipStream.RemoveSegments(stored) ?? PagedGzipStream.RemoveSegments(stored, tolerateTail: true); + if (body != null) + { + int offset = body.AsSpan(HeaderLength).IndexOf((ReadOnlySpan)[0x1F, 0x8B, 8, 0, 0, 0, 0, 0, 0, 0x0B]); + if (offset >= 0) + { + offset += HeaderLength; + byte[]? index = PagedGzipStream.InflateMember(body, offset); + var indexClass = document.Classes.FirstOrDefault(c => c.Name == IndexClass); + if (index is { Length: >= sizeof(ushort) } && indexClass?.Id == BinaryPrimitives.ReadUInt16LittleEndian(index)) + return (index, body[..offset]); + } + } + throw new DowngradeRefusedException("contents-transcode-failed", $"The document storage index in Contents of the {role} could not be read."); } } diff --git a/src/RvtIO/Writing/BasicFileInfoPatcher.cs b/src/RvtIO/Writing/BasicFileInfoPatcher.cs index 3cab6de2..f40dd5d3 100644 --- a/src/RvtIO/Writing/BasicFileInfoPatcher.cs +++ b/src/RvtIO/Writing/BasicFileInfoPatcher.cs @@ -4,8 +4,8 @@ namespace RvtIO.Writing; /// -/// Patches the raw bytes of the BasicFileInfo stream when a file is downgraded: every UTF-16LE -/// occurrence of the source release year becomes the target year, the stream version dword and the build +/// Patches the raw bytes of the BasicFileInfo stream when a file is downgraded: release years +/// outside saved and central model paths become the target year, the stream version dword and the build /// string are taken from the profile file, and the length-prefixed UTF-16 build value is re-written with /// its own length prefix (so a profile build of another length is accepted and the following values shift). /// The key-value text block of the stream is free text and is patched in place. @@ -17,7 +17,12 @@ internal static byte[] Patch(byte[] data, int sourceRelease, int targetRelease, string from = sourceRelease.ToString(System.Globalization.CultureInfo.InvariantCulture); string to = targetRelease.ToString(System.Globalization.CultureInfo.InvariantCulture); if (from.Length != 4 || to.Length != 4) throw new ArgumentException("Releases must be four-digit years."); - byte[] patched = from == to ? [.. data] : ReplaceAll(data, Encoding.Unicode.GetBytes(from), Encoding.Unicode.GetBytes(to), required: true); + var sourceFields = Parsing.BasicFileInfoReader.Parse(data); + byte[][] paths = [.. new[] { "LastSavePath", "Last Save Path", "Central Model Path" } + .Select(key => sourceFields.GetValueOrDefault(key)).OfType().Where(path => path.Length != 0) + .Distinct(StringComparer.Ordinal).Select(Encoding.Unicode.GetBytes)]; + byte[] patched = from == to ? [.. data] : ReplaceAll(data, Encoding.Unicode.GetBytes(from), + Encoding.Unicode.GetBytes(to), paths, required: true); if (profileData is not null) { @@ -29,13 +34,14 @@ internal static byte[] Patch(byte[] data, int sourceRelease, int targetRelease, BinaryPrimitives.WriteInt32LittleEndian(patched.AsSpan(0, 4), streamVersionValue); } - string? sourceBuild = Parsing.BasicFileInfoReader.Parse(data).GetValueOrDefault("Build"); + string? sourceBuild = sourceFields.GetValueOrDefault("Build"); if (profileFields.TryGetValue("Build", out string? profileBuild) && sourceBuild is not null && profileBuild != sourceBuild) { // The standalone value: [i32 length][UTF-16 chars]; the length prefix is rewritten with it. patched = ReplaceLengthPrefixed(patched, sourceBuild, profileBuild); // Any occurrence in the trailing key-value text block. - patched = ReplaceAll(patched, Encoding.Unicode.GetBytes(sourceBuild), Encoding.Unicode.GetBytes(profileBuild), required: false); + patched = ReplaceAll(patched, Encoding.Unicode.GetBytes(sourceBuild), + Encoding.Unicode.GetBytes(profileBuild), paths, required: false); } } @@ -65,19 +71,28 @@ private static byte[] ReplaceLengthPrefixed(byte[] data, string oldText, string return data; } - private static byte[] ReplaceAll(byte[] data, byte[] oldBytes, byte[] newBytes, bool required) + private static byte[] ReplaceAll(byte[] data, byte[] oldBytes, byte[] newBytes, byte[][] paths, bool required) { - var patched = new byte[data.Length]; - Buffer.BlockCopy(data, 0, patched, 0, data.Length); + var pathRanges = new List<(int Start, int End)>(); + foreach (byte[] path in paths) + for (int start = IndexOf(data, path, 0); start >= 0; start = IndexOf(data, path, start + path.Length)) + pathRanges.Add((start, start + path.Length)); + + using var output = new MemoryStream(data.Length); int replacements = 0; - for (int at = IndexOf(patched, oldBytes, 0); at >= 0; at = IndexOf(patched, oldBytes, at + newBytes.Length)) + int copied = 0; + for (int at = IndexOf(data, oldBytes, 0); at >= 0; at = IndexOf(data, oldBytes, at + oldBytes.Length)) { - newBytes.CopyTo(patched, at); + if (pathRanges.Any(path => at < path.End && at + oldBytes.Length > path.Start)) continue; + output.Write(data.AsSpan(copied, at - copied)); + output.Write(newBytes); + copied = at + oldBytes.Length; replacements++; } if (replacements == 0 && required) throw new InvalidDataException($"BasicFileInfo holds no expected '{Encoding.Unicode.GetString(oldBytes)}' value to patch."); - return patched; + output.Write(data.AsSpan(copied)); + return output.ToArray(); } private static int IndexOf(byte[] haystack, byte[] needle, int start) diff --git a/src/RvtIO/Writing/DowngradePartitionRewriter.cs b/src/RvtIO/Writing/DowngradePartitionRewriter.cs index 7547c177..43d3d012 100644 --- a/src/RvtIO/Writing/DowngradePartitionRewriter.cs +++ b/src/RvtIO/Writing/DowngradePartitionRewriter.cs @@ -1,4 +1,5 @@ using System.Buffers.Binary; +using System.IO.Compression; using ICSharpCode.SharpZipLib.Checksum; using RvtIO.Parsing; @@ -24,13 +25,13 @@ internal sealed record ProjectEdits( IReadOnlyList Additions, IReadOnlyDictionary<(ulong Owner, int Channel), byte[]> Replacements); internal static ContainerEntry Rewrite( - Stream stored, Stream destination, + Stream stored, Stream destination, MemoryStream chainBuffer, PartitionFraming.Tags sourceTags, int sourceWidth, PartitionFraming.Tags targetTags, int targetWidth, R22Transcoder transcoder, IReadOnlySet knownDropped, IReadOnlyDictionary keptCounts, - Func? tagFixer, + Func, byte[], byte[]?>? tagFixer, ProjectEdits? projectEdits = null) { if (sourceWidth is not (4 or 8) || targetWidth is not (4 or 8)) @@ -72,7 +73,7 @@ internal static ContainerEntry Rewrite( BinaryPrimitives.WriteUInt16LittleEndian(signature, targetTags.SignatureMarker); output.Write(signature); }); - if (!PartitionFraming.WalkStream(stored, sourceTags, sourceWidth, _ => { }, out var sourceFailure, out _, blocks)) + if (!PartitionFraming.WalkStream(stored, sourceTags, sourceWidth, _ => { }, out var sourceFailure, out _, blocks, chainBuffer)) throw new InvalidDataException($"Partition stream framing is invalid: {sourceFailure}."); WriteHeader("", uint.MaxValue); @@ -93,7 +94,7 @@ internal static ContainerEntry Rewrite( else adler.Update(record.Body.ToArray()); if ((uint)adler.Value != record.Extra) throw new InvalidDataException($"Rewritten record (block {record.Block}, channel {record.Channel}, owner {record.Owner}) has a mismatched Adler-32 checksum."); - }, out string? failure, out _); + }, out string? failure, out _, chainBuffer: chainBuffer); if (!ok) throw new InvalidDataException($"Rewritten partition stream failed framing verification: {failure}."); return entry; @@ -119,7 +120,7 @@ void WriteHeader(string key, uint owners) internal sealed record PartitionState(HashSet Owners, HashSet Dropped); internal static PartitionState Inspect( - Stream stored, PartitionFraming.Tags tags, int width, R22Transcoder transcoder, + Stream stored, PartitionFraming.Tags tags, int width, R22Transcoder transcoder, MemoryStream chainBuffer, IReadOnlySet? knownDropped = null, Dictionary? keptCounts = null) { ulong terminator = width == 8 ? ulong.MaxValue : uint.MaxValue; @@ -152,18 +153,14 @@ internal static PartitionState Inspect( if (transcoder.HasSourceClass(tag)) { shouldDrop = !transcoder.CanWriteRecord(tag, isElement); - if (!shouldDrop) - { - byte[] body = record.Body.ToArray(); - shouldDrop = transcoder.Payload(body, 0, body.Length, out _) is null; - } + if (!shouldDrop) shouldDrop = transcoder.Payload(record.Body) is null; } if (shouldDrop) { blockDropped.Add(record.Owner); dropped.Add(record.Owner); } - }, out var failure, out _)) + }, out var failure, out _, chainBuffer: chainBuffer)) throw new InvalidDataException($"Partition stream framing is invalid: {failure}."); if (countKept && block >= 0) keptCounts![block] = (uint)kept.Count; return new PartitionState(owners, dropped); @@ -181,7 +178,7 @@ private static void WriteConvertedChain( ulong sourceTerminator, ulong targetTerminator, IReadOnlySet dropOwners, - Func? tagFixer, + Func, byte[], byte[]?>? tagFixer, ProjectEdits? projectEdits, HashSet addedChannels, HashSet<(ulong, int)> replacedRecords) @@ -194,7 +191,8 @@ private static void WriteConvertedChain( void FlushBatch() { if (batchCount == 0) return; - WriteSegment(output, targetTags, chain.UpperFlags, batchCount, checked((uint)batchBodyBytes), (uint)chain.Channel, chain.Opaque, batch.ToArray()); + WriteSegment(output, targetTags, chain.UpperFlags, batchCount, checked((uint)batchBodyBytes), + (uint)chain.Channel, chain.Opaque, batch.GetBuffer().AsSpan(0, (int)batch.Length)); batch.SetLength(0); batch.Position = 0; batchCount = 0; @@ -257,7 +255,7 @@ void FlushBatch() throw new DowngradeRefusedException("id-beyond-32-bits", $"Element id {owner} does not fit in 32 bits and cannot be downgraded to a 4-byte release."); newOwner = owner; - var rawBody = inf.Slice(bodyAt, bodySize); + var rawBody = chain.Inflated.Slice(bodyAt, bodySize); byte[]? converted; if (projectEdits?.Replacements.TryGetValue((owner, chain.Channel), out var edit) == true) { @@ -266,9 +264,8 @@ void FlushBatch() } else { - byte[] body = rawBody.ToArray(); - converted = bodySize >= 2 ? transcoder.Payload(body, 0, bodySize, out _) : null; - if (converted is not null && tagFixer is not null && tagFixer(body, converted) is { } fixedBody) + converted = bodySize >= 2 ? transcoder.Payload(rawBody) : null; + if (converted is not null && tagFixer is not null && tagFixer(rawBody, converted) is { } fixedBody) converted = fixedBody; } if (converted == null) @@ -276,7 +273,7 @@ void FlushBatch() // A body that cannot be rewritten on its own (an unknown nested structure) keeps its bytes // behind an unknown class tag; the element stays framed and is left out by readers. converted = new byte[bodySize >= 2 ? bodySize : 2]; - if (bodySize >= 2) rawBody[2..].CopyTo(converted.AsSpan(2)); + if (bodySize >= 2) rawBody.Span[2..].CopyTo(converted.AsSpan(2)); BinaryPrimitives.WriteUInt16LittleEndian(converted.AsSpan(0, 2), R22Transcoder.UnknownTag); } newBody = converted; @@ -296,13 +293,13 @@ void FlushBatch() void WriteRecord(ulong owner, byte[] recordBody, uint checksum) { bool hasExtra = chain.Channel != 101; - byte[] header = new byte[targetWidth + (hasExtra ? 4 : 0) + 4]; + Span header = stackalloc byte[targetWidth + (hasExtra ? 4 : 0) + 4]; int hp = 0; - if (targetWidth == 8) { BinaryPrimitives.WriteUInt64LittleEndian(header.AsSpan(hp, 8), owner); hp += 8; } - else { BinaryPrimitives.WriteUInt32LittleEndian(header.AsSpan(hp, 4), (uint)owner); hp += 4; } - if (hasExtra) { BinaryPrimitives.WriteUInt32LittleEndian(header.AsSpan(hp, 4), checksum); hp += 4; } - BinaryPrimitives.WriteUInt32LittleEndian(header.AsSpan(hp, 4), (uint)recordBody.Length); - byte[] footer = new byte[4]; + if (targetWidth == 8) { BinaryPrimitives.WriteUInt64LittleEndian(header, owner); hp += 8; } + else { BinaryPrimitives.WriteUInt32LittleEndian(header, (uint)owner); hp += 4; } + if (hasExtra) { BinaryPrimitives.WriteUInt32LittleEndian(header[hp..], checksum); hp += 4; } + BinaryPrimitives.WriteUInt32LittleEndian(header[hp..], (uint)recordBody.Length); + Span footer = stackalloc byte[4]; BinaryPrimitives.WriteUInt32LittleEndian(footer, (uint)recordBody.Length); int itemLength = header.Length + recordBody.Length + 4; @@ -338,7 +335,7 @@ private static void WriteSplitRecord( int offset = MaxSegmentBodyBytes; while (recordBody.Length - offset > MaxSegmentBodyBytes) { - byte[] middleSlice = recordBody.Slice(offset, MaxSegmentBodyBytes).ToArray(); + ReadOnlySpan middleSlice = recordBody.Slice(offset, MaxSegmentBodyBytes); WriteSegment(output, tags, chain.UpperFlags | 3u, 0u, MaxSegmentBodyBytes, (uint)chain.Channel, chain.Opaque, middleSlice); offset += MaxSegmentBodyBytes; } @@ -360,7 +357,7 @@ private static void WriteSegment( uint opaque, ReadOnlySpan inflatedBytes) { - byte[] gzPayload = GzipMember.Write(inflatedBytes); + byte[] gzPayload = GzipMember.Write(inflatedBytes, CompressionLevel.Optimal); uint segmentSize = checked((uint)(gzPayload.Length + 8)); Span header = stackalloc byte[26]; diff --git a/src/RvtIO/Writing/DowngradeWriter.cs b/src/RvtIO/Writing/DowngradeWriter.cs index 3fe19b9a..8be28023 100644 --- a/src/RvtIO/Writing/DowngradeWriter.cs +++ b/src/RvtIO/Writing/DowngradeWriter.cs @@ -137,10 +137,11 @@ private static DowngradeWriteResult Transcode( // Clear references at the same transition as the omission, while their old owners are known. var knownOwners = new HashSet(); var knownDropped = new HashSet(); + using var chainBuffer = new MemoryStream(); foreach (var (_, open) in sourcePartitions) { using var partition = open(); - var state = DowngradePartitionRewriter.Inspect(partition, sourceTags, sourceWidth, transcoder); + var state = DowngradePartitionRewriter.Inspect(partition, sourceTags, sourceWidth, transcoder, chainBuffer); knownOwners.UnionWith(state.Owners); knownDropped.UnionWith(state.Dropped); } @@ -177,7 +178,7 @@ private static DowngradeWriteResult Transcode( { using var partition = open(); var ownersByBlock = new Dictionary(); - var restate = DowngradePartitionRewriter.Inspect(partition, sourceTags, sourceWidth, transcoder, + var restate = DowngradePartitionRewriter.Inspect(partition, sourceTags, sourceWidth, transcoder, chainBuffer, knownDropped, ownersByBlock); survivingOwnersByPartition.Add(path, ownersByBlock); knownOwners.UnionWith(restate.Owners); @@ -232,7 +233,8 @@ private static DowngradeWriteResult Transcode( ["Formats/Latest"] = profileStored, ["BasicFileInfo"] = patchedBfi, }; - if (ArchiveContents.ForTarget(sourceContents, profileContents) is { } contents && contents != sourceContents) + if (ArchiveContents.ForTarget(sourceContents, profileContents, sourceDoc, profileDoc, transcoder) is { } contents + && contents != sourceContents) replacements["Contents"] = contents; // Single-object Global streams: transcode the class object by class and field name. // A stream that does not open with a class of the source schema holds no class object @@ -486,7 +488,7 @@ private static DowngradeWriteResult Transcode( Dictionary? omittedProjectElements = null; if (droppedOwners.Count != 0 || planResult.TargetRelease <= 2022) { - omittedProjectElements = ElementCensus.CountByClass(sourceRoot, sourceDoc, out _, droppedOwners); + omittedProjectElements = ElementCensus.CountByClass(sourceRoot, sourceDoc, out _, droppedOwners, chainBuffer); } var omittedOwners = new HashSet(droppedOwners); if (restored is not null) @@ -533,12 +535,12 @@ ContainerEntry RewritePartition(string path, Func open, Stream destinati { // The last planning pass used the drop set from before the last update. keptCounts.Clear(); - var state = DowngradePartitionRewriter.Inspect(partition, sourceTags, sourceWidth, transcoder, + var state = DowngradePartitionRewriter.Inspect(partition, sourceTags, sourceWidth, transcoder, chainBuffer, knownDropped, keptCounts); if (!state.Dropped.IsSubsetOf(knownDropped)) throw new InvalidDataException("Additional omitted elements were detected after writing the element table."); } - return DowngradePartitionRewriter.Rewrite(partition, destination, sourceTags, sourceWidth, + return DowngradePartitionRewriter.Rewrite(partition, destination, chainBuffer, sourceTags, sourceWidth, targetTags, targetWidth, transcoder, knownDropped, keptCounts, tagFixer, edits); } catch (Exception exception) when (exception is InvalidDataException or ArgumentException or OverflowException) diff --git a/src/RvtIO/Writing/ElementCensus.cs b/src/RvtIO/Writing/ElementCensus.cs index c3a19c6e..4ea45762 100644 --- a/src/RvtIO/Writing/ElementCensus.cs +++ b/src/RvtIO/Writing/ElementCensus.cs @@ -15,7 +15,8 @@ internal static class ElementCensus /// Elements per class name, or null with the reason in when the count cannot be made from this /// file's layout: the class table has no framing classes, the id width is not known, or there is no partition stream. /// A partition stream is present but its framing does not hold or a record has no class tag. - internal static Dictionary? CountByClass(RootStorage root, SchemaDocument document, out string? failure, IReadOnlySet? onlyOwners = null) + internal static Dictionary? CountByClass(RootStorage root, SchemaDocument document, + out string? failure, IReadOnlySet? onlyOwners = null, MemoryStream? chainBuffer = null) { failure = null; var schema = new FormatsSchema(document); @@ -41,7 +42,7 @@ internal static class ElementCensus || onlyOwners is not null && !onlyOwners.Contains(record.Owner)) return; if (record.Body.Length < 2) { bad = true; return; } tagOfOwner[record.Owner] = BinaryPrimitives.ReadUInt16LittleEndian(record.Body.Span); - }, out string? walkFailure, out _); + }, out string? walkFailure, out _, chainBuffer: chainBuffer); if (!ok) throw new RvtInputException("truncated-or-damaged", $"Partition stream {name} is damaged: its framing does not hold ({walkFailure})."); if (bad) throw new RvtInputException("truncated-or-damaged", $"Partition stream {name} is damaged: it holds a record without a class tag."); } diff --git a/src/RvtIO/Writing/GzipMember.cs b/src/RvtIO/Writing/GzipMember.cs index c893af22..e7bbf3d1 100644 --- a/src/RvtIO/Writing/GzipMember.cs +++ b/src/RvtIO/Writing/GzipMember.cs @@ -21,14 +21,14 @@ internal static class GzipMember private static readonly byte[] EmptyDeflate = [0x03, 0x00]; /// The gzip member that inflates to . - internal static byte[] Write(ReadOnlySpan data) + internal static byte[] Write(ReadOnlySpan data, CompressionLevel compression = CompressionLevel.SmallestSize) { using var stream = new MemoryStream(); stream.Write(Header); if (data.IsEmpty) stream.Write(EmptyDeflate); // DeflateStream writes nothing at all for empty input on some runtimes else - using (var deflate = new DeflateStream(stream, CompressionLevel.SmallestSize, leaveOpen: true)) + using (var deflate = new DeflateStream(stream, compression, leaveOpen: true)) deflate.Write(data); var crc = new Crc32(); crc.Update(data.ToArray()); diff --git a/src/RvtIO/Writing/TagCellRewriter.cs b/src/RvtIO/Writing/TagCellRewriter.cs index 51c02bac..5a99dc2f 100644 --- a/src/RvtIO/Writing/TagCellRewriter.cs +++ b/src/RvtIO/Writing/TagCellRewriter.cs @@ -14,7 +14,7 @@ namespace RvtIO.Writing; /// internal static class TagCellRewriter { - internal static Func? Create( + internal static Func, byte[], byte[]?>? Create( SchemaDocument sourceDoc, SchemaDocument targetDoc, IReadOnlyDictionary? entitySchemas, int sourceWidth) { var target = new FormatsSchema(targetDoc); @@ -25,8 +25,8 @@ internal static class TagCellRewriter sourceDoc.Classes.FirstOrDefault(c => c.Name == "FabricReinSpanSymbol") is { } fabricSymbol && !sourceDoc.Classes.Any(c => c.Name == "IndependentTag" && c.Fields.Any(f => f.Name == "m_taggedElementId"))) return (source, generic) => source.Length >= sizeof(ushort) && - BinaryPrimitives.ReadUInt16LittleEndian(source) == fabricSymbol.Id - ? RewriteFabricHost(source, generic, sourceDoc, targetDoc, entitySchemas, sourceWidth, fabricSymbol.Id) + BinaryPrimitives.ReadUInt16LittleEndian(source.Span) == fabricSymbol.Id + ? RewriteFabricHost(source.ToArray(), generic, sourceDoc, targetDoc, entitySchemas, sourceWidth, fabricSymbol.Id) : null; if (tag.Fields.All(f => f.Name != "m_taggedEntitiesCell") || target.Get("TaggedEntitiesCell") is not { } targetCell || @@ -37,8 +37,8 @@ internal static class TagCellRewriter var sourceWalker = new WideBlockWalker(sourceDoc, (d, f) => d.Name + "." + f.Name, []); if (entitySchemas is not null) sourceWalker.UseEntitySchemas(entitySchemas, passUnknown: true); var tags = sourceDoc.Classes.Where(c => sourceWalker.IsA(c.Id, "IndependentTag")).Select(c => c.Id).ToHashSet(); - return (source, generic) => source.Length >= sizeof(ushort) && tags.Contains(BinaryPrimitives.ReadUInt16LittleEndian(source)) - ? Rewrite(source, generic, sourceWalker, targetDoc, transcoder, targetCell, (ushort)taggedElem.Id) + return (source, generic) => source.Length >= sizeof(ushort) && tags.Contains(BinaryPrimitives.ReadUInt16LittleEndian(source.Span)) + ? Rewrite(source.ToArray(), generic, sourceWalker, targetDoc, transcoder, targetCell, (ushort)taggedElem.Id) : null; } diff --git a/tests/RvtIO.Tests/ArchiveContentsTests.cs b/tests/RvtIO.Tests/ArchiveContentsTests.cs index ba4ebc61..0f137a5f 100644 --- a/tests/RvtIO.Tests/ArchiveContentsTests.cs +++ b/tests/RvtIO.Tests/ArchiveContentsTests.cs @@ -1,4 +1,5 @@ using System.Buffers.Binary; +using RvtIO.Parsing; using RvtIO.Writing; using Xunit; @@ -6,6 +7,22 @@ namespace RvtIO.Tests; public sealed class ArchiveContentsTests { + private static SchemaDocument IndexSchema(ushort tag) => new() + { + Classes = + [ + new(tag, "DocumentStorageIndexImpl", 0, 1, + [new("m_bSingleUser", 1, 0, 0, null, null, null, null)], []) + ] + }; + + private static byte[] Index(ushort tag, byte singleUser, byte trailing) + { + byte[] index = [0, 0, singleUser, trailing, 0, 0, 0]; + BinaryPrimitives.WriteUInt16LittleEndian(index, tag); + return index; + } + private static byte[] Header(uint version, byte marker = 0) { var bytes = new byte[12]; @@ -18,12 +35,20 @@ private static byte[] Header(uint version, byte marker = 0) [Theory] [InlineData(26u)] [InlineData(31u)] - public void ForTarget_TakesTheProfileHeader_WhenItsVersionIsOlderOrEqual(uint targetVersion) + public void ForTarget_KeepsSourceIndexWithTargetHeader_WhenItsVersionIsOlderOrEqual(uint targetVersion) { - byte[] source = Header(31, 1); - byte[] profile = Header(targetVersion, 2); + var sourceDoc = IndexSchema(1342); + var targetDoc = IndexSchema(1285); + byte[] targetHeader = Header(targetVersion, 2); + byte[] source = PageCodec.EncodePadded([.. Header(31, 1), .. GzipMember.Write(Index(1342, 0, 3))]); + byte[] profile = PageCodec.EncodePadded([.. targetHeader, .. GzipMember.Write(Index(1285, 1, 4))]); - Assert.Same(profile, ArchiveContents.ForTarget(source, profile)); + byte[] rewritten = Assert.IsType(ArchiveContents.ForTarget(source, profile, sourceDoc, targetDoc, + new(sourceDoc, targetDoc, 8))); + + Assert.Equal(PageCheckStatus.Valid, PageCodec.Verify(rewritten).Status); + Assert.Equal(targetHeader, rewritten[..targetHeader.Length]); + Assert.Equal(Index(1285, 0, 3), PagedGzipStream.InflateMember(rewritten, targetHeader.Length)); } [Fact] @@ -31,17 +56,53 @@ public void ForTarget_KeepsTheSourceHeader_WhenTheProfileIsNewer() { byte[] source = Header(26, 1); byte[] profile = Header(27, 2); + var doc = IndexSchema(1285); - Assert.Same(source, ArchiveContents.ForTarget(source, profile)); + Assert.Same(source, ArchiveContents.ForTarget(source, profile, doc, doc, new(doc, doc, 8))); } [Fact] public void ForTarget_WithoutAProfileHeader_KeepsTheSourceHeader() { byte[] source = Header(31); - Assert.Same(source, ArchiveContents.ForTarget(source, null)); - Assert.Null(ArchiveContents.ForTarget(null, Header(26))); - Assert.Null(ArchiveContents.ForTarget([1, 2, 3], Header(26))); + var doc = IndexSchema(1285); + var transcoder = new R22Transcoder(doc, doc, 8); + Assert.Same(source, ArchiveContents.ForTarget(source, null, doc, doc, transcoder)); + Assert.Null(ArchiveContents.ForTarget(null, Header(26), doc, doc, transcoder)); + Assert.Null(ArchiveContents.ForTarget([1, 2, 3], Header(26), doc, doc, transcoder)); + } + + [Fact] + public void ForTarget_RefusesACorruptSourceIndex() + { + var doc = IndexSchema(1285); + byte[] member = GzipMember.Write(Index(1285, 0, 3)); + member[^8] ^= 1; + byte[] source = PageCodec.EncodePadded([.. Header(31), .. member]); + byte[] profile = PageCodec.EncodePadded([.. Header(26), .. GzipMember.Write(Index(1285, 1, 4))]); + + Assert.Throws( + () => ArchiveContents.ForTarget(source, profile, doc, doc, new(doc, doc, 8))); + } + + [Fact] + public void ForTarget_RewritesAnIndexAcrossSeveralPages() + { + var sourceDoc = IndexSchema(1342); + var targetDoc = IndexSchema(1285); + byte[] trailing = new byte[3 * PagedGzipStream.PageDataLength]; + new Random(26).NextBytes(trailing); + byte[] source = PageCodec.EncodePadded([.. Header(28), .. GzipMember.Write([.. Index(1342, 0, 3), .. trailing])]); + byte[] profile = PageCodec.EncodePadded([.. Header(27), .. GzipMember.Write(Index(1285, 1, 4))]); + Assert.True(source.Length > 2 * PagedGzipStream.PageStride); + + byte[] result = Assert.IsType(ArchiveContents.ForTarget(source, profile, sourceDoc, targetDoc, + new(sourceDoc, targetDoc, 8))); + + Assert.Equal(PageCheckStatus.Valid, PageCodec.Verify(result).Status); + byte[] logical = Assert.IsType(PagedGzipStream.RemoveSegments(result)); + Assert.Equal(Header(27), logical[..12]); + Assert.Equal([.. Index(1285, 0, 3), .. trailing], PagedGzipStream.InflateMember(logical, 12)); } [Fact] diff --git a/tests/RvtIO.Tests/DowngradeWriterTests.cs b/tests/RvtIO.Tests/DowngradeWriterTests.cs index e39ae24a..f097c902 100644 --- a/tests/RvtIO.Tests/DowngradeWriterTests.cs +++ b/tests/RvtIO.Tests/DowngradeWriterTests.cs @@ -380,7 +380,7 @@ private string Synthetic(int release, string name, bool includeElemTable = false } [Fact] - public void BasicFileInfoPatcher_ReplacesEveryYearOccurrence_KeepingLength() + public void BasicFileInfoPatcher_RewritesReleaseFields_KeepingLength() { byte[] data = RvtWriterTests.BuildBasicFileInfoBytes(2026); byte[] patched = BasicFileInfoPatcher.Patch(data, 2026, 2025); @@ -391,6 +391,22 @@ public void BasicFileInfoPatcher_ReplacesEveryYearOccurrence_KeepingLength() Assert.DoesNotContain(Encoding.Unicode.GetBytes("2026"), patched); } + [Fact] + public void BasicFileInfoPatcher_PreservesModelPathsThatContainTheReleaseYear() + { + const string central = @"C:\Models\2026\Central.rvt"; + const string local = @"D:\Copies\Hospital-2026.rvt"; + byte[] data = RvtWriterTests.BuildBasicFileInfoBytes(2026, worksharing: "File-Based Central", + centralPath: central, lastSavePath: local); + + byte[] patched = BasicFileInfoPatcher.Patch(data, 2026, 2024); + + var info = BasicFileInfoReader.Parse(patched); + Assert.Equal("2024", info["RevitVersion"]); + Assert.Equal(central, info["Central Model Path"]); + Assert.Equal(local, info["LastSavePath"]); + } + [Fact] public void Write_SameWidth_LowersBasicFileInfo_AndReplanningGivesNoEdits() { diff --git a/tests/RvtIO.Tests/GzipMemberTests.cs b/tests/RvtIO.Tests/GzipMemberTests.cs index 81601e5e..f0a41d28 100644 --- a/tests/RvtIO.Tests/GzipMemberTests.cs +++ b/tests/RvtIO.Tests/GzipMemberTests.cs @@ -75,6 +75,17 @@ public void Write_Compresses() Assert.True(GzipMember.Write(data).Length < data.Length / 2); } + [Fact] + public void Write_OptimalCompressionKeepsTheFixedMemberFormat() + { + byte[] data = Compressible(131_072, 6); + byte[] member = GzipMember.Write(data, CompressionLevel.Optimal); + + Assert.Equal(Header, member[..GzipMember.HeaderLength]); + Assert.Equal(Crc32(data), BinaryPrimitives.ReadUInt32LittleEndian(member.AsSpan(member.Length - 8))); + Assert.Equal(data, Inflate(member)); + } + [Theory] [MemberData(nameof(Inputs))] public void ReaderDecodesTheMemberInAPagedStream_WithAndWithoutThePrefixOfAGlobalStream(byte[] data) diff --git a/tests/RvtIO.Tests/PartitionFramingFuzzTests.cs b/tests/RvtIO.Tests/PartitionFramingFuzzTests.cs index a1ba1ee2..0c71afe9 100644 --- a/tests/RvtIO.Tests/PartitionFramingFuzzTests.cs +++ b/tests/RvtIO.Tests/PartitionFramingFuzzTests.cs @@ -119,6 +119,24 @@ public void Walk_StreamReadsPageSizedRangesAndChecksTailsAfterTheTerminal() Assert.Equal("page-framing", failure); } + [Fact] + public void WalkStream_ReusesTheBorrowedChainBuffer() + { + using var input = new PageSizedReads(WithTails(LargePayload())); + using var chain = new MemoryStream(); + chain.WriteByte(42); + Assert.True(PartitionFraming.WalkStream(input, FramingTags(), 4, _ => { }, out var failure, out _, + chainBuffer: chain), failure); + byte[] first = chain.GetBuffer(); + Assert.NotEmpty(first); + + int records = 0; + Assert.True(PartitionFraming.WalkStream(input, FramingTags(), 4, _ => records++, out failure, out _, + chainBuffer: chain), failure); + Assert.Equal(3, records); + Assert.Same(first, chain.GetBuffer()); + } + private sealed class PageSizedReads(byte[] bytes) : MemoryStream(bytes, writable: false) { public override int Read(Span buffer) diff --git a/tests/RvtIO.Tests/R22TranscoderTests.cs b/tests/RvtIO.Tests/R22TranscoderTests.cs index 75e39c76..313258ea 100644 --- a/tests/RvtIO.Tests/R22TranscoderTests.cs +++ b/tests/RvtIO.Tests/R22TranscoderTests.cs @@ -119,6 +119,8 @@ public void Payload_RenumbersCutsInsertsAndLeavesOutUnknownObjects() var transcoder = new R22Transcoder(Source(), Target(), 8); var result = transcoder.Payload(block, 0, block.Length); Assert.Equal(expected, result); + byte[] framed = [0xCC, 0xDD, .. block, 0xEE]; + Assert.Equal(expected, transcoder.Payload(framed.AsMemory(2, block.Length))); var walk = new WideBlockWalker(Target(), (_, _) => null, []).Run(result!, 0, result!.Length, 11); Assert.True(walk.Exact, walk.Error); } @@ -164,6 +166,16 @@ public void Payload_WritesFieldsInTheOrderOfThe2022Class() Assert.Equal(expected, new R22Transcoder(Source(), Target(), 8).Payload(block, 0, block.Length)); } + [Fact] + public void Payload_ReportsTheFieldThatWasCutOff() + { + var block = Bytes(w => { w.Write((ushort)6); w.Write(1); }); + var transcoder = new R22Transcoder(Source(), Target(), 8); + + Assert.Null(transcoder.Payload(block, 0, block.Length, out var failure)); + Assert.EndsWith(" at Pair.m_second", failure); + } + [Fact] public void Payload_TakesARenamedNarrowedFieldFromTheSource() { From 584dcf254b7fe37ec1361ee808d7bcb35401f31a Mon Sep 17 00:00:00 2001 From: mie Date: Sat, 5 Dec 2026 09:04:36 +0300 Subject: [PATCH 3/7] Collect downgrade omissions during the first partition scan --- src/RvtIO.Cli/DowngradeCommand.cs | 5 +- .../Writing/DowngradePartitionRewriter.cs | 21 +++--- src/RvtIO/Writing/DowngradePlanner.cs | 5 +- src/RvtIO/Writing/DowngradeWriter.cs | 51 ++++++++------ src/RvtIO/Writing/ElementCensus.cs | 67 ++++++++++++------- tests/RvtIO.Tests/DowngradeWriterTests.cs | 27 ++++++++ 6 files changed, 118 insertions(+), 58 deletions(-) diff --git a/src/RvtIO.Cli/DowngradeCommand.cs b/src/RvtIO.Cli/DowngradeCommand.cs index bce6500e..ec5431ca 100644 --- a/src/RvtIO.Cli/DowngradeCommand.cs +++ b/src/RvtIO.Cli/DowngradeCommand.cs @@ -69,8 +69,9 @@ internal static int Run(string[] args, TextWriter output, TextWriter error) if (PathProblem(source, profile, reportPath, outputPath) is { } problem) return Usage(error, problem + " Nothing was read or written."); string sourceName = Path.GetFileName(source), profileName = Path.GetFileName(profile); + using var chainBuffer = new MemoryStream(); DowngradePlanner.Result result; - try { result = DowngradePlanner.Plan(source, profile, rule); } + try { result = DowngradePlanner.Plan(source, profile, rule, chainBuffer: chainBuffer); } catch (RvtInputException exception) { return End(error, reportPath, RvtExitCodes.InputError, exception.Kind, exception.Message, sourceName, profileName, rule); @@ -111,7 +112,7 @@ internal static int Run(string[] args, TextWriter output, TextWriter error) if (WriteReport(error, reportPath, WriteReportBody(result, sourceName, profileName, prepared), RvtExitCodes.Success) != RvtExitCodes.Success) throw new ReportWriteFailedException(); - }); + }, chainBuffer: chainBuffer); if (written.RestoredAnalyticalMembers is { } restored) output.WriteLine($"Restored analytical members: {restored.Count.ToString(inv)}. Panels: {(written.RestoredAnalyticalPanels?.Count ?? 0).ToString(inv)}. Point supports: {(written.RestoredPointSupports?.Count ?? 0).ToString(inv)}. Line supports: {(written.RestoredLineSupports?.Count ?? 0).ToString(inv)}."); if (written.RestoredAnalyticalOpenings is { Count: > 0 } openings) diff --git a/src/RvtIO/Writing/DowngradePartitionRewriter.cs b/src/RvtIO/Writing/DowngradePartitionRewriter.cs index 43d3d012..2006a37b 100644 --- a/src/RvtIO/Writing/DowngradePartitionRewriter.cs +++ b/src/RvtIO/Writing/DowngradePartitionRewriter.cs @@ -32,7 +32,7 @@ internal static ContainerEntry Rewrite( IReadOnlySet knownDropped, IReadOnlyDictionary keptCounts, Func, byte[], byte[]?>? tagFixer, - ProjectEdits? projectEdits = null) + ProjectEdits? projectEdits, bool releaseSourceBuffer) { if (sourceWidth is not (4 or 8) || targetWidth is not (4 or 8)) throw new ArgumentOutOfRangeException(nameof(targetWidth), "Element identifier byte width must be 4 or 8."); @@ -75,6 +75,7 @@ internal static ContainerEntry Rewrite( }); if (!PartitionFraming.WalkStream(stored, sourceTags, sourceWidth, _ => { }, out var sourceFailure, out _, blocks, chainBuffer)) throw new InvalidDataException($"Partition stream framing is invalid: {sourceFailure}."); + if (releaseSourceBuffer) chainBuffer.Capacity = 0; WriteHeader("", uint.MaxValue); if (projectEdits is not null && (addedChannels.Count != 3 || replacedRecords.Count != projectEdits.Replacements.Count)) @@ -116,15 +117,13 @@ void WriteHeader(string key, uint owners) } } - /// The owners a stored stream holds and the ones a rewrite would leave out. - internal sealed record PartitionState(HashSet Owners, HashSet Dropped); - - internal static PartitionState Inspect( + /// Finds additional owners whose records a rewrite would leave out. + internal static HashSet Inspect( Stream stored, PartitionFraming.Tags tags, int width, R22Transcoder transcoder, MemoryStream chainBuffer, - IReadOnlySet? knownDropped = null, Dictionary? keptCounts = null) + IReadOnlySet? knownDropped = null, Dictionary? keptCounts = null, + Action? observe = null) { ulong terminator = width == 8 ? ulong.MaxValue : uint.MaxValue; - var owners = new HashSet(); var dropped = new HashSet(); var blockDropped = new HashSet(); var kept = new HashSet(); @@ -139,11 +138,11 @@ internal static PartitionState Inspect( blockDropped.Clear(); kept.Clear(); } - if (record.Owner == terminator) return; - owners.Add(record.Owner); + if (record.Owner == terminator || knownDropped?.Contains(record.Owner) == true) return; + observe?.Invoke(record); if (record.Channel == 101) { - if (countKept && !knownDropped!.Contains(record.Owner)) kept.Add(record.Owner); + if (countKept) kept.Add(record.Owner); return; } if (record.Body.Length < 2 || blockDropped.Contains(record.Owner)) return; @@ -163,7 +162,7 @@ internal static PartitionState Inspect( }, out var failure, out _, chainBuffer: chainBuffer)) throw new InvalidDataException($"Partition stream framing is invalid: {failure}."); if (countKept && block >= 0) keptCounts![block] = (uint)kept.Count; - return new PartitionState(owners, dropped); + return dropped; } private sealed record ChainSpan(int Channel, uint UpperFlags, uint Opaque, ReadOnlyMemory Inflated); diff --git a/src/RvtIO/Writing/DowngradePlanner.cs b/src/RvtIO/Writing/DowngradePlanner.cs index fddbfae5..8491f8d2 100644 --- a/src/RvtIO/Writing/DowngradePlanner.cs +++ b/src/RvtIO/Writing/DowngradePlanner.cs @@ -151,7 +151,8 @@ internal sealed record Result(DowngradePlan Plan, int SourceRelease, int TargetR /// Reads the source file and the profile file and plans the edit. Nothing is written. /// A file is missing, not a compound file, cut or damaged, or its Formats/Latest cannot be read. /// The releases are out of scope or the class tables cannot be planned. - internal static Result Plan(string sourcePath, string profilePath, GuidRule rule, bool countElements = true) + internal static Result Plan(string sourcePath, string profilePath, GuidRule rule, bool countElements = true, + MemoryStream? chainBuffer = null) { RvtContainerCheck.Verify(sourcePath); RvtContainerCheck.Verify(profilePath); @@ -178,7 +179,7 @@ internal static Result Plan(string sourcePath, string profilePath, GuidRule rule int? omittedContextualMembers = null; if (countElements) { - var counts = ElementCensus.CountByClass(sourceRoot, sourceSchema, out countFailure); + var counts = ElementCensus.CountByClass(sourceRoot, sourceSchema, out countFailure, chainBuffer); if (counts is not null) { plan = Compute(sourceSchema, profileSchema, rule, counts); diff --git a/src/RvtIO/Writing/DowngradeWriter.cs b/src/RvtIO/Writing/DowngradeWriter.cs index 8be28023..93fa8571 100644 --- a/src/RvtIO/Writing/DowngradeWriter.cs +++ b/src/RvtIO/Writing/DowngradeWriter.cs @@ -30,27 +30,32 @@ internal sealed record DowngradeWriteResult( internal static DowngradeWriteResult Write( string sourcePath, string profilePath, string outputPath, GuidRule rule, bool includeOmittedAnalytics = false, - bool restoreLegacyAnalytics = false, bool allowLoss = false, Action? beforePublish = null) => - Write(sourcePath, profilePath, outputPath, DowngradePlanner.Plan(sourcePath, profilePath, rule), - includeOmittedAnalytics, restoreLegacyAnalytics, allowLoss, beforePublish); + bool restoreLegacyAnalytics = false, bool allowLoss = false, Action? beforePublish = null) + { + using var chainBuffer = new MemoryStream(); + return Write(sourcePath, profilePath, outputPath, DowngradePlanner.Plan(sourcePath, profilePath, rule, chainBuffer: chainBuffer), + includeOmittedAnalytics, restoreLegacyAnalytics, allowLoss, beforePublish, chainBuffer); + } internal static DowngradeWriteResult Write( string sourcePath, string profilePath, string outputPath, DowngradePlanner.Result planResult, bool includeOmittedAnalytics = false, bool restoreLegacyAnalytics = false, bool allowLoss = false, - Action? beforePublish = null) + Action? beforePublish = null, MemoryStream? chainBuffer = null) { if (restoreLegacyAnalytics && (planResult.SourceRelease < 2023 || planResult.TargetRelease != 2022)) throw new DowngradeRefusedException("unsupported-analytical-restore", "Legacy analytical restoration requires a Revit 2023 or newer source and its historical Revit 2022 project as the target profile."); int sourceWidth = SchemaRelease.IdWidth(planResult.SourceRelease)!.Value; int targetWidth = SchemaRelease.IdWidth(planResult.TargetRelease)!.Value; - return Transcode(sourcePath, profilePath, outputPath, planResult, sourceWidth, targetWidth, + using var ownedChainBuffer = chainBuffer is null ? new MemoryStream() : null; + return Transcode(sourcePath, profilePath, outputPath, planResult, sourceWidth, targetWidth, chainBuffer ?? ownedChainBuffer!, includeOmittedAnalytics, restoreLegacyAnalytics, allowLoss, beforePublish); } private static DowngradeWriteResult Transcode( string sourcePath, string profilePath, string outputPath, DowngradePlanner.Result planResult, - int sourceWidth, int targetWidth, bool includeOmittedAnalytics, bool restoreLegacyAnalytics, bool allowLoss, + int sourceWidth, int targetWidth, MemoryStream chainBuffer, + bool includeOmittedAnalytics, bool restoreLegacyAnalytics, bool allowLoss, Action? beforePublish) { var plan = planResult.Plan; @@ -137,13 +142,19 @@ private static DowngradeWriteResult Transcode( // Clear references at the same transition as the omission, while their old owners are known. var knownOwners = new HashSet(); var knownDropped = new HashSet(); - using var chainBuffer = new MemoryStream(); - foreach (var (_, open) in sourcePartitions) + ElementCensus? projectElements = new(sourceDoc, sourceWidth); + // The last copy in numeric partition order supplies the class for the omissions report. + foreach (var (path, open) in sourcePartitions.OrderBy(p => + int.Parse(p.Path.AsSpan("Partitions/".Length), System.Globalization.CultureInfo.InvariantCulture))) { using var partition = open(); - var state = DowngradePartitionRewriter.Inspect(partition, sourceTags, sourceWidth, transcoder, chainBuffer); - knownOwners.UnionWith(state.Owners); - knownDropped.UnionWith(state.Dropped); + string name = path["Partitions/".Length..]; + knownDropped.UnionWith(DowngradePartitionRewriter.Inspect(partition, sourceTags, sourceWidth, transcoder, chainBuffer, + observe: record => + { + knownOwners.Add(record.Owner); + projectElements.Observe(record, name); + })); } transcoder.SetDroppedElementIds(knownDropped); // Orphaned rows: an element whose owning element is left out cannot stay, or the @@ -178,12 +189,9 @@ private static DowngradeWriteResult Transcode( { using var partition = open(); var ownersByBlock = new Dictionary(); - var restate = DowngradePartitionRewriter.Inspect(partition, sourceTags, sourceWidth, transcoder, chainBuffer, - knownDropped, ownersByBlock); + added.UnionWith(DowngradePartitionRewriter.Inspect(partition, sourceTags, sourceWidth, transcoder, chainBuffer, + knownDropped, ownersByBlock)); survivingOwnersByPartition.Add(path, ownersByBlock); - knownOwners.UnionWith(restate.Owners); - foreach (var id in restate.Dropped) - if (!knownDropped.Contains(id)) added.Add(id); } if (sourceElemRows is not null) { @@ -447,6 +455,7 @@ private static DowngradeWriteResult Transcode( } } + int remainingPartitions = sourcePartitions.Count; var generated = new Dictionary>(StringComparer.OrdinalIgnoreCase); foreach (var (path, open) in sourcePartitions) { @@ -488,8 +497,9 @@ private static DowngradeWriteResult Transcode( Dictionary? omittedProjectElements = null; if (droppedOwners.Count != 0 || planResult.TargetRelease <= 2022) { - omittedProjectElements = ElementCensus.CountByClass(sourceRoot, sourceDoc, out _, droppedOwners, chainBuffer); + omittedProjectElements = projectElements.CountByClass(droppedOwners); } + projectElements = null; var omittedOwners = new HashSet(droppedOwners); if (restored is not null) { @@ -535,13 +545,14 @@ ContainerEntry RewritePartition(string path, Func open, Stream destinati { // The last planning pass used the drop set from before the last update. keptCounts.Clear(); - var state = DowngradePartitionRewriter.Inspect(partition, sourceTags, sourceWidth, transcoder, chainBuffer, + var added = DowngradePartitionRewriter.Inspect(partition, sourceTags, sourceWidth, transcoder, chainBuffer, knownDropped, keptCounts); - if (!state.Dropped.IsSubsetOf(knownDropped)) + if (added.Count != 0) throw new InvalidDataException("Additional omitted elements were detected after writing the element table."); } return DowngradePartitionRewriter.Rewrite(partition, destination, chainBuffer, sourceTags, sourceWidth, - targetTags, targetWidth, transcoder, knownDropped, keptCounts, tagFixer, edits); + targetTags, targetWidth, transcoder, knownDropped, keptCounts, tagFixer, edits, + releaseSourceBuffer: --remainingPartitions == 0); } catch (Exception exception) when (exception is InvalidDataException or ArgumentException or OverflowException) { diff --git a/src/RvtIO/Writing/ElementCensus.cs b/src/RvtIO/Writing/ElementCensus.cs index 4ea45762..466eb3ad 100644 --- a/src/RvtIO/Writing/ElementCensus.cs +++ b/src/RvtIO/Writing/ElementCensus.cs @@ -10,13 +10,49 @@ namespace RvtIO.Writing; /// class table. An element that several partition streams hold is counted once, in the class of its last copy. Records of the keyed /// blocks (loaded family documents) are not project elements and are not counted. /// -internal static class ElementCensus +internal sealed class ElementCensus(SchemaDocument document, int width) { + private readonly ulong _terminator = width == 8 ? ulong.MaxValue : uint.MaxValue; + private readonly Dictionary _tags = []; + private readonly List<(ulong Owner, string Partition)> _taglessRecords = []; + + internal void Observe(PartitionFraming.Record record, string partition) + { + if (record.Block != 0 || record.Channel != 102 || record.Owner == _terminator) return; + if (record.Body.Length < sizeof(ushort)) + { + _taglessRecords.Add((record.Owner, partition)); + return; + } + _tags[record.Owner] = BinaryPrimitives.ReadUInt16LittleEndian(record.Body.Span); + } + + internal Dictionary CountByClass(IReadOnlySet? onlyOwners = null) + { + CheckClassTags(onlyOwners); + var nameOfTag = document.ById; + var counts = new Dictionary(StringComparer.Ordinal); + foreach (var (owner, tag) in _tags) + { + if (onlyOwners is not null && !onlyOwners.Contains(owner)) continue; + string className = nameOfTag.TryGetValue(tag, out var c) ? c.Name : $"(class {tag})"; + counts[className] = counts.GetValueOrDefault(className) + 1; + } + return counts; + } + + private void CheckClassTags(IReadOnlySet? onlyOwners) + { + foreach (var (owner, partition) in _taglessRecords) + if (onlyOwners is null || onlyOwners.Contains(owner)) + throw new RvtInputException("truncated-or-damaged", $"Partition stream {partition} is damaged: it holds a record without a class tag."); + } + /// Elements per class name, or null with the reason in when the count cannot be made from this /// file's layout: the class table has no framing classes, the id width is not known, or there is no partition stream. /// A partition stream is present but its framing does not hold or a record has no class tag. - internal static Dictionary? CountByClass(RootStorage root, SchemaDocument document, - out string? failure, IReadOnlySet? onlyOwners = null, MemoryStream? chainBuffer = null) + internal static Dictionary? CountByClass(RootStorage root, SchemaDocument document, out string? failure, + MemoryStream? chainBuffer = null) { failure = null; var schema = new FormatsSchema(document); @@ -30,30 +66,15 @@ internal static class ElementCensus .OrderBy(n => int.Parse(n, System.Globalization.CultureInfo.InvariantCulture)).ToList(); if (names.Count == 0) { failure = "the file has no partition stream"; return null; } - ulong terminator = width == 8 ? ulong.MaxValue : uint.MaxValue; - var tagOfOwner = new Dictionary(); + var census = new ElementCensus(document, width); foreach (string name in names) { using var stream = storage.OpenStream(name); - bool bad = false; - bool ok = PartitionFraming.WalkStream(stream, tags, width, record => - { - if (record.Block != 0 || record.Channel != 102 || record.Owner == terminator - || onlyOwners is not null && !onlyOwners.Contains(record.Owner)) return; - if (record.Body.Length < 2) { bad = true; return; } - tagOfOwner[record.Owner] = BinaryPrimitives.ReadUInt16LittleEndian(record.Body.Span); - }, out string? walkFailure, out _, chainBuffer: chainBuffer); + bool ok = PartitionFraming.WalkStream(stream, tags, width, record => census.Observe(record, name), + out string? walkFailure, out _, chainBuffer: chainBuffer); if (!ok) throw new RvtInputException("truncated-or-damaged", $"Partition stream {name} is damaged: its framing does not hold ({walkFailure})."); - if (bad) throw new RvtInputException("truncated-or-damaged", $"Partition stream {name} is damaged: it holds a record without a class tag."); + census.CheckClassTags(null); } - - var nameOfTag = document.ById; - var counts = new Dictionary(StringComparer.Ordinal); - foreach (ushort tag in tagOfOwner.Values) - { - string className = nameOfTag.TryGetValue(tag, out var c) ? c.Name : $"(class {tag})"; - counts[className] = counts.GetValueOrDefault(className) + 1; - } - return counts; + return census.CountByClass(); } } diff --git a/tests/RvtIO.Tests/DowngradeWriterTests.cs b/tests/RvtIO.Tests/DowngradeWriterTests.cs index f097c902..d735f150 100644 --- a/tests/RvtIO.Tests/DowngradeWriterTests.cs +++ b/tests/RvtIO.Tests/DowngradeWriterTests.cs @@ -599,6 +599,33 @@ public void Write_CrossWidth_TranscodesPartitions_AndValidates() } } + [Fact] + public void Write_ReportsOmittedOwnersByTheirLastNumberedProjectRecord() + { + string source = Synthetic(2026, "omissions-source.rvt"); + string profile = Synthetic(2025, "omissions-profile.rvt"); + using (var root = RootStorage.Open(source, FileMode.Open)) + { + var schema = TfSchemaReader.Read(root)!; + var tags = PartitionFraming.TagsOf(new FormatsSchema(schema))!.Value; + ushort item = (ushort)schema.Classes.Single(c => c.Name == "SyntheticItem").Id; + var parts = root.OpenStorage("Partitions"); + var lastProject = PartitionStreamEditorTests.MakeStandardBlock(8, keyed: false, [(202UL, item, new byte[4])]); + var family = PartitionStreamEditorTests.MakeStandardBlock(8, keyed: true, [(202UL, 65002, new byte[4])]); + using (var tenth = parts.CreateStream("10")) + tenth.Write(PartitionStreamEditorTests.BuildPartitionStream(8, tags, lastProject, family)); + var earlier = PartitionStreamEditorTests.MakeStandardBlock(8, keyed: false, [(202UL, 65001, new byte[4])]); + using var second = parts.CreateStream("2"); + second.Write(PartitionStreamEditorTests.BuildPartitionStream(8, tags, earlier)); + } + + var plan = DowngradePlanner.Plan(source, profile, GuidRule.Exact, countElements: false); + var result = DowngradeWriter.Write(source, profile, P("omissions-output.rvt"), plan, allowLoss: true); + + Assert.Equal([202UL], result.OmittedRecordOwners); + Assert.Equal(new KeyValuePair("SyntheticItem", 1), Assert.Single(result.OmittedProjectElements!)); + } + [Fact] public void Write_DowngradedFile_StillOpens_InRvtIO() { From b7fe69fde73a57749f2e94c2df0f901462e6579f Mon Sep 17 00:00:00 2001 From: mie <79989386+mahach666@users.noreply.github.com> Date: Sat, 5 Dec 2026 16:57:48 +0300 Subject: [PATCH 4/7] Compute the RVT gzip trailer while compressing --- src/RvtIO/Writing/GzipMember.cs | 30 +++++++++++++++--------------- 1 file changed, 15 insertions(+), 15 deletions(-) diff --git a/src/RvtIO/Writing/GzipMember.cs b/src/RvtIO/Writing/GzipMember.cs index e7bbf3d1..53a5f0cb 100644 --- a/src/RvtIO/Writing/GzipMember.cs +++ b/src/RvtIO/Writing/GzipMember.cs @@ -1,6 +1,4 @@ -using System.Buffers.Binary; using System.IO.Compression; -using ICSharpCode.SharpZipLib.Checksum; namespace RvtIO.Writing; @@ -23,19 +21,21 @@ internal static class GzipMember /// The gzip member that inflates to . internal static byte[] Write(ReadOnlySpan data, CompressionLevel compression = CompressionLevel.SmallestSize) { - using var stream = new MemoryStream(); - stream.Write(Header); if (data.IsEmpty) - stream.Write(EmptyDeflate); // DeflateStream writes nothing at all for empty input on some runtimes - else - using (var deflate = new DeflateStream(stream, compression, leaveOpen: true)) - deflate.Write(data); - var crc = new Crc32(); - crc.Update(data.ToArray()); - Span trailer = stackalloc byte[8]; - BinaryPrimitives.WriteUInt32LittleEndian(trailer, (uint)crc.Value); - BinaryPrimitives.WriteUInt32LittleEndian(trailer[4..], (uint)data.Length); - stream.Write(trailer); - return stream.ToArray(); + { + // Some runtimes omit the member entirely when no input is written. + var empty = new byte[HeaderLength + EmptyDeflate.Length + 8]; + Header.CopyTo(empty, 0); + EmptyDeflate.CopyTo(empty, HeaderLength); + return empty; + } + + using var stream = new MemoryStream(); + using (var gzip = new GZipStream(stream, compression, leaveOpen: true)) + gzip.Write(data); + var member = stream.ToArray(); + // GZipStream computes the trailer while writing. Use the RVT header in place of the runtime's header. + Header.CopyTo(member, 0); + return member; } } From 60458f5e23d7856ab2c57391f46ab8334568a92a Mon Sep 17 00:00:00 2001 From: mie <79989386+mahach666@users.noreply.github.com> Date: Sat, 5 Dec 2026 16:57:48 +0300 Subject: [PATCH 5/7] Share the first partition scan with the downgrade report --- src/RvtIO.Cli/DowngradeCommand.cs | 42 ++++++++++------ .../Writing/DowngradePartitionRewriter.cs | 6 ++- src/RvtIO/Writing/DowngradePlanner.cs | 36 +++++++++----- src/RvtIO/Writing/DowngradeWriter.cs | 12 +++-- src/RvtIO/Writing/ElementCensus.cs | 2 +- tests/RvtIO.Tests/DowngradeWriterTests.cs | 49 +++++++++++++++++++ 6 files changed, 114 insertions(+), 33 deletions(-) diff --git a/src/RvtIO.Cli/DowngradeCommand.cs b/src/RvtIO.Cli/DowngradeCommand.cs index ec5431ca..0b64e7f7 100644 --- a/src/RvtIO.Cli/DowngradeCommand.cs +++ b/src/RvtIO.Cli/DowngradeCommand.cs @@ -71,7 +71,11 @@ internal static int Run(string[] args, TextWriter output, TextWriter error) string sourceName = Path.GetFileName(source), profileName = Path.GetFileName(profile); using var chainBuffer = new MemoryStream(); DowngradePlanner.Result result; - try { result = DowngradePlanner.Plan(source, profile, rule, chainBuffer: chainBuffer); } + try + { + result = DowngradePlanner.Plan(source, profile, rule, chainBuffer: chainBuffer, + countDuringWrite: outputPath is not null && !check); + } catch (RvtInputException exception) { return End(error, reportPath, RvtExitCodes.InputError, exception.Kind, exception.Message, sourceName, profileName, rule); @@ -85,20 +89,24 @@ internal static int Run(string[] args, TextWriter output, TextWriter error) return End(error, reportPath, RvtExitCodes.InputError, "limit-exceeded", exception.Message, sourceName, profileName, rule); } - var plan = result.Plan; var inv = CultureInfo.InvariantCulture; - output.WriteLine($"Source: {sourceName} (release {result.SourceRelease}, {plan.SourceClasses.ToString(inv)} classes)"); - output.WriteLine($"Profile: {profileName} (release {result.TargetRelease}, {plan.TargetClasses.ToString(inv)} classes)"); - output.WriteLine($"Upgrade-identifier rule: {RuleName(rule)}"); - output.WriteLine($"Classes in both: {plan.CommonClasses.ToString(inv)}; class versions to lower: {plan.HigherVersions.Count.ToString(inv)}; upgrade-identifier lists to change: {plan.GuidLists.Count.ToString(inv)}"); - string elements = plan.ElementsInSourceOnlyClasses is int n ? $"; elements in them: {n.ToString(inv)}" : "; elements not counted"; - output.WriteLine($"Classes only in the source: {plan.ClassesOnlyInSource.Count.ToString(inv)}{elements}"); - output.WriteLine($"Classes only in the profile: {plan.ClassesOnlyInTarget.Count.ToString(inv)}; classes with different fields: {plan.FieldDifferences.Count.ToString(inv)}"); - int emptied = plan.GuidLists.Count(g => g.Result == 0); - if (emptied > 0) output.WriteLine($"Upgrade-identifier lists that become empty: {emptied.ToString(inv)} (the rule yields no identifier for them)"); - if (!restoreLegacyAnalytics && result.OmittedContextualMembers is > 0) - error.WriteLine($"warning: Revit 2022 cannot open independent analytical members. Downgrade omits {result.OmittedContextualMembers.Value.ToString(inv)} AnalyticalMember elements."); - if (result.CountFailure != null) error.WriteLine($"warning: the elements were not counted: {result.CountFailure}."); + void PrintPlan() + { + var plan = result.Plan; + output.WriteLine($"Source: {sourceName} (release {result.SourceRelease}, {plan.SourceClasses.ToString(inv)} classes)"); + output.WriteLine($"Profile: {profileName} (release {result.TargetRelease}, {plan.TargetClasses.ToString(inv)} classes)"); + output.WriteLine($"Upgrade-identifier rule: {RuleName(rule)}"); + output.WriteLine($"Classes in both: {plan.CommonClasses.ToString(inv)}; class versions to lower: {plan.HigherVersions.Count.ToString(inv)}; upgrade-identifier lists to change: {plan.GuidLists.Count.ToString(inv)}"); + string elements = plan.ElementsInSourceOnlyClasses is int n ? $"; elements in them: {n.ToString(inv)}" : "; elements not counted"; + output.WriteLine($"Classes only in the source: {plan.ClassesOnlyInSource.Count.ToString(inv)}{elements}"); + output.WriteLine($"Classes only in the profile: {plan.ClassesOnlyInTarget.Count.ToString(inv)}; classes with different fields: {plan.FieldDifferences.Count.ToString(inv)}"); + int emptied = plan.GuidLists.Count(g => g.Result == 0); + if (emptied > 0) output.WriteLine($"Upgrade-identifier lists that become empty: {emptied.ToString(inv)} (the rule yields no identifier for them)"); + if (!restoreLegacyAnalytics && result.OmittedContextualMembers is > 0) + error.WriteLine($"warning: Revit 2022 cannot open independent analytical members. Downgrade omits {result.OmittedContextualMembers.Value.ToString(inv)} AnalyticalMember elements."); + if (result.CountFailure != null) error.WriteLine($"warning: the elements were not counted: {result.CountFailure}."); + } + if (!result.CountInWriter) PrintPlan(); if (outputPath != null) { @@ -112,7 +120,11 @@ internal static int Run(string[] args, TextWriter output, TextWriter error) if (WriteReport(error, reportPath, WriteReportBody(result, sourceName, profileName, prepared), RvtExitCodes.Success) != RvtExitCodes.Success) throw new ReportWriteFailedException(); - }, chainBuffer: chainBuffer); + }, chainBuffer: chainBuffer, afterCensus: counted => + { + result = counted; + PrintPlan(); + }); if (written.RestoredAnalyticalMembers is { } restored) output.WriteLine($"Restored analytical members: {restored.Count.ToString(inv)}. Panels: {(written.RestoredAnalyticalPanels?.Count ?? 0).ToString(inv)}. Point supports: {(written.RestoredPointSupports?.Count ?? 0).ToString(inv)}. Line supports: {(written.RestoredLineSupports?.Count ?? 0).ToString(inv)}."); if (written.RestoredAnalyticalOpenings is { Count: > 0 } openings) diff --git a/src/RvtIO/Writing/DowngradePartitionRewriter.cs b/src/RvtIO/Writing/DowngradePartitionRewriter.cs index 2006a37b..a2c42b5a 100644 --- a/src/RvtIO/Writing/DowngradePartitionRewriter.cs +++ b/src/RvtIO/Writing/DowngradePartitionRewriter.cs @@ -121,7 +121,7 @@ void WriteHeader(string key, uint owners) internal static HashSet Inspect( Stream stored, PartitionFraming.Tags tags, int width, R22Transcoder transcoder, MemoryStream chainBuffer, IReadOnlySet? knownDropped = null, Dictionary? keptCounts = null, - Action? observe = null) + Action? observe = null, string? censusPartition = null) { ulong terminator = width == 8 ? ulong.MaxValue : uint.MaxValue; var dropped = new HashSet(); @@ -160,7 +160,11 @@ internal static HashSet Inspect( dropped.Add(record.Owner); } }, out var failure, out _, chainBuffer: chainBuffer)) + { + if (censusPartition is not null) + throw new RvtInputException("truncated-or-damaged", $"Partition stream {censusPartition} is damaged: its framing does not hold ({failure})."); throw new InvalidDataException($"Partition stream framing is invalid: {failure}."); + } if (countKept && block >= 0) keptCounts![block] = (uint)kept.Count; return dropped; } diff --git a/src/RvtIO/Writing/DowngradePlanner.cs b/src/RvtIO/Writing/DowngradePlanner.cs index 8491f8d2..ea38ea30 100644 --- a/src/RvtIO/Writing/DowngradePlanner.cs +++ b/src/RvtIO/Writing/DowngradePlanner.cs @@ -146,13 +146,23 @@ private static Dictionary ByName(SchemaDocument document, s /// The outcome of planning two files. internal sealed record Result(DowngradePlan Plan, int SourceRelease, int TargetRelease, int SourceStreamBytes, - int EditedStreamBytes, string? CountFailure, int? OmittedContextualMembers); + int EditedStreamBytes, string? CountFailure, int? OmittedContextualMembers, bool CountInWriter = false); + + internal static Result WithElementCounts(Result result, SchemaDocument source, SchemaDocument profile, + IReadOnlyDictionary counts) => result with + { + Plan = Compute(source, profile, result.Plan.Rule, counts), + OmittedContextualMembers = result.TargetRelease == 2022 + ? counts.GetValueOrDefault(R22Transcoder.ContextualAnalyticalMember) + : null, + CountInWriter = false, + }; /// Reads the source file and the profile file and plans the edit. Nothing is written. /// A file is missing, not a compound file, cut or damaged, or its Formats/Latest cannot be read. /// The releases are out of scope or the class tables cannot be planned. internal static Result Plan(string sourcePath, string profilePath, GuidRule rule, bool countElements = true, - MemoryStream? chainBuffer = null) + MemoryStream? chainBuffer = null, bool countDuringWrite = false) { RvtContainerCheck.Verify(sourcePath); RvtContainerCheck.Verify(profilePath); @@ -175,17 +185,18 @@ internal static Result Plan(string sourcePath, string profilePath, GuidRule rule throw new DowngradeRefusedException("profile-not-older", $"The profile file is from release {targetRelease}, which is not older than the source (release {sourceRelease})."); var plan = Compute(sourceSchema, profileSchema, rule); + // The writer visits these same numbered partitions in numeric order before writing any output. + bool countInWriter = countElements && countDuringWrite + && PartitionFraming.TagsOf(new FormatsSchema(sourceSchema)) != null + && PartitionFraming.TagsOf(new FormatsSchema(profileSchema)) != null + && sourceRoot.TryOpenStorage("Partitions", out var partitions) + && partitions.EnumerateEntries().Any(e => e.Type == EntryType.Stream + && int.TryParse(e.Name, System.Globalization.NumberStyles.None, System.Globalization.CultureInfo.InvariantCulture, out _)); string? countFailure = null; - int? omittedContextualMembers = null; - if (countElements) + IReadOnlyDictionary? counts = null; + if (countElements && !countInWriter) { - var counts = ElementCensus.CountByClass(sourceRoot, sourceSchema, out countFailure, chainBuffer); - if (counts is not null) - { - plan = Compute(sourceSchema, profileSchema, rule, counts); - if (targetRelease == 2022) - omittedContextualMembers = counts.GetValueOrDefault(R22Transcoder.ContextualAnalyticalMember); - } + counts = ElementCensus.CountByClass(sourceRoot, sourceSchema, out countFailure, chainBuffer); } byte[] edited; @@ -194,7 +205,8 @@ internal static Result Plan(string sourcePath, string profilePath, GuidRule rule { throw new DowngradeRefusedException("edit-not-applicable", $"The planned edit does not apply to the class table of the source: {exception.Message}"); } - return new Result(plan, sourceRelease, targetRelease, sourceStream.Length, edited.Length, countFailure, omittedContextualMembers); + var result = new Result(plan, sourceRelease, targetRelease, sourceStream.Length, edited.Length, countFailure, null, countInWriter); + return counts is null ? result : WithElementCounts(result, sourceSchema, profileSchema, counts); } private static byte[] ReadStream(RootStorage root, string role, string path) diff --git a/src/RvtIO/Writing/DowngradeWriter.cs b/src/RvtIO/Writing/DowngradeWriter.cs index 93fa8571..3664fd3e 100644 --- a/src/RvtIO/Writing/DowngradeWriter.cs +++ b/src/RvtIO/Writing/DowngradeWriter.cs @@ -40,7 +40,8 @@ internal static DowngradeWriteResult Write( internal static DowngradeWriteResult Write( string sourcePath, string profilePath, string outputPath, DowngradePlanner.Result planResult, bool includeOmittedAnalytics = false, bool restoreLegacyAnalytics = false, bool allowLoss = false, - Action? beforePublish = null, MemoryStream? chainBuffer = null) + Action? beforePublish = null, MemoryStream? chainBuffer = null, + Action? afterCensus = null) { if (restoreLegacyAnalytics && (planResult.SourceRelease < 2023 || planResult.TargetRelease != 2022)) throw new DowngradeRefusedException("unsupported-analytical-restore", @@ -49,14 +50,14 @@ internal static DowngradeWriteResult Write( int targetWidth = SchemaRelease.IdWidth(planResult.TargetRelease)!.Value; using var ownedChainBuffer = chainBuffer is null ? new MemoryStream() : null; return Transcode(sourcePath, profilePath, outputPath, planResult, sourceWidth, targetWidth, chainBuffer ?? ownedChainBuffer!, - includeOmittedAnalytics, restoreLegacyAnalytics, allowLoss, beforePublish); + includeOmittedAnalytics, restoreLegacyAnalytics, allowLoss, beforePublish, afterCensus); } private static DowngradeWriteResult Transcode( string sourcePath, string profilePath, string outputPath, DowngradePlanner.Result planResult, int sourceWidth, int targetWidth, MemoryStream chainBuffer, bool includeOmittedAnalytics, bool restoreLegacyAnalytics, bool allowLoss, - Action? beforePublish) + Action? beforePublish, Action? afterCensus) { var plan = planResult.Plan; SchemaDocument sourceDoc, profileDoc; @@ -154,8 +155,11 @@ private static DowngradeWriteResult Transcode( { knownOwners.Add(record.Owner); projectElements.Observe(record, name); - })); + }, censusPartition: planResult.CountInWriter ? name : null)); + if (planResult.CountInWriter) projectElements.CheckClassTags(); } + if (planResult.CountInWriter && afterCensus is not null) + afterCensus(DowngradePlanner.WithElementCounts(planResult, sourceDoc, profileDoc, projectElements.CountByClass())); transcoder.SetDroppedElementIds(knownDropped); // Orphaned rows: an element whose owning element is left out cannot stay, or the // older release reports a missing owner and fails the open. Close over the source diff --git a/src/RvtIO/Writing/ElementCensus.cs b/src/RvtIO/Writing/ElementCensus.cs index 466eb3ad..b544084a 100644 --- a/src/RvtIO/Writing/ElementCensus.cs +++ b/src/RvtIO/Writing/ElementCensus.cs @@ -41,7 +41,7 @@ internal Dictionary CountByClass(IReadOnlySet? onlyOwners = return counts; } - private void CheckClassTags(IReadOnlySet? onlyOwners) + internal void CheckClassTags(IReadOnlySet? onlyOwners = null) { foreach (var (owner, partition) in _taglessRecords) if (onlyOwners is null || onlyOwners.Contains(owner)) diff --git a/tests/RvtIO.Tests/DowngradeWriterTests.cs b/tests/RvtIO.Tests/DowngradeWriterTests.cs index d735f150..8ff6eb76 100644 --- a/tests/RvtIO.Tests/DowngradeWriterTests.cs +++ b/tests/RvtIO.Tests/DowngradeWriterTests.cs @@ -712,6 +712,55 @@ public void Cli_Output_CrossWidth_WritesFile_WithExit0() Assert.NotNull(doc.RawData); } + [Fact] + public void Cli_WriteReusesTheCensusAndMatchesTheCheckReport() + { + string source = Synthetic(2026, "source.rvt"); + string profile = Synthetic(2025, "profile.rvt"); + string output = P("output.rvt"); + string checkReport = P("check.json"); + string writeReport = P("write.json"); + using var stdout = new StringWriter(); + using var stderr = new StringWriter(); + + Assert.Equal(0, DowngradeCommand.Run([source, "--target-profile", profile, "--check", "--report", checkReport], stdout, stderr)); + stdout.GetStringBuilder().Clear(); + Assert.Equal(0, DowngradeCommand.Run([source, "--target-profile", profile, "--output", output, "--allow-loss", "--report", writeReport], stdout, stderr)); + Assert.Contains("; elements in them:", stdout.ToString()); + Assert.True(File.Exists(output)); + + using var check = JsonDocument.Parse(File.ReadAllText(checkReport)); + using var write = JsonDocument.Parse(File.ReadAllText(writeReport)); + foreach (string key in new[] { "classesOnlyInSource", "elementsInClassesOnlyInSource" }) + Assert.Equal(check.RootElement.GetProperty(key).GetRawText(), write.RootElement.GetProperty(key).GetRawText()); + Assert.Equal("202", Assert.Single(write.RootElement.GetProperty("omittedRecordOwners").EnumerateArray()).GetString()); + Assert.False(write.RootElement.TryGetProperty("elementCountFailure", out _)); + } + + [Fact] + public void Cli_WriteReportsInvalidCensusFramingAsInputDamage() + { + string source = Synthetic(2026, "source.rvt"); + string profile = Synthetic(2025, "profile.rvt"); + string output = P("output.rvt"); + string report = P("report.json"); + using (var root = RootStorage.Open(source, FileMode.Open)) + using (var partition = root.OpenStorage("Partitions").OpenStream("1")) + { + partition.SetLength(0); + partition.Write(new byte[8]); + } + using var stdout = new StringWriter(); + using var stderr = new StringWriter(); + + Assert.Equal(2, DowngradeCommand.Run([source, "--target-profile", profile, "--output", output, "--report", report], stdout, stderr)); + Assert.False(File.Exists(output)); + Assert.Empty(stdout.ToString()); + Assert.Contains("Partition stream 1 is damaged", stderr.ToString()); + using var json = JsonDocument.Parse(File.ReadAllText(report)); + Assert.Equal("truncated-or-damaged", json.RootElement.GetProperty("kind").GetString()); + } + [Fact] public void Cli_LossReportFailure_LeavesNoOutput_AndCanBeRetried() { From 2215833f7daf310bd815fadbc73b5f68ebbc0f41 Mon Sep 17 00:00:00 2001 From: mie <79989386+mahach666@users.noreply.github.com> Date: Sun, 6 Dec 2026 01:55:09 +0300 Subject: [PATCH 6/7] Reuse record edit ranges during RVT transcoding --- src/RvtIO/Parsing/R22Transcoder.cs | 36 ++++++++++++++++-------------- 1 file changed, 19 insertions(+), 17 deletions(-) diff --git a/src/RvtIO/Parsing/R22Transcoder.cs b/src/RvtIO/Parsing/R22Transcoder.cs index 0263ff27..5d2eb8d1 100644 --- a/src/RvtIO/Parsing/R22Transcoder.cs +++ b/src/RvtIO/Parsing/R22Transcoder.cs @@ -766,8 +766,7 @@ private static byte[] Assemble(Context c, int offset, int objectEnd) int n = c.ObjectStarts.Count; if (n == 0) return Apply(c.D, offset, objectEnd, c.Edits); int rootEnd = c.ObjectStarts[0]; - var bySlot = new List[n + 1]; - for (int i = 0; i <= n; i++) bySlot[i] = []; + var bySlot = new List?[n + 1]; foreach (var edit in c.Edits) { int slot = edit.Slot is int objectSlot ? objectSlot + 1 : 0; @@ -786,7 +785,7 @@ private static byte[] Assemble(Context c, int offset, int objectEnd) } slot = found + 1; } - bySlot[slot].Add(edit); + (bySlot[slot] ??= []).Add(edit); } var order = new List(); @@ -805,24 +804,24 @@ void Children(int slot) Children(-1); for (int i = 0; i < order.Count; i++) Children(order[i]); - int length = EditedLength(rootEnd - offset, bySlot[0]); + int length = EditedLength(rootEnd - offset, CollectionsMarshal.AsSpan(bySlot[0])); foreach (int q in order) { int end = q + 1 < n ? c.ObjectStarts[q + 1] : objectEnd; - length = checked(length + EditedLength(end - c.ObjectStarts[q], bySlot[q + 1])); + length = checked(length + EditedLength(end - c.ObjectStarts[q], CollectionsMarshal.AsSpan(bySlot[q + 1]))); } var output = new byte[length]; - int written = ApplyTo(c.D, offset, rootEnd, bySlot[0], output); + int written = ApplyTo(c.D, offset, rootEnd, CollectionsMarshal.AsSpan(bySlot[0]), output); foreach (int q in order) { int start = c.ObjectStarts[q]; int end = q + 1 < n ? c.ObjectStarts[q + 1] : objectEnd; - written += ApplyTo(c.D, start, end, bySlot[q + 1], output.AsSpan(written)); + written += ApplyTo(c.D, start, end, CollectionsMarshal.AsSpan(bySlot[q + 1]), output.AsSpan(written)); } return output; } - private static int EditedLength(int length, List edits) + private static int EditedLength(int length, ReadOnlySpan edits) { foreach (var edit in edits) length = checked(length + edit.Replacement.Length - (edit.End - edit.Start)); @@ -830,28 +829,31 @@ private static int EditedLength(int length, List edits) } /// The bytes [start, end) with the edits applied (insertions sort before the replacement that starts at the same place). - private static byte[] Apply(byte[] data, int start, int end, List edits) + private static byte[] Apply(byte[] data, int start, int end, List edits) => + ApplyEdits(data, start, end, CollectionsMarshal.AsSpan(edits)); + + private static byte[] ApplyEdits(byte[] data, int start, int end, Span edits) { var output = new byte[EditedLength(end - start, edits)]; ApplyTo(data, start, end, edits, output); return output; } - private static int ApplyTo(byte[] data, int start, int end, List edits, Span output) + private static int ApplyTo(byte[] data, int start, int end, Span edits, Span output) { // The edits are added as the bytes are read, so they come nearly in order: an insertion sort moves few of them, and // it keeps the order of equal ones as the ordering by two keys did. A loop also stays in compiled code in the // browser, where the ordering of a list of structs by its keys runs through the interpreter. - var ordered = edits.ToArray(); - for (int i = 0; i < ordered.Length; i++) + // Each caller owns this range and discards it after writing the bytes. + for (int i = 0; i < edits.Length; i++) { - var edit = ordered[i]; + var edit = edits[i]; int j = i - 1; - for (; j >= 0 && After(ordered[j], edit); j--) ordered[j + 1] = ordered[j]; - ordered[j + 1] = edit; + for (; j >= 0 && After(edits[j], edit); j--) edits[j + 1] = edits[j]; + edits[j + 1] = edit; } int at = 0, source = start; - foreach (var e in ordered) + foreach (var e in edits) { int gap = e.Start - source; if (gap < 0 || e.End > end) throw new Fail("overlapping edits"); @@ -1132,7 +1134,7 @@ byte[] MissingField(int index) { if (bySource[j] < 0) { composed.Write(MissingField(j)); continue; } var (start, end, from, to) = spans[bySource[j]]; - composed.Write(Apply(c.D, start, end, c.Edits.GetRange(from, to - from))); + composed.Write(ApplyEdits(c.D, start, end, CollectionsMarshal.AsSpan(c.Edits).Slice(from, to - from))); } c.Edits.RemoveRange(regionEdits, c.Edits.Count - regionEdits); c.Edits.Add(new(regionStart, c.Pos, composed.ToArray(), c.Slot)); From f0a083670e41a78ac81584cbb2709b07add00332 Mon Sep 17 00:00:00 2001 From: mie <79989386+mahach666@users.noreply.github.com> Date: Sun, 6 Dec 2026 02:56:53 +0300 Subject: [PATCH 7/7] Reuse verified records when closing Revit downgrade omissions --- src/RvtIO/Parsing/R22Transcoder.cs | 69 +++++++++++++++++-- .../Writing/DowngradePartitionRewriter.cs | 37 +++++++++- src/RvtIO/Writing/DowngradeWriter.cs | 22 +++++- tests/RvtIO.Tests/R22TranscoderTests.cs | 10 +++ 4 files changed, 129 insertions(+), 9 deletions(-) diff --git a/src/RvtIO/Parsing/R22Transcoder.cs b/src/RvtIO/Parsing/R22Transcoder.cs index 5d2eb8d1..271936e8 100644 --- a/src/RvtIO/Parsing/R22Transcoder.cs +++ b/src/RvtIO/Parsing/R22Transcoder.cs @@ -524,6 +524,46 @@ private static uint Adler32(byte[] data) } + /// Positive IDs read by a conversion against an empty dropped set. + internal sealed class DropReferenceLog(int limit) + { + internal readonly record struct Range(int Start, int Count); + private readonly List _ids = []; + private int _start; + private bool _overflow; + + internal void Begin() + { + _start = _ids.Count; + _overflow = false; + } + + internal void Add(long id) + { + if (id <= 0 || _overflow) return; + ulong value = (ulong)id; + if (_ids.Count > _start && _ids[^1] == value) return; + if (_ids.Count == limit) _overflow = true; + else _ids.Add(value); + } + + internal Range? End(bool success) + { + int count = _ids.Count - _start; + if (success && !_overflow) return new Range(_start, count); + _ids.RemoveRange(_start, count); + return null; + } + + internal bool UnaffectedBy(Range range, IReadOnlySet dropped) + { + if (dropped.Count == 0) return true; + foreach (ulong id in CollectionsMarshal.AsSpan(_ids).Slice(range.Start, range.Count)) + if (dropped.Contains(id)) return false; + return true; + } + } + private sealed class Context(byte[] data, int pos, int end) { public readonly byte[] D = data; @@ -544,6 +584,7 @@ private sealed class Context(byte[] data, int pos, int end) public bool NeedsValidation; public bool Cutting; public bool LegacyHostedLoad; + public DropReferenceLog? DropReferences; public IReadOnlyDictionary? DailySchedules; public bool InArray; /// Inside a counted array, also through inline structures (its items must keep their stored order). @@ -582,6 +623,17 @@ private sealed class Context(byte[] data, int pos, int end) ? Payload(segment.Array!, segment.Offset, segment.Count) : Payload(data.ToArray(), 0, data.Length); + internal byte[]? PayloadWithDropReferences(ReadOnlyMemory data, DropReferenceLog log, + out DropReferenceLog.Range? references) + { + log.Begin(); + byte[]? result = MemoryMarshal.TryGetArray(data, out var segment) + ? Payload(segment.Array!, segment.Offset, segment.Count, out _, log) + : Payload(data.ToArray(), 0, data.Length, out _, log); + references = log.End(result is not null); + return result; + } + /// The payload in the 2022 layout with every byte after the object copied unchanged (a stream that holds one /// class object followed by opaque data), or null when the object cannot be rewritten. internal byte[]? PayloadWithTail(byte[] data, int offset, int size, out string? failure) @@ -596,9 +648,13 @@ private sealed class Context(byte[] data, int pos, int end) } /// Why the payload cannot be rewritten (the root class and the first rule that failed), null when it can. - internal byte[]? Payload(byte[] data, int offset, int size, out string? failure) + internal byte[]? Payload(byte[] data, int offset, int size, out string? failure) => + Payload(data, offset, size, out failure, null); + + private byte[]? Payload(byte[] data, int offset, int size, out string? failure, DropReferenceLog? dropReferences) { - byte[]? rewritten = PayloadObject(data, offset, size, out int objectEnd, out failure); + byte[]? rewritten = PayloadObject(data, offset, size, out int objectEnd, out failure, + dropReferences: dropReferences); if (rewritten is null) return null; if (objectEnd != offset + size) { @@ -609,7 +665,8 @@ private sealed class Context(byte[] data, int pos, int end) return rewritten; } - private byte[]? PayloadObject(byte[] data, int offset, int size, out int objectEnd, out string? failure, bool validateTarget = false) + private byte[]? PayloadObject(byte[] data, int offset, int size, out int objectEnd, out string? failure, + bool validateTarget = false, DropReferenceLog? dropReferences = null) { failure = null; objectEnd = offset; @@ -623,6 +680,7 @@ private sealed class Context(byte[] data, int pos, int end) var c = new Context(data, offset + 2, offset + size) { LegacyHostedLoad = _legacyHostedLoads.Contains(rootClass), + DropReferences = dropReferences, }; if (_energyScheduleWalker is not null && _source[rootClass].Name == "EnergyAnalysisDetailModel") c.DailySchedules = LegacyEnergySchedules.Read(_energyScheduleWalker, data, offset, size, rootClass); @@ -1033,6 +1091,7 @@ byte[] MissingField(int index) if (kind >= 0) { long id = browserOrganizations.GetValueOrDefault(kind, -1); + c.DropReferences?.Add(id); if (id > 0 && _droppedElements.Contains((ulong)id)) id = -1; if (_targetIdentifierWidth == 4 && (id < int.MinValue || id > uint.MaxValue)) throw new Fail("id beyond 32 bits: " + id); @@ -1409,7 +1468,7 @@ private void ReadReference(Context c, string? declaring, SchemaField f, int dept { int p = Take(c, _sourceWidth); bool narrow = _sourceWidth == 8 && _targetIdentifierWidth == 4; - if (!c.Cutting && (narrow || _droppedElements.Count > 0)) + if (!c.Cutting && (narrow || _droppedElements.Count > 0 || c.DropReferences != null)) { long id = _sourceWidth == 8 ? BitConverter.ToInt64(c.D, p) : BitConverter.ToUInt32(c.D, p); if (narrow && _ids != null) @@ -1417,6 +1476,8 @@ private void ReadReference(Context c, string? declaring, SchemaField f, int dept c.Edits.Add(new(p, p + _sourceWidth, BitConverter.GetBytes(_ids.Key(id)))); return; } + c.DropReferences?.Add(id); + if (!narrow && _droppedElements.Count == 0) return; bool dangling = id > 0 && _droppedElements.Contains((ulong)id); // The index, rather than the value, identifies a unique document setting. bool slot = IsUniqueElementSlot(declaring, f); diff --git a/src/RvtIO/Writing/DowngradePartitionRewriter.cs b/src/RvtIO/Writing/DowngradePartitionRewriter.cs index a2c42b5a..e02e405e 100644 --- a/src/RvtIO/Writing/DowngradePartitionRewriter.cs +++ b/src/RvtIO/Writing/DowngradePartitionRewriter.cs @@ -117,17 +117,40 @@ void WriteHeader(string key, uint owners) } } + internal sealed class InspectionResults(R22Transcoder.DropReferenceLog references, int limit) + { + private readonly record struct VerifiedRecord(long Offset, R22Transcoder.DropReferenceLog.Range References); + private readonly List _verified = []; + internal int Count => _verified.Count; + + internal byte[]? InspectPayload(PartitionFraming.Record record, R22Transcoder transcoder) + { + if (Count == limit) return transcoder.Payload(record.Body); + var payload = transcoder.PayloadWithDropReferences(record.Body, references, out var range); + if (range is { } complete) _verified.Add(new(record.Offset, complete)); + return payload; + } + + internal bool RemainsWritable(long offset, IReadOnlySet dropped, ref int next) + { + while (next < _verified.Count && _verified[next].Offset < offset) next++; + return next < _verified.Count && _verified[next].Offset == offset + && references.UnaffectedBy(_verified[next].References, dropped); + } + } + /// Finds additional owners whose records a rewrite would leave out. internal static HashSet Inspect( Stream stored, PartitionFraming.Tags tags, int width, R22Transcoder transcoder, MemoryStream chainBuffer, IReadOnlySet? knownDropped = null, Dictionary? keptCounts = null, - Action? observe = null, string? censusPartition = null) + Action? observe = null, string? censusPartition = null, + InspectionResults? previousInspection = null) { ulong terminator = width == 8 ? ulong.MaxValue : uint.MaxValue; var dropped = new HashSet(); var blockDropped = new HashSet(); var kept = new HashSet(); - int block = -1; + int block = -1, nextPrev = 0; bool countKept = keptCounts != null && knownDropped is { Count: > 0 }; if (!PartitionFraming.WalkStream(stored, tags, width, record => { @@ -152,7 +175,15 @@ internal static HashSet Inspect( if (transcoder.HasSourceClass(tag)) { shouldDrop = !transcoder.CanWriteRecord(tag, isElement); - if (!shouldDrop) shouldDrop = transcoder.Payload(record.Body) is null; + if (!shouldDrop) + { + if (previousInspection == null) + shouldDrop = transcoder.Payload(record.Body) is null; + else if (knownDropped == null) + shouldDrop = previousInspection.InspectPayload(record, transcoder) is null; + else if (!previousInspection.RemainsWritable(record.Offset, knownDropped, ref nextPrev)) + shouldDrop = transcoder.Payload(record.Body) is null; + } } if (shouldDrop) { diff --git a/src/RvtIO/Writing/DowngradeWriter.cs b/src/RvtIO/Writing/DowngradeWriter.cs index 3664fd3e..883d2bef 100644 --- a/src/RvtIO/Writing/DowngradeWriter.cs +++ b/src/RvtIO/Writing/DowngradeWriter.cs @@ -144,18 +144,33 @@ private static DowngradeWriteResult Transcode( var knownOwners = new HashSet(); var knownDropped = new HashSet(); ElementCensus? projectElements = new(sourceDoc, sourceWidth); + // The browser reads the same immutable File on each pass. Keep bounded evidence + // from the first pass so the closure need only revisit records affected by omissions. + const int inspectionLimit = 2_097_152; + const int referenceLimit = 4_194_304; + int remainingInspections = inspectionLimit; + R22Transcoder.DropReferenceLog? dropReferences = OperatingSystem.IsBrowser() + ? new(referenceLimit) : null; + var inspections = new Dictionary(StringComparer.OrdinalIgnoreCase); // The last copy in numeric partition order supplies the class for the omissions report. foreach (var (path, open) in sourcePartitions.OrderBy(p => int.Parse(p.Path.AsSpan("Partitions/".Length), System.Globalization.CultureInfo.InvariantCulture))) { using var partition = open(); string name = path["Partitions/".Length..]; + var inspection = dropReferences != null && remainingInspections > 0 + ? new DowngradePartitionRewriter.InspectionResults(dropReferences, remainingInspections) : null; knownDropped.UnionWith(DowngradePartitionRewriter.Inspect(partition, sourceTags, sourceWidth, transcoder, chainBuffer, observe: record => { knownOwners.Add(record.Owner); projectElements.Observe(record, name); - }, censusPartition: planResult.CountInWriter ? name : null)); + }, censusPartition: planResult.CountInWriter ? name : null, previousInspection: inspection)); + if (inspection is { Count: > 0 }) + { + inspections.Add(path, inspection); + remainingInspections -= inspection.Count; + } if (planResult.CountInWriter) projectElements.CheckClassTags(); } if (planResult.CountInWriter && afterCensus is not null) @@ -194,7 +209,7 @@ private static DowngradeWriteResult Transcode( using var partition = open(); var ownersByBlock = new Dictionary(); added.UnionWith(DowngradePartitionRewriter.Inspect(partition, sourceTags, sourceWidth, transcoder, chainBuffer, - knownDropped, ownersByBlock)); + knownDropped, ownersByBlock, previousInspection: inspections.GetValueOrDefault(path))); survivingOwnersByPartition.Add(path, ownersByBlock); } if (sourceElemRows is not null) @@ -215,6 +230,9 @@ private static DowngradeWriteResult Transcode( transcoder.SetDroppedElementIds(knownDropped); } + inspections.Clear(); + dropReferences = null; + byte[] patchedBfi; try { patchedBfi = BasicFileInfoPatcher.Patch(sourceBfi, planResult.SourceRelease, planResult.TargetRelease, sourceBfiProfile); } catch (InvalidDataException exception) diff --git a/tests/RvtIO.Tests/R22TranscoderTests.cs b/tests/RvtIO.Tests/R22TranscoderTests.cs index 313258ea..cbfd29bb 100644 --- a/tests/RvtIO.Tests/R22TranscoderTests.cs +++ b/tests/RvtIO.Tests/R22TranscoderTests.cs @@ -71,6 +71,16 @@ public void Payload_PrunesExplicitlyDroppedIdsFromSameWidthRecords() }); var transcoder = new R22Transcoder(schema, schema, 4); Assert.Equal(record, transcoder.Payload(record, 0, record.Length)); + var log = new R22Transcoder.DropReferenceLog(8); + Assert.Equal(record, transcoder.PayloadWithDropReferences(record, log, out var proof)); + Assert.NotNull(proof); + Assert.True(log.UnaffectedBy(proof.Value, new HashSet { 8 })); + Assert.False(log.UnaffectedBy(proof.Value, new HashSet { 7 })); + Assert.False(log.UnaffectedBy(proof.Value, new HashSet { 42 })); + + var limited = new R22Transcoder.DropReferenceLog(1); + Assert.Equal(record, transcoder.PayloadWithDropReferences(record, limited, out var incomplete)); + Assert.Null(incomplete); var walker = new WideBlockWalker(schema, (owner, field) => WideBlockWalker.AllItemsKeyPrefix + owner.Name + "." + field.Name, []); var walk = walker.Run(record, 0, record.Length, 30);