diff --git a/README.md b/README.md
index 99148f86..923e787f 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
@@ -216,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.Cli/DowngradeCommand.cs b/src/RvtIO.Cli/DowngradeCommand.cs
index 1da5c788..0b64e7f7 100644
--- a/src/RvtIO.Cli/DowngradeCommand.cs
+++ b/src/RvtIO.Cli/DowngradeCommand.cs
@@ -69,8 +69,13 @@ 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,
+ countDuringWrite: outputPath is not null && !check);
+ }
catch (RvtInputException exception)
{
return End(error, reportPath, RvtExitCodes.InputError, exception.Kind, exception.Message, sourceName, profileName, rule);
@@ -84,33 +89,41 @@ 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)
{
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 =>
{
if (WriteReport(error, reportPath, WriteReportBody(result, sourceName, profileName, prepared),
RvtExitCodes.Success) != RvtExitCodes.Success)
throw new ReportWriteFailedException();
+ }, 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)}.");
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 d1dbd881..e67e3ca8 100644
--- a/src/RvtIO/Parsing/PartitionFraming.cs
+++ b/src/RvtIO/Parsing/PartitionFraming.cs
@@ -92,20 +92,37 @@ 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, 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, MemoryStream? chainBuffer = 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();
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");
@@ -117,12 +134,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 +156,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 +214,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 +225,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 +371,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 +463,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 +500,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/Parsing/R22Transcoder.cs b/src/RvtIO/Parsing/R22Transcoder.cs
index aecf0874..271936e8 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;
@@ -523,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;
@@ -543,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).
@@ -550,7 +592,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 +618,22 @@ 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);
+
+ 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)
@@ -588,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)
{
@@ -601,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;
@@ -615,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);
@@ -649,7 +715,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 +754,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,9 +822,9 @@ private static void RekeyArchive(byte[] payload, List 0 ? c.ObjectStarts[0] : objectEnd;
- var bySlot = new List[n + 1];
- for (int i = 0; i <= n; i++) bySlot[i] = [];
+ if (n == 0) return Apply(c.D, offset, objectEnd, c.Edits);
+ int rootEnd = c.ObjectStarts[0];
+ var bySlot = new List?[n + 1];
foreach (var edit in c.Edits)
{
int slot = edit.Slot is int objectSlot ? objectSlot + 1 : 0;
@@ -777,7 +843,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();
@@ -796,47 +862,67 @@ 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, 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], CollectionsMarshal.AsSpan(bySlot[q + 1])));
+ }
+ var output = new byte[length];
+ 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;
- output.Write(Apply(c.D, start, end, bySlot[q + 1]));
+ written += ApplyTo(c.D, start, end, CollectionsMarshal.AsSpan(bySlot[q + 1]), output.AsSpan(written));
}
- return output.ToArray();
+ return output;
+ }
+
+ private static int EditedLength(int length, ReadOnlySpan 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)
+ 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, 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();
- int growth = 0;
- 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];
- growth = checked(growth + edit.Replacement.Length - (edit.End - edit.Start));
+ 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;
}
- var output = new byte[end - start + growth];
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");
- 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 +1068,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;
@@ -1005,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);
@@ -1047,7 +1134,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 +1163,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 +1178,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));
@@ -1107,7 +1193,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));
@@ -1215,7 +1301,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)
@@ -1381,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)
@@ -1389,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/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/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..e02e405e 100644
--- a/src/RvtIO/Writing/DowngradePartitionRewriter.cs
+++ b/src/RvtIO/Writing/DowngradePartitionRewriter.cs
@@ -1,6 +1,6 @@
using System.Buffers.Binary;
+using System.IO.Compression;
using ICSharpCode.SharpZipLib.Checksum;
-using ICSharpCode.SharpZipLib.Zip.Compression;
using RvtIO.Parsing;
namespace RvtIO.Writing;
@@ -24,378 +24,186 @@ 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, MemoryStream chainBuffer,
PartitionFraming.Tags sourceTags, int sourceWidth,
PartitionFraming.Tags targetTags, int targetWidth,
R22Transcoder transcoder,
- IReadOnlySet? knownDropped,
- Func? tagFixer,
- out IReadOnlySet droppedOwners,
- ProjectEdits? projectEdits = null)
+ IReadOnlySet knownDropped,
+ IReadOnlyDictionary keptCounts,
+ Func, byte[], byte[]?>? tagFixer,
+ 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.");
- 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;
- }
-
- if (expectedOwners == uint.MaxValue)
- {
- // 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;
- }
+ bool inProjectBlock = false;
- 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)
+ var blocks = new PartitionFraming.BlockCallbacks(
+ (index, key, expectedOwners) =>
{
- 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.
+ 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),
+ () =>
{
- 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, 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))
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 _);
+ }, out string? failure, out _, chainBuffer: chainBuffer);
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)
+ internal sealed class InspectionResults(R22Transcoder.DropReferenceLog references, int limit)
{
- 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.");
+ private readonly record struct VerifiedRecord(long Offset, R22Transcoder.DropReferenceLog.Range References);
+ private readonly List _verified = [];
+ internal int Count => _verified.Count;
- ulong sourceTerminator = sourceWidth == 8 ? ulong.MaxValue : uint.MaxValue;
- var owners = new HashSet();
- var dropped = new HashSet();
- int pos = 8;
- for (; ; )
+ internal byte[]? InspectPayload(PartitionFraming.Record record, R22Transcoder transcoder)
{
- 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 (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 (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))));
+ 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;
}
- 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)
+ internal bool RemainsWritable(long offset, IReadOnlySet dropped, ref int next)
{
- 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;
+ while (next < _verified.Count && _verified[next].Offset < offset) next++;
+ return next < _verified.Count && _verified[next].Offset == offset
+ && references.UnaffectedBy(_verified[next].References, dropped);
}
}
- private static List ReadBlockChains(byte[] body, ref int pos, PartitionFraming.Tags tags)
+ /// 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,
+ InspectionResults? previousInspection = null)
{
- var chains = new List();
- using var inflated = new MemoryStream();
- int channel = 0;
- uint firstFlags = 0, firstOpaque = 0;
- bool inChain = false;
-
- while (true)
+ ulong terminator = width == 8 ? ulong.MaxValue : uint.MaxValue;
+ var dropped = new HashSet();
+ var blockDropped = new HashSet();
+ var kept = new HashSet();
+ int block = -1, nextPrev = 0;
+ bool countKept = keptCounts != null && knownDropped is { Count: > 0 };
+ if (!PartitionFraming.WalkStream(stored, tags, width, record =>
{
- 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.Block != block)
{
- if ((flags & 3) != 0) throw new InvalidDataException("Partition stream empty segment is chained.");
- break;
+ if (countKept && block >= 0) keptCounts![block] = (uint)kept.Count;
+ block = record.Block;
+ blockDropped.Clear();
+ kept.Clear();
}
- 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.Owner == terminator || knownDropped?.Contains(record.Owner) == true) return;
+ observe?.Invoke(record);
+ if (record.Channel == 101)
{
- if (inChain) throw new InvalidDataException("Partition stream chain starts inside a chain.");
- inChain = true;
- firstFlags = flags & ~3u;
- firstOpaque = opaque;
- channel = (int)index;
+ if (countKept) kept.Add(record.Owner);
+ return;
}
- else if (!inChain) throw new InvalidDataException("Partition stream chain continuation starts no chain.");
- if (mode is 0 or 1)
+ 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))
{
- inChain = false;
- chains.Add(new ChainSpan(channel, firstFlags, firstOpaque, inflated.ToArray()));
+ shouldDrop = !transcoder.CanWriteRecord(tag, isElement);
+ 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 (inChain) throw new InvalidDataException("Partition stream ends inside a chain.");
- return chains;
- }
-
- 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)
+ if (shouldDrop)
+ {
+ blockDropped.Add(record.Owner);
+ dropped.Add(record.Owner);
+ }
+ }, out var failure, out _, chainBuffer: chainBuffer))
{
- 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);
+ 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;
}
+ 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,
@@ -404,7 +212,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)
@@ -417,37 +225,36 @@ 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;
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 +289,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 = chain.Inflated.Slice(bodyAt, bodySize);
byte[]? converted;
if (projectEdits?.Replacements.TryGetValue((owner, chain.Channel), out var edit) == true)
{
@@ -490,8 +298,8 @@ void FlushBatch()
}
else
{
- 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)
@@ -499,7 +307,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.Span[2..].CopyTo(converted.AsSpan(2));
BinaryPrimitives.WriteUInt16LittleEndian(converted.AsSpan(0, 2), R22Transcoder.UnknownTag);
}
newBody = converted;
@@ -519,13 +327,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;
@@ -546,10 +354,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,
@@ -563,7 +369,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;
}
@@ -576,7 +382,7 @@ private static void WriteSplitRecord(
}
private static void WriteSegment(
- MemoryStream output,
+ PageCodec.PagedOutput output,
PartitionFraming.Tags tags,
uint flags,
uint recordCount,
@@ -585,7 +391,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/DowngradePlanner.cs b/src/RvtIO/Writing/DowngradePlanner.cs
index fddbfae5..ea38ea30 100644
--- a/src/RvtIO/Writing/DowngradePlanner.cs
+++ b/src/RvtIO/Writing/DowngradePlanner.cs
@@ -146,12 +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)
+ internal static Result Plan(string sourcePath, string profilePath, GuidRule rule, bool countElements = true,
+ MemoryStream? chainBuffer = null, bool countDuringWrite = false)
{
RvtContainerCheck.Verify(sourcePath);
RvtContainerCheck.Verify(profilePath);
@@ -174,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);
- 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;
@@ -193,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 de4500e2..883d2bef 100644
--- a/src/RvtIO/Writing/DowngradeWriter.cs
+++ b/src/RvtIO/Writing/DowngradeWriter.cs
@@ -32,20 +32,32 @@ internal static DowngradeWriteResult Write(
string sourcePath, string profilePath, string outputPath, GuidRule rule, bool includeOmittedAnalytics = false,
bool restoreLegacyAnalytics = false, bool allowLoss = false, Action? beforePublish = null)
{
- var planResult = DowngradePlanner.Plan(sourcePath, profilePath, rule);
+ 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, MemoryStream? chainBuffer = null,
+ Action? afterCensus = 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,
- includeOmittedAnalytics, restoreLegacyAnalytics, allowLoss, beforePublish);
+ using var ownedChainBuffer = chainBuffer is null ? new MemoryStream() : null;
+ return Transcode(sourcePath, profilePath, outputPath, planResult, sourceWidth, targetWidth, chainBuffer ?? ownedChainBuffer!,
+ includeOmittedAnalytics, restoreLegacyAnalytics, allowLoss, beforePublish, afterCensus);
}
private static DowngradeWriteResult Transcode(
string sourcePath, string profilePath, string outputPath, DowngradePlanner.Result planResult,
- int sourceWidth, int targetWidth, bool includeOmittedAnalytics, bool restoreLegacyAnalytics, bool allowLoss,
- Action? beforePublish)
+ int sourceWidth, int targetWidth, MemoryStream chainBuffer,
+ bool includeOmittedAnalytics, bool restoreLegacyAnalytics, bool allowLoss,
+ Action? beforePublish, Action? afterCensus)
{
var plan = planResult.Plan;
SchemaDocument sourceDoc, profileDoc;
@@ -53,13 +65,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 +86,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,12 +143,38 @@ 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)
+ 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)))
{
- var state = DowngradePartitionRewriter.Inspect(raw, sourceTags, sourceWidth, transcoder);
- knownOwners.UnionWith(state.Owners);
- knownDropped.UnionWith(state.Dropped);
+ 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, 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)
+ 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
@@ -163,15 +198,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)
+ survivingOwnersByPartition.Clear();
+ foreach (var (path, open) in sourcePartitions)
{
- var restate = DowngradePartitionRewriter.Inspect(raw, sourceTags, sourceWidth, transcoder);
- knownOwners.UnionWith(restate.Owners);
- foreach (var id in restate.Dropped)
- if (!knownDropped.Contains(id)) added.Add(id);
+ using var partition = open();
+ var ownersByBlock = new Dictionary();
+ added.UnionWith(DowngradePartitionRewriter.Inspect(partition, sourceTags, sourceWidth, transcoder, chainBuffer,
+ knownDropped, ownersByBlock, previousInspection: inspections.GetValueOrDefault(path)));
+ survivingOwnersByPartition.Add(path, ownersByBlock);
}
if (sourceElemRows is not null)
{
@@ -182,11 +221,18 @@ 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);
}
+ inspections.Clear();
+ dropReferences = null;
+
byte[] patchedBfi;
try { patchedBfi = BasicFileInfoPatcher.Patch(sourceBfi, planResult.SourceRelease, planResult.TargetRelease, sourceBfiProfile); }
catch (InvalidDataException exception)
@@ -217,7 +263,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
@@ -366,10 +413,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 +467,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 +477,18 @@ private static DowngradeWriteResult Transcode(
}
}
- int plannedDrops = knownDropped.Count;
- foreach (var (path, raw) in sourcePartitions)
+ int remainingPartitions = sourcePartitions.Count;
+ 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 +507,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,17 +515,13 @@ 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);
+ omittedProjectElements = projectElements.CountByClass(droppedOwners);
}
+ projectElements = null;
var omittedOwners = new HashSet(droppedOwners);
if (restored is not null)
{
@@ -498,7 +543,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 +553,36 @@ 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 added = DowngradePartitionRewriter.Inspect(partition, sourceTags, sourceWidth, transcoder, chainBuffer,
+ knownDropped, keptCounts);
+ 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,
+ releaseSourceBuffer: --remainingPartitions == 0);
+ }
+ 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..b544084a 100644
--- a/src/RvtIO/Writing/ElementCensus.cs
+++ b/src/RvtIO/Writing/ElementCensus.cs
@@ -10,12 +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;
+ }
+
+ internal void CheckClassTags(IReadOnlySet? onlyOwners = null)
+ {
+ 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)
+ internal static Dictionary? CountByClass(RootStorage root, SchemaDocument document, out string? failure,
+ MemoryStream? chainBuffer = null)
{
failure = null;
var schema = new FormatsSchema(document);
@@ -29,32 +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);
- var raw = new byte[stream.Length];
- stream.ReadExactly(raw);
- bool bad = false;
- bool ok = PartitionFraming.Walk(raw, 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 _);
+ 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/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/GzipMember.cs b/src/RvtIO/Writing/GzipMember.cs
index c893af22..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;
@@ -21,21 +19,23 @@ 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))
- 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;
}
}
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/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..8ff6eb76 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()
{
@@ -583,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()
{
@@ -669,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()
{
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/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/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..0c71afe9 100644
--- a/tests/RvtIO.Tests/PartitionFramingFuzzTests.cs
+++ b/tests/RvtIO.Tests/PartitionFramingFuzzTests.cs
@@ -99,6 +99,53 @@ 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);
+ }
+
+ [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)
+ {
+ Assert.InRange(buffer.Length, 1, PagedGzipStream.PageStride);
+ return base.Read(buffer);
+ }
+ }
+
[Fact]
public void Walk_ChecksTheTagOfEveryPageTailBeforeItReadsARecord()
{
diff --git a/tests/RvtIO.Tests/R22TranscoderTests.cs b/tests/RvtIO.Tests/R22TranscoderTests.cs
index 75e39c76..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);
@@ -119,6 +129,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 +176,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()
{