From a4c850752da8e65e062d3bcb897bf7958db3346e Mon Sep 17 00:00:00 2001 From: MarcT1me Date: Mon, 16 Nov 2026 21:34:54 +0700 Subject: [PATCH 1/9] [KERNEL] [DOCS] StellarEngine 0.9.0: contracts of the file system and the resources The file system - FilePath: domain://path as a value, one form for every path (FileSystemNames). - Domains mounted by drivers of open schemes (DomainScheme); IDomain holds the state of its source, DomainCapabilities says what it can do. - IFileSystem routes paths to domains; FileEntry with a revision, ContentType, atomic writes, random access, memory without a copy, watches. The resources - IResource: a lease with a reference count, a snapshot of the data. - IResourceSystem: policies Stream, Cache, Keep; a cache budget. Versions - Orchestra, Kernel, Core and Runtime 0.9.0; new modules start at 0.9.0. Docs - Modules: an entry point is optional for a module, required for the application. --- .../Stellar.Core.Tests/FilePathTests.cs | 157 +++++++++++ Docs/Engine/Modules.md | 4 + .../Stellar.Kernel/FileSystem/ContentType.cs | 121 +++++++++ .../FileSystem/DomainCapabilities.cs | 34 +++ .../Stellar.Kernel/FileSystem/DomainMount.cs | 24 ++ .../FileSystem/DomainNotFoundException.cs | 16 ++ .../Stellar.Kernel/FileSystem/DomainScheme.cs | 77 ++++++ .../Stellar.Kernel/FileSystem/DomainType.cs | 17 -- .../FileSystem/Dto/IFileInfo.cs | 36 --- .../FileSystem/Dto/IFileStream.cs | 28 -- .../Stellar.Kernel/FileSystem/FileChange.cs | 37 +++ .../Stellar.Kernel/FileSystem/FileEntry.cs | 52 ++++ .../FileSystem/FileOpenOptions.cs | 62 +++++ .../Stellar.Kernel/FileSystem/FilePath.cs | 245 ++++++++++++++++++ .../FileSystem/FileSystemExtensions.cs | 116 +++++++++ .../FileSystem/FileSystemNames.cs | 167 ++++++++++++ .../FileSystem/IContentTypeRegistry.cs | 36 +++ .../Stellar.Kernel/FileSystem/IDomain.cs | 132 +++++++++- .../Stellar.Kernel/FileSystem/IFile.cs | 26 -- .../Stellar.Kernel/FileSystem/IFileDriver.cs | 33 +++ .../Stellar.Kernel/FileSystem/IFileSystem.cs | 91 +++++++ .../Stellar.Kernel/FileSystem/IFileType.cs | 22 -- .../Stellar.Kernel/FileSystem/IPath.cs | 33 --- .../FileSystem/IRandomAccessFile.cs | 42 +++ .../Stellar.Kernel/FileSystem/IResource.cs | 18 -- .../FileSystem/IResourceOrchestrator.cs | 47 ---- .../FileSystem/Provider/IFileProvider.cs | 67 ----- .../Provider/IFileProviderFactory.cs | 24 -- .../FileSystem/Provider/IResourceFactory.cs | 23 -- .../FileSystem/Resources/IResource.cs | 83 ++++++ .../FileSystem/Resources/IResourceSystem.cs | 82 ++++++ .../FileSystem/Resources/ResourcePolicy.cs | 29 +++ .../Stellar.Kernel/Stellar.Kernel.csproj | 1 + Shared/Build/Stellar.Versions.props | 10 +- 34 files changed, 1633 insertions(+), 359 deletions(-) create mode 100644 Core/tests/Managed/Stellar.Core.Tests/FilePathTests.cs create mode 100644 Kernel/src/Managed/Stellar.Kernel/FileSystem/ContentType.cs create mode 100644 Kernel/src/Managed/Stellar.Kernel/FileSystem/DomainCapabilities.cs create mode 100644 Kernel/src/Managed/Stellar.Kernel/FileSystem/DomainMount.cs create mode 100644 Kernel/src/Managed/Stellar.Kernel/FileSystem/DomainNotFoundException.cs create mode 100644 Kernel/src/Managed/Stellar.Kernel/FileSystem/DomainScheme.cs delete mode 100644 Kernel/src/Managed/Stellar.Kernel/FileSystem/DomainType.cs delete mode 100644 Kernel/src/Managed/Stellar.Kernel/FileSystem/Dto/IFileInfo.cs delete mode 100644 Kernel/src/Managed/Stellar.Kernel/FileSystem/Dto/IFileStream.cs create mode 100644 Kernel/src/Managed/Stellar.Kernel/FileSystem/FileChange.cs create mode 100644 Kernel/src/Managed/Stellar.Kernel/FileSystem/FileEntry.cs create mode 100644 Kernel/src/Managed/Stellar.Kernel/FileSystem/FileOpenOptions.cs create mode 100644 Kernel/src/Managed/Stellar.Kernel/FileSystem/FilePath.cs create mode 100644 Kernel/src/Managed/Stellar.Kernel/FileSystem/FileSystemExtensions.cs create mode 100644 Kernel/src/Managed/Stellar.Kernel/FileSystem/FileSystemNames.cs create mode 100644 Kernel/src/Managed/Stellar.Kernel/FileSystem/IContentTypeRegistry.cs delete mode 100644 Kernel/src/Managed/Stellar.Kernel/FileSystem/IFile.cs create mode 100644 Kernel/src/Managed/Stellar.Kernel/FileSystem/IFileDriver.cs create mode 100644 Kernel/src/Managed/Stellar.Kernel/FileSystem/IFileSystem.cs delete mode 100644 Kernel/src/Managed/Stellar.Kernel/FileSystem/IFileType.cs delete mode 100644 Kernel/src/Managed/Stellar.Kernel/FileSystem/IPath.cs create mode 100644 Kernel/src/Managed/Stellar.Kernel/FileSystem/IRandomAccessFile.cs delete mode 100644 Kernel/src/Managed/Stellar.Kernel/FileSystem/IResource.cs delete mode 100644 Kernel/src/Managed/Stellar.Kernel/FileSystem/IResourceOrchestrator.cs delete mode 100644 Kernel/src/Managed/Stellar.Kernel/FileSystem/Provider/IFileProvider.cs delete mode 100644 Kernel/src/Managed/Stellar.Kernel/FileSystem/Provider/IFileProviderFactory.cs delete mode 100644 Kernel/src/Managed/Stellar.Kernel/FileSystem/Provider/IResourceFactory.cs create mode 100644 Kernel/src/Managed/Stellar.Kernel/FileSystem/Resources/IResource.cs create mode 100644 Kernel/src/Managed/Stellar.Kernel/FileSystem/Resources/IResourceSystem.cs create mode 100644 Kernel/src/Managed/Stellar.Kernel/FileSystem/Resources/ResourcePolicy.cs diff --git a/Core/tests/Managed/Stellar.Core.Tests/FilePathTests.cs b/Core/tests/Managed/Stellar.Core.Tests/FilePathTests.cs new file mode 100644 index 0000000..f59b7af --- /dev/null +++ b/Core/tests/Managed/Stellar.Core.Tests/FilePathTests.cs @@ -0,0 +1,157 @@ +using Stellar.Kernel.FileSystem; + +namespace Stellar.Core.Tests; + +public class FilePathTests +{ + [Theory] + [InlineData("assets://textures/hero.png", "assets", "textures/hero.png")] + [InlineData("Assets://textures/hero.png", "assets", "textures/hero.png")] + [InlineData(@"assets://textures\hero.png", "assets", "textures/hero.png")] + [InlineData("assets:///textures//./hero.png/", "assets", "textures/hero.png")] + [InlineData("assets://textures/../sounds/hit.wav", "assets", "sounds/hit.wav")] + [InlineData("assets://", "assets", "")] + [InlineData("user-data.v2://saves/1.sav", "user-data.v2", "saves/1.sav")] + public void Parse_GivesTheOneForm(string text, string domain, string value) + { + var path = FilePath.Parse(text); + + path.Domain.Should().Be(domain); + path.Value.Should().Be(value); + path.ToString().Should().Be($"{domain}://{value}"); + FilePath.Parse(path.ToString()).Should().Be(path); + } + + [Theory] + [InlineData(null)] + [InlineData("")] + [InlineData("textures/hero.png")] + [InlineData("://textures/hero.png")] + [InlineData("-assets://a")] + [InlineData("as sets://a")] + [InlineData("assets://..")] + [InlineData("assets://a/../../b")] + [InlineData("assets://C:/Windows")] + [InlineData("assets://a/b.")] + [InlineData("assets://a /b")] + [InlineData("assets://a/*.png")] + [InlineData("assets://a\u0001b")] + public void TryParse_RefusesWhatIsNotAPath(string? text) + { + FilePath.TryParse(text, out var path).Should().BeFalse(); + path.IsEmpty.Should().BeTrue(); + } + + [Fact] + public void Paths_ToOneFile_AreEqual() + { + var first = FilePath.Create("Assets", @"textures\.\hero.png"); + var second = FilePath.Parse("assets://textures/hero.png"); + + first.Should().Be(second); + (first == second).Should().BeTrue(); + first.GetHashCode().Should().Be(second.GetHashCode()); + first.Should().NotBe(FilePath.Parse("assets://textures/Hero.png")); + } + + [Fact] + public void AnAlreadyNormalPath_IsNotCopied() + { + const string value = "textures/hero.png"; + FilePath.Create("assets", value).Value.Should().BeSameAs(value); + } + + [Fact] + public void Names_AndExtensions() + { + var path = FilePath.Parse("assets://textures/hero.albedo.png"); + + path.Name.Should().Be("hero.albedo.png"); + path.Extension.Should().Be(".png"); + path.NameWithoutExtension.Should().Be("hero.albedo"); + path.Parent.Should().Be(FilePath.Parse("assets://textures")); + path.Parent.Parent.IsRoot.Should().BeTrue(); + FilePath.Root("assets").Name.Should().BeEmpty(); + } + + [Fact] + public void Root_HasNoParent() + { + var root = FilePath.Root("assets"); + + root.IsRoot.Should().BeTrue(); + root.Invoking(r => r.Parent).Should().Throw(); + default(FilePath).Invoking(p => p.Parent).Should().Throw(); + } + + [Fact] + public void Combine_StaysInsideTheDomain() + { + var textures = FilePath.Parse("assets://textures"); + + textures.Combine("hero.png").Should().Be(FilePath.Parse("assets://textures/hero.png")); + textures.Combine("../sounds/hit.wav").Should().Be(FilePath.Parse("assets://sounds/hit.wav")); + textures.Combine("/levels/1.json").Should().Be(FilePath.Parse("assets://levels/1.json")); + FilePath.Root("assets").Combine("a").Should().Be(FilePath.Parse("assets://a")); + textures.Combine("").Should().Be(textures); + textures.Invoking(t => t.Combine("../../escape")).Should().Throw(); + } + + [Fact] + public void IsInside_FollowsSegments() + { + var textures = FilePath.Parse("assets://textures"); + + FilePath.Parse("assets://textures/hero.png").IsInside(textures).Should().BeTrue(); + FilePath.Parse("assets://textures/ui/button.png").IsInside(textures).Should().BeTrue(); + FilePath.Parse("assets://textures2/hero.png").IsInside(textures).Should().BeFalse(); + textures.IsInside(textures).Should().BeFalse(); + textures.IsInside(FilePath.Root("assets")).Should().BeTrue(); + FilePath.Parse("mods://textures/hero.png").IsInside(textures).Should().BeFalse(); + } + + [Fact] + public void WithDomain_KeepsThePath() + { + FilePath.Parse("base://textures/hero.png").WithDomain("mods") + .Should().Be(FilePath.Parse("mods://textures/hero.png")); + } + + [Fact] + public void TheEmptyPath_NamesNothing() + { + var empty = default(FilePath); + + empty.IsEmpty.Should().BeTrue(); + empty.IsRoot.Should().BeFalse(); + empty.ToString().Should().BeEmpty(); + empty.Should().NotBe(FilePath.Root("assets")); + empty.Invoking(p => p.Combine("a")).Should().Throw(); + } + + [Fact] + public void Schemes_AreFoldedNames() + { + new DomainScheme("DIR").Should().Be(DomainScheme.Directory); + new DomainScheme("zip").Name.Should().Be("zip"); + FluentActions.Invoking(() => new DomainScheme("no scheme")).Should().Throw(); + } + + [Fact] + public void ContentTypes_ComparedByValue() + { + new ContentType("Text/Plain", ContentKind.Text, "UTF-8").Should().Be(ContentType.PlainText); + ContentType.PlainText.ToString().Should().Be("text/plain; charset=utf-8"); + default(ContentType).IsUnknown.Should().BeTrue(); + default(ContentType).MediaType.Should().Be(ContentType.OctetStream.MediaType); + FluentActions.Invoking(() => new ContentType("png", ContentKind.Binary)).Should().Throw(); + } + + [Fact] + public void OpenOptions_TellWrites() + { + FileOpenOptions.Read.Writes.Should().BeFalse(); + FileOpenOptions.Write.Writes.Should().BeTrue(); + FileOpenOptions.Replace.Flags.Should().HaveFlag(FileOpenFlags.Atomic); + } +} diff --git a/Docs/Engine/Modules.md b/Docs/Engine/Modules.md index 9cd3816..90f2f48 100644 --- a/Docs/Engine/Modules.md +++ b/Docs/Engine/Modules.md @@ -79,6 +79,10 @@ on, directly or not, every module after the ones it depends on. `Stellar.Runtime above the core into a load context of its own, starts their entry points level by level, then the application. See [Runtime](../Architecture/Runtime.md). +An entry point (a `StellarEntryPoint` marked `[StellarEntryPoint]`) is optional for a module: one without it is a +library, loaded for the modules that use it, and takes no part in the start, the stop or the loops of the engine. +The application must have one. + ## The native part A native project of a module imports two shared files: diff --git a/Kernel/src/Managed/Stellar.Kernel/FileSystem/ContentType.cs b/Kernel/src/Managed/Stellar.Kernel/FileSystem/ContentType.cs new file mode 100644 index 0000000..bc56b8a --- /dev/null +++ b/Kernel/src/Managed/Stellar.Kernel/FileSystem/ContentType.cs @@ -0,0 +1,121 @@ +using System; + +namespace Stellar.Kernel.FileSystem; + +/// +/// How the bytes of a file are to be read: as bytes or as text. +/// +public enum ContentKind : byte +{ + /// Bytes: images, sounds, meshes, packed data. + Binary, + + /// Text in a : JSON, shaders, scripts, localization. + Text +} + +/// +/// What a file holds: a media type, such as image/png, and whether it is text or bytes. +/// +/// +/// The content type says how to read a file, never what the file becomes: one JSON file may give the asset +/// system a material, a level and a dozen prefabs. Assets are decided above the file system. +/// default(ContentType) is the unknown content (), read as +/// . +/// +public readonly struct ContentType + : IEquatable +{ + private readonly string? _mediaType; + + /// + /// Gets the media type; application/octet-stream when unknown. + /// + public string MediaType => _mediaType ?? "application/octet-stream"; + + /// + /// Gets whether the content is text or bytes. + /// + public ContentKind Kind { get; } + + /// + /// Gets the encoding of text, such as utf-8; null for bytes or when unknown. + /// + public string? Charset { get; } + + /// + /// Gets whether this is the unknown content, default(ContentType). + /// + public bool IsUnknown => _mediaType is null; + + /// + /// Gets whether the content is text. + /// + public bool IsText => Kind == ContentKind.Text; + + /// + /// Makes a content type. + /// + /// The media type, type/subtype, such as image/png. + /// Whether the content is text or bytes. + /// The encoding of text, such as utf-8; null for bytes or when unknown. + /// Thrown if is not type/subtype. + public ContentType(string mediaType, ContentKind kind, string? charset = null) + { + if (mediaType is null) throw new ArgumentNullException(nameof(mediaType)); + + var slash = mediaType.IndexOf('/'); + if (slash <= 0 + || slash == mediaType.Length - 1 + || mediaType.IndexOf('/', slash + 1) >= 0 + || mediaType.IndexOf(' ') >= 0) + throw new ArgumentException($"'{mediaType}' is not a media type: expected type/subtype", nameof(mediaType)); + + _mediaType = mediaType.ToLowerInvariant(); + Kind = kind; + Charset = charset?.ToLowerInvariant(); + } + + #region Defaults + + /// Bytes of no known type. + public static ContentType OctetStream { get; } = new("application/octet-stream", ContentKind.Binary); + + /// Plain text in UTF-8. + public static ContentType PlainText { get; } = new("text/plain", ContentKind.Text, "utf-8"); + + #endregion + + #region Utility functions + + /// + public bool Equals(ContentType other) => + string.Equals(_mediaType, other._mediaType, StringComparison.Ordinal) + && Kind == other.Kind + && string.Equals(Charset, other.Charset, StringComparison.Ordinal); + + /// + public override bool Equals(object? obj) => + obj is ContentType other && Equals(other); + + /// + public override int GetHashCode() => HashCode.Combine(_mediaType, Kind, Charset); + + /// + /// Writes the content type as a media type with its charset, such as text/plain; charset=utf-8. + /// + /// The text of the content type. + public override string ToString() => Charset is null ? MediaType : $"{MediaType}; charset={Charset}"; + + #endregion + + #region Operators + + /// Compares two content types by value. + public static bool operator ==(ContentType left, ContentType right) => left.Equals(right); + + /// Compares two content types by value. + public static bool operator !=(ContentType left, ContentType right) => !left.Equals(right); + + #endregion +} diff --git a/Kernel/src/Managed/Stellar.Kernel/FileSystem/DomainCapabilities.cs b/Kernel/src/Managed/Stellar.Kernel/FileSystem/DomainCapabilities.cs new file mode 100644 index 0000000..055fab3 --- /dev/null +++ b/Kernel/src/Managed/Stellar.Kernel/FileSystem/DomainCapabilities.cs @@ -0,0 +1,34 @@ +using System; + +namespace Stellar.Kernel.FileSystem; + +/// +/// What a domain can do. A call it cannot do throws , before any work. +/// +[Flags] +public enum DomainCapabilities +{ + /// Nothing. + None = 0, + + /// Opens files for reading. + Read = 1 << 0, + + /// Creates, writes, moves and deletes files and directories. + Write = 1 << 1, + + /// Lists the files of a directory. + Enumerate = 1 << 2, + + /// Reports the changes of its files (). + Watch = 1 << 3, + + /// Reads at any offset without a stream (). + RandomAccess = 1 << 4, + + /// Holds files in memory and hands them out without a copy (). + Memory = 1 << 5, + + /// Replaces a file as a whole or not at all (). + AtomicWrite = 1 << 6 +} diff --git a/Kernel/src/Managed/Stellar.Kernel/FileSystem/DomainMount.cs b/Kernel/src/Managed/Stellar.Kernel/FileSystem/DomainMount.cs new file mode 100644 index 0000000..a899515 --- /dev/null +++ b/Kernel/src/Managed/Stellar.Kernel/FileSystem/DomainMount.cs @@ -0,0 +1,24 @@ +using System.Collections.Generic; + +namespace Stellar.Kernel.FileSystem; + +/// +/// What to mount: the name of the domain, its driver and where the driver finds it. +/// +/// +/// The source is for the driver alone, and the only place where a location of the machine may appear. The +/// runtime resolves it from the configuration ($(StellarRoot), the project, the folders of the user); a +/// game names domains, never sources. +/// Examples: dir takes a directory; asm an assembly name; zip the path of an archive in +/// another domain (dlc://pack.zip); overlay the domains of its layers, first wins +/// (mods,dlc,base). +/// +/// The name of the domain, in . +/// The driver that mounts it. +/// Where the driver finds the domain, in the terms of the driver. +/// Settings of the driver, such as readonly=true; null for none. +public readonly record struct DomainMount( + string Name, + DomainScheme Scheme, + string Source, + IReadOnlyDictionary? Options = null); diff --git a/Kernel/src/Managed/Stellar.Kernel/FileSystem/DomainNotFoundException.cs b/Kernel/src/Managed/Stellar.Kernel/FileSystem/DomainNotFoundException.cs new file mode 100644 index 0000000..c4087d1 --- /dev/null +++ b/Kernel/src/Managed/Stellar.Kernel/FileSystem/DomainNotFoundException.cs @@ -0,0 +1,16 @@ +using System.IO; + +namespace Stellar.Kernel.FileSystem; + +/// +/// Thrown when a path names a domain that is not mounted. +/// +/// The name of the domain. +public sealed class DomainNotFoundException(string domain) + : IOException($"No domain '{domain}' is mounted") +{ + /// + /// Gets the name of the domain. + /// + public string Domain { get; } = domain; +} diff --git a/Kernel/src/Managed/Stellar.Kernel/FileSystem/DomainScheme.cs b/Kernel/src/Managed/Stellar.Kernel/FileSystem/DomainScheme.cs new file mode 100644 index 0000000..f875c40 --- /dev/null +++ b/Kernel/src/Managed/Stellar.Kernel/FileSystem/DomainScheme.cs @@ -0,0 +1,77 @@ +using System; + +namespace Stellar.Kernel.FileSystem; + +/// +/// The kind of a domain: which driver mounts it, such as dir, asm or zip. +/// +/// +/// A scheme is an open set: a driver brings its own (), so a module, a tool +/// or a game adds archives, network shares or a file system of its own world without touching the engine. +/// The names follow . The well-known ones below are conventions, not a list: +/// a file system has only the drivers registered in it. +/// +public readonly struct DomainScheme + : IEquatable +{ + /// + /// Gets the name of the scheme; an empty string for default(DomainScheme). + /// + public string Name => _name ?? string.Empty; + + // A field, not the C# 14 'field' keyword: the SDK of global.json is .NET 9 (C# 13) + private readonly string? _name; + + /// + /// Makes a scheme. + /// + /// The name of the scheme. + /// Thrown if is not a valid name. + public DomainScheme(string name) + { + // ReSharper disable once RedundantArgumentDefaultValue + _name = FileSystemNames.NormalizeName(name, nameof(name)); + } + + #region Defaults + + /// A directory of the machine. + public static DomainScheme Directory { get; } = new("dir"); + + /// The resources embedded in an assembly. + public static DomainScheme Assembly { get; } = new("asm"); + + /// Files held in memory: tests, generated data. + public static DomainScheme Memory { get; } = new("mem"); + + /// Several domains in layers, the first that has a file wins: mods over DLC over the game. + public static DomainScheme Overlay { get; } = new("overlay"); + + #endregion + + #region Utility functions + + /// + public bool Equals(DomainScheme other) => string.Equals(Name, other.Name, StringComparison.Ordinal); + + /// + public override bool Equals(object? obj) => obj is DomainScheme other && Equals(other); + + /// + public override int GetHashCode() => StringComparer.Ordinal.GetHashCode(Name); + + /// + public override string ToString() => Name; + + #endregion + + #region Operators + + /// Compares two schemes by name. + public static bool operator ==(DomainScheme left, DomainScheme right) => left.Equals(right); + + /// Compares two schemes by name. + public static bool operator !=(DomainScheme left, DomainScheme right) => !left.Equals(right); + + #endregion +} diff --git a/Kernel/src/Managed/Stellar.Kernel/FileSystem/DomainType.cs b/Kernel/src/Managed/Stellar.Kernel/FileSystem/DomainType.cs deleted file mode 100644 index 8afe468..0000000 --- a/Kernel/src/Managed/Stellar.Kernel/FileSystem/DomainType.cs +++ /dev/null @@ -1,17 +0,0 @@ -namespace Stellar.Kernel.FileSystem; - -/// -/// Specifies the kind of file system domain. -/// -public enum DomainType : byte -{ - /// - /// A regular directory on the operating system's file system. - /// - Directory, - - /// - /// An assembly file (e.g., .dll or .exe) that may contain embedded resources. - /// - Assembly -} diff --git a/Kernel/src/Managed/Stellar.Kernel/FileSystem/Dto/IFileInfo.cs b/Kernel/src/Managed/Stellar.Kernel/FileSystem/Dto/IFileInfo.cs deleted file mode 100644 index bc66e89..0000000 --- a/Kernel/src/Managed/Stellar.Kernel/FileSystem/Dto/IFileInfo.cs +++ /dev/null @@ -1,36 +0,0 @@ -using System; -using Stellar.Kernel.FileSystem.Provider; -using Stellar.Kernel.Quantization; - -namespace Stellar.Kernel.FileSystem; - -/// -/// Provides metadata information about a file. -/// -/// -/// This interface is returned by and contains -/// basic file attributes such as name, size, and timestamps. -/// -public interface IFileInfo - : IQuantumObject -{ - /// - /// Gets the file name (the last segment of the path). - /// - string Name { get; } - - /// - /// Gets the full path of the file within its domain (as stored in ). - /// - string FullPath { get; } - - /// - /// Gets the file size in bytes. Returns -1 if the size is unknown (e.g., for virtual files). - /// - long Size { get; } - - /// - /// Gets the file creation time in UTC, or null if not supported by the underlying provider. - /// - DateTime? CreationTimeUtc { get; } -} diff --git a/Kernel/src/Managed/Stellar.Kernel/FileSystem/Dto/IFileStream.cs b/Kernel/src/Managed/Stellar.Kernel/FileSystem/Dto/IFileStream.cs deleted file mode 100644 index 41fc25e..0000000 --- a/Kernel/src/Managed/Stellar.Kernel/FileSystem/Dto/IFileStream.cs +++ /dev/null @@ -1,28 +0,0 @@ -using System; -using System.IO; -using Stellar.Kernel.Quantization; - -namespace Stellar.Kernel.FileSystem; - -/// -/// Provides a quantum‑aware wrapper around a raw file stream. -/// -/// -/// An combines a quantum reference -/// with a standard .NET for reading/writing content. -/// It is a meta‑quant, disposable, and equatable. The underlying stream should be disposed -/// when the quantum stream is disposed. -/// -public interface IFileStream - : IMetaQuant, IDisposable, IEquatable -{ - /// - /// Gets the quantum file associated with this stream. - /// - IFile File { get; } - - /// - /// Gets the underlying .NET stream for direct I/O operations. - /// - Stream Stream { get; } -} diff --git a/Kernel/src/Managed/Stellar.Kernel/FileSystem/FileChange.cs b/Kernel/src/Managed/Stellar.Kernel/FileSystem/FileChange.cs new file mode 100644 index 0000000..a6212ce --- /dev/null +++ b/Kernel/src/Managed/Stellar.Kernel/FileSystem/FileChange.cs @@ -0,0 +1,37 @@ +namespace Stellar.Kernel.FileSystem; + +/// +/// What happened to a watched file. +/// +public enum FileChangeKind : byte +{ + /// The file or directory appeared. + Created, + + /// The content changed. + Changed, + + /// The file or directory is gone. + Deleted, + + /// It moved from to . + Renamed, + + /// + /// Changes were lost (the source dropped them, or the domain was remounted): anything under + /// may have changed. Read it again. + /// + Invalidated +} + +/// +/// A change of a watched file or directory. +/// +/// +/// Changes come as the source reports them: an editor saving one file may give several. Who reacts to them (the +/// resource system, a hot reload) coalesces them. +/// +/// What happened. +/// The path the change is about; for , the new one. +/// The old path of a ; the empty path otherwise. +public readonly record struct FileChange(FileChangeKind Kind, FilePath Path, FilePath OldPath = default); diff --git a/Kernel/src/Managed/Stellar.Kernel/FileSystem/FileEntry.cs b/Kernel/src/Managed/Stellar.Kernel/FileSystem/FileEntry.cs new file mode 100644 index 0000000..d8357e7 --- /dev/null +++ b/Kernel/src/Managed/Stellar.Kernel/FileSystem/FileEntry.cs @@ -0,0 +1,52 @@ +using System; + +namespace Stellar.Kernel.FileSystem; + +/// +/// Whether an entry is a file or a directory. +/// +public enum FileEntryKind : byte +{ + /// A file. + File, + + /// A directory. + Directory +} + +/// +/// What is known of a file or a directory at one moment: the answer of a domain, not a handle. +/// +/// +/// An entry does not follow the file: read it again, or watch the file (), to see a change. +/// +/// The path of the entry. +/// Whether it is a file or a directory. +/// The length of a file in bytes; 0 for a directory; -1 when the domain cannot tell. +/// When the entry was created, if the domain knows. +/// When the entry was last written, if the domain knows. +/// What the file holds; the unknown content for a directory. +/// +/// Changes whenever the content changes, as far as the domain can tell: the time of the last write, a counter, a +/// hash. Equal revisions of one path mean the same bytes; 0 when the domain cannot tell, and then nothing can be +/// assumed. Caches compare it. +/// +public readonly record struct FileEntry( + FilePath Path, + FileEntryKind Kind, + long Length, + DateTime? CreationTimeUtc, + DateTime? LastWriteTimeUtc, + ContentType Content, + long Revision) +{ + /// + /// Gets whether the entry is a file. + /// + public bool IsFile => Kind == FileEntryKind.File; + + /// + /// Gets whether the entry is a directory. + /// + public bool IsDirectory => Kind == FileEntryKind.Directory; +} diff --git a/Kernel/src/Managed/Stellar.Kernel/FileSystem/FileOpenOptions.cs b/Kernel/src/Managed/Stellar.Kernel/FileSystem/FileOpenOptions.cs new file mode 100644 index 0000000..5df91dd --- /dev/null +++ b/Kernel/src/Managed/Stellar.Kernel/FileSystem/FileOpenOptions.cs @@ -0,0 +1,62 @@ +using System; +using System.IO; + +namespace Stellar.Kernel.FileSystem; + +/// +/// How a file is opened, beyond its mode and access. +/// +[Flags] +public enum FileOpenFlags +{ + /// Nothing more. + None = 0, + + /// + /// The file is replaced as a whole when the stream is closed, or not at all if the process stops first: the + /// domain writes beside the file and swaps it in. For saves and settings. Needs + /// . + /// + Atomic = 1 << 0, + + /// A hint: the file is read from start to end once. + Sequential = 1 << 1, + + /// A hint: the file is read at scattered offsets. + RandomAccess = 1 << 2 +} + +/// +/// How to open a file: the mode and access of and the flags of the engine. +/// +/// Whether the file must exist, is created, truncated or appended to. +/// Read, write, or both. +/// Atomic replacement and hints. +public readonly record struct FileOpenOptions( + FileMode Mode, + FileAccess Access, + FileOpenFlags Flags = FileOpenFlags.None) +{ + /// + /// Gets whether these options change the file. + /// + public bool Writes => + (Access & FileAccess.Write) != 0 || + Mode is FileMode.Create or FileMode.CreateNew or FileMode.Truncate or FileMode.Append; + + #region Defaults + + /// Reads a file that exists. + public static FileOpenOptions Read { get; } = new(FileMode.Open, FileAccess.Read); + + /// Creates a file, or truncates the one that exists, and writes it. + public static FileOpenOptions Write { get; } = new(FileMode.Create, FileAccess.Write); + + /// Writes at the end of a file, creating it if needed. + public static FileOpenOptions Append { get; } = new(FileMode.Append, FileAccess.Write); + + /// Replaces a file as a whole, or leaves it as it was (). + public static FileOpenOptions Replace { get; } = new(FileMode.Create, FileAccess.Write, FileOpenFlags.Atomic); + + #endregion +} diff --git a/Kernel/src/Managed/Stellar.Kernel/FileSystem/FilePath.cs b/Kernel/src/Managed/Stellar.Kernel/FileSystem/FilePath.cs new file mode 100644 index 0000000..d79d937 --- /dev/null +++ b/Kernel/src/Managed/Stellar.Kernel/FileSystem/FilePath.cs @@ -0,0 +1,245 @@ +using System; + +namespace Stellar.Kernel.FileSystem; + +/// +/// The address of a file or a directory: a domain and a path inside it, written domain://path. +/// +/// +/// A path is a value, not a quant: it allocates nothing beyond its two strings, compares by value and is +/// checked once, when it is made. Every path is in the one form of , so two paths to +/// the same file are equal, and no path leaves its domain. +/// The domain is a name mounted in an , never a location of the machine: +/// assets://textures/hero.png, not C:\Game\textures\hero.png. Where the domain lies is the business of +/// the driver that mounted it. +/// Paths compare by ordinal: whether a.png and A.png are one file is up to the domain, and the +/// engine never relies on it. +/// default(FilePath) is the empty path (); it names nothing. +/// +public readonly struct FilePath + : IEquatable, IComparable +{ + /// + /// What separates the domain from the path in the text of a path. + /// + public const string DomainSeparator = "://"; + + // Fields, not the C# 14 'field' keyword: the SDK of global.json is .NET 9 (C# 13) + private readonly string? _domain; + private readonly string? _value; + + /// + /// Gets the name of the domain. + /// + public string Domain => _domain ?? string.Empty; + + /// + /// Gets the path inside the domain, in its one form; an empty string for the root. + /// + public string Value => _value ?? string.Empty; + + /// + /// Gets whether this is the empty path, default(FilePath). + /// + public bool IsEmpty => _domain is null; + + /// + /// Gets whether this is the root of its domain. + /// + public bool IsRoot => _domain is not null && Value.Length == 0; + + /// + /// Gets the last segment: the name of the file or the directory; an empty string for the root. + /// + public string Name + { + get + { + var value = Value; + return value.Substring(value.LastIndexOf('/') + 1); + } + } + + /// + /// Gets the extension of with its dot, such as .png; an empty string if there is none. + /// + public string Extension + { + get + { + var name = Name; + var dot = name.LastIndexOf('.'); + return dot < 0 ? string.Empty : name.Substring(dot); + } + } + + /// + /// Gets without its . + /// + public string NameWithoutExtension + { + get + { + var name = Name; + var dot = name.LastIndexOf('.'); + return dot < 0 ? name : name.Substring(0, dot); + } + } + + /// + /// Gets the directory this path lies in. + /// + /// Thrown for the root and the empty path, which have none. + public FilePath Parent + { + get + { + if (_domain is null || Value.Length == 0) throw new InvalidOperationException($"'{this}' has no parent"); + var slash = Value.LastIndexOf('/'); + return new FilePath(_domain, slash < 0 ? string.Empty : Value.Substring(0, slash)); + } + } + + private FilePath(string domain, string value) + { + _domain = domain; + _value = value; + } + + /// + /// Makes the root of a domain. + /// + /// The name of the domain. + /// The root of . + public static FilePath Root(string domain) => + new(FileSystemNames.NormalizeName(domain, nameof(domain)), string.Empty); + + /// + /// Makes a path from a domain and a path inside it. + /// + /// The name of the domain. + /// The path inside the domain, in any form accepts. + /// The path. + /// Thrown if the domain or the path is not valid. + public static FilePath Create(string domain, string path) => + // ReSharper disable once RedundantArgumentDefaultValue + new(FileSystemNames.NormalizeName(domain, nameof(domain)), FileSystemNames.NormalizePath(path, nameof(path))); + + /// + /// Reads a path written domain://path. + /// + /// The text of the path. + /// The path. + /// Thrown if is not a valid path. + public static FilePath Parse(string text) => + TryParse(text, out var path) + ? path + : throw new FormatException($"'{text}' is not a path: expected domain://path"); + + /// + /// Reads a path written domain://path. + /// + /// The text of the path. + /// The path, or the empty path if is not valid. + /// true if is a valid path. + public static bool TryParse(string? text, out FilePath path) + { + path = default; + if (text is null) return false; + + var separator = text.IndexOf(DomainSeparator, StringComparison.Ordinal); + if (separator <= 0) return false; + + if (!FileSystemNames.TryNormalizeName(text.Substring(0, separator), out var domain)) + return false; + if (!FileSystemNames.TryNormalizePath(text.Substring(separator + DomainSeparator.Length), out var value)) + return false; + + path = new FilePath(domain, value); + return true; + } + + /// + /// Goes from this directory by a relative path. + /// + /// The way to go: '..' goes up, a leading '/' starts from the root of the domain. + /// The path reached. + /// Thrown if the way is not valid or goes above the root. + /// Thrown for the empty path. + public FilePath Combine(string relative) + { + if (_domain is null) throw new InvalidOperationException("The empty path cannot be combined"); + if (relative is null) throw new ArgumentNullException(nameof(relative)); + if (relative.Length == 0) return this; + + var rooted = relative[0] is '/' or '\\'; + var joined = rooted || Value.Length == 0 ? relative : Value + "/" + relative; + return new FilePath(_domain, FileSystemNames.NormalizePath(joined, nameof(relative))); + } + + /// + /// Gets the same path in another domain: a layer of an overlay, a copy, a cache. + /// + /// The name of the other domain. + /// The path inside . + public FilePath WithDomain(string domain) => + new(FileSystemNames.NormalizeName(domain, nameof(domain)), Value); + + /// + /// Gets whether this path lies inside a directory, at any depth. + /// + /// The directory. + /// true if this path is inside , but not itself. + public bool IsInside(FilePath directory) + { + if (_domain is null || directory._domain is null) return false; + if (!string.Equals(_domain, directory._domain, StringComparison.Ordinal)) return false; + if (directory.Value.Length == 0) return Value.Length > 0; + + return Value.Length > directory.Value.Length + && Value[directory.Value.Length] == '/' + && Value.StartsWith(directory.Value, StringComparison.Ordinal); + } + + #region Utility functions + + /// + public bool Equals(FilePath other) => + string.Equals(_domain, other._domain, StringComparison.Ordinal) && + string.Equals(Value, other.Value, StringComparison.Ordinal); + + /// + public override bool Equals(object? obj) => + obj is FilePath other && Equals(other); + + /// + public override int GetHashCode() => + _domain is null + ? 0 + : HashCode.Combine(StringComparer.Ordinal.GetHashCode(_domain), StringComparer.Ordinal.GetHashCode(Value)); + + /// + public int CompareTo(FilePath other) + { + var domain = string.CompareOrdinal(_domain, other._domain); + return domain != 0 ? domain : string.CompareOrdinal(Value, other.Value); + } + + /// + /// Writes the path as domain://path; the empty path as an empty string. + /// + /// The text of the path, which reads back. + public override string ToString() => _domain is null ? string.Empty : _domain + DomainSeparator + Value; + + #endregion + + #region Operators + + /// Compares two paths by value. + public static bool operator ==(FilePath left, FilePath right) => left.Equals(right); + + /// Compares two paths by value. + public static bool operator !=(FilePath left, FilePath right) => !left.Equals(right); + + #endregion +} diff --git a/Kernel/src/Managed/Stellar.Kernel/FileSystem/FileSystemExtensions.cs b/Kernel/src/Managed/Stellar.Kernel/FileSystem/FileSystemExtensions.cs new file mode 100644 index 0000000..d17e4ef --- /dev/null +++ b/Kernel/src/Managed/Stellar.Kernel/FileSystem/FileSystemExtensions.cs @@ -0,0 +1,116 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Threading; +using System.Threading.Tasks; + +namespace Stellar.Kernel.FileSystem; + +/// +/// The operations of on full paths: each finds the domain of the path and calls it. +/// +public static class FileSystemExtensions +{ + /// + /// Gets the domain of a path. + /// + /// The file system. + /// The path. + /// The domain that names. + /// Thrown for the empty path. + /// Thrown if the domain is not mounted. + public static IDomain GetDomain(this IFileSystem fileSystem, FilePath path) + { + if (path.IsEmpty) throw new ArgumentException("The empty path names no domain", nameof(path)); + return fileSystem.GetDomain(path.Domain); + } + + /// + public static bool Exists(this IFileSystem fileSystem, FilePath path) => + !path.IsEmpty && fileSystem.TryGetDomain(path.Domain, out var domain) && domain.Exists(path.Value); + + /// + public static bool TryGetEntry(this IFileSystem fileSystem, FilePath path, out FileEntry entry) + { + entry = default; + return !path.IsEmpty + && fileSystem.TryGetDomain(path.Domain, out var domain) + && domain.TryGetEntry(path.Value, out entry); + } + + /// + /// Reads what is known of a file or a directory. + /// + /// The file system. + /// The path. + /// The entry. + /// Thrown if there is nothing at . + public static FileEntry GetEntry(this IFileSystem fileSystem, FilePath path) => + fileSystem.GetDomain(path).TryGetEntry(path.Value, out var entry) + ? entry + : throw new FileNotFoundException($"Nothing at '{path}'", path.ToString()); + + /// + public static IEnumerable Enumerate(this IFileSystem fileSystem, FilePath directory, + string pattern = "*", bool recursive = false) => + fileSystem.GetDomain(directory).Enumerate(directory.Value, pattern, recursive); + + /// + public static Stream Open(this IFileSystem fileSystem, FilePath path, FileOpenOptions options) => + fileSystem.GetDomain(path).Open(path.Value, options); + + /// + /// Opens a file that exists for reading. + /// + /// The file system. + /// The path. + /// The stream; the caller closes it. + public static Stream OpenRead(this IFileSystem fileSystem, FilePath path) => + fileSystem.GetDomain(path).Open(path.Value, FileOpenOptions.Read); + + /// + public static ValueTask OpenAsync(this IFileSystem fileSystem, FilePath path, FileOpenOptions options, + CancellationToken cancellationToken = default) => + fileSystem.GetDomain(path).OpenAsync(path.Value, options, cancellationToken); + + /// + public static IRandomAccessFile OpenRandomAccess(this IFileSystem fileSystem, FilePath path) => + fileSystem.GetDomain(path).OpenRandomAccess(path.Value); + + /// + public static bool TryGetMemory(this IFileSystem fileSystem, FilePath path, out ReadOnlyMemory data) + { + data = default; + return !path.IsEmpty + && fileSystem.TryGetDomain(path.Domain, out var domain) + && domain.TryGetMemory(path.Value, out data); + } + + /// + public static void CreateDirectory(this IFileSystem fileSystem, FilePath path) => + fileSystem.GetDomain(path).CreateDirectory(path.Value); + + /// + public static bool Delete(this IFileSystem fileSystem, FilePath path, bool recursive = false) => + fileSystem.GetDomain(path).Delete(path.Value, recursive); + + /// + /// Moves or renames a file or a directory inside its domain. + /// + /// The file system. + /// The path to move. + /// The new path, in the same domain. + /// Whether a file at is replaced. + /// Thrown if the paths are in different domains: copy, then delete. + public static void Move(this IFileSystem fileSystem, FilePath source, FilePath destination, bool overwrite = false) + { + if (source.Domain != destination.Domain) + throw new ArgumentException($"'{source}' and '{destination}' are in different domains", nameof(destination)); + fileSystem.GetDomain(source).Move(source.Value, destination.Value, overwrite); + } + + /// + public static IDisposable Watch(this IFileSystem fileSystem, FilePath directory, bool recursive, + Action handler) => + fileSystem.GetDomain(directory).Watch(directory.Value, recursive, handler); +} diff --git a/Kernel/src/Managed/Stellar.Kernel/FileSystem/FileSystemNames.cs b/Kernel/src/Managed/Stellar.Kernel/FileSystem/FileSystemNames.cs new file mode 100644 index 0000000..c215671 --- /dev/null +++ b/Kernel/src/Managed/Stellar.Kernel/FileSystem/FileSystemNames.cs @@ -0,0 +1,167 @@ +using System; + +namespace Stellar.Kernel.FileSystem; + +/// +/// The rules for the names of the file system: domains and schemes, and the paths inside a domain. +/// +/// +/// A name is lower case ASCII: a letter or a digit, then letters, digits, '.', '_' or '-'. Upper case is +/// folded, so Assets and assets are one name. +/// A path is relative to the root of its domain and uses '/'. Every driver gets it in one form, so a path +/// means the same on every platform and in every domain: +/// +/// '\' is read as '/', empty and '.' segments are dropped, a leading '/' means the root; +/// '..' goes up, but never above the root of the domain; +/// a segment has no control characters and none of : * ? " < > |; +/// a segment does not end with '.' or ' ': Windows drops them, so a. would open a. +/// +/// +public static class FileSystemNames +{ + /// + /// Checks and folds the name of a domain or a scheme. + /// + /// The name. + /// The parameter the name came from, for the exception. + /// The name in lower case. + /// Thrown if is not a valid name. + public static string NormalizeName(string name, string parameter = "name") + { + if (name is null) throw new ArgumentNullException(parameter); + return TryNormalizeName(name, out var normalized) + ? normalized + : throw new ArgumentException($"'{name}' is not a valid name: a letter or a digit, then letters, digits, '.', '_' or '-'", parameter); + } + + /// + /// Checks and folds the name of a domain or a scheme. + /// + /// The name. + /// The name in lower case, or an empty string if it is not valid. + /// true if is a valid name. + public static bool TryNormalizeName(string? name, out string normalized) + { + normalized = string.Empty; + if (string.IsNullOrEmpty(name)) return false; + + var lower = true; + for (var i = 0; i < name.Length; i++) + { + var c = name[i]; + if (c is >= 'A' and <= 'Z') { lower = false; continue; } + if (c is >= 'a' and <= 'z' or >= '0' and <= '9') continue; + if (i > 0 && c is '.' or '_' or '-') continue; + return false; + } + + normalized = lower ? name : name.ToLowerInvariant(); + return true; + } + + private static bool TryNormalizePath(string? path, out string normalized, out string error) + { + normalized = string.Empty; + error = string.Empty; + if (path is null) { error = "no path"; return false; } + if (path.Length == 0) return true; + + // Most paths are in their form already: check them without allocating + if (IsNormalized(path, out error)) + { + if (error.Length != 0) return false; + normalized = path; + return true; + } + + var segments = new string[path.Length]; + var count = 0; + var start = 0; + for (var i = 0; i <= path.Length; i++) + { + if (i < path.Length && path[i] is not ('/' or '\\')) continue; + + var length = i - start; + if (length == 0 || (length == 1 && path[start] == '.')) { start = i + 1; continue; } + if (length == 2 && path[start] == '.' && path[start + 1] == '.') + { + if (count == 0) { error = "'..' goes above the root of the domain"; return false; } + count--; + start = i + 1; + continue; + } + + if (!IsValidSegment(path, start, length, out error)) return false; + segments[count++] = path.Substring(start, length); + start = i + 1; + } + + normalized = string.Join("/", segments, 0, count); + return true; + } + + /// + /// Brings a path inside a domain to its one form. + /// + /// The path, relative to the root of the domain. + /// The parameter the path came from, for the exception. + /// The path in its one form; an empty string for the root. + /// Thrown if is not a valid path. + public static string NormalizePath(string path, string parameter = "path") + { + if (path is null) throw new ArgumentNullException(parameter); + return TryNormalizePath(path, out var normalized, out var error) + ? normalized + : throw new ArgumentException($"'{path}' is not a valid path: {error}", parameter); + } + + /// + /// Brings a path inside a domain to its one form. + /// + /// The path, relative to the root of the domain. + /// The path in its one form, or an empty string if it is not valid. + /// true if is a valid path. + public static bool TryNormalizePath(string? path, out string normalized) => + TryNormalizePath(path, out normalized, out _); + + // true with an empty error: the path is in its form; true with an error: it is invalid; false: rewrite it + private static bool IsNormalized(string path, out string error) + { + error = string.Empty; + var start = 0; + for (var i = 0; i <= path.Length; i++) + { + if (i < path.Length && path[i] != '/') + { + if (path[i] == '\\') return false; + continue; + } + + var length = i - start; + if (length == 0) return false; + if (path[start] == '.' && (length == 1 || (length == 2 && path[start + 1] == '.'))) return false; + if (!IsValidSegment(path, start, length, out error)) return true; + start = i + 1; + } + return true; + } + + private static bool IsValidSegment(string path, int start, int length, out string error) + { + error = string.Empty; + for (var i = start; i < start + length; i++) + { + var c = path[i]; + if (c < ' ' || c == '\u007f') { error = "a control character"; return false; } + if (c is ':' or '*' or '?' or '"' or '<' or '>' or '|') { error = $"'{c}' is not allowed"; return false; } + } + + var last = path[start + length - 1]; + if (last is '.' or ' ') + { + error = $"'{path.Substring(start, length)}' ends with '{last}'"; + return false; + } + return true; + } +} diff --git a/Kernel/src/Managed/Stellar.Kernel/FileSystem/IContentTypeRegistry.cs b/Kernel/src/Managed/Stellar.Kernel/FileSystem/IContentTypeRegistry.cs new file mode 100644 index 0000000..c49e3a1 --- /dev/null +++ b/Kernel/src/Managed/Stellar.Kernel/FileSystem/IContentTypeRegistry.cs @@ -0,0 +1,36 @@ +using Stellar.Kernel.Quantization; + +namespace Stellar.Kernel.FileSystem; + +/// +/// The content types of a file system, by extension. +/// +/// +/// Drivers fill from here, unless their source tells it (a network share with a +/// content type of its own). Modules add the formats they read. +/// +public interface IContentTypeRegistry + : IQuantumObject +{ + /// + /// Maps an extension to a content type, replacing the previous one. + /// + /// The extension with its dot, such as .png; any case. + /// The content type of the files with that extension. + void Register(string extension, ContentType contentType); + + /// + /// Finds the content type of an extension. + /// + /// The extension with its dot, such as .png; any case. + /// The content type, or the unknown one. + /// true if the extension is registered. + bool TryGet(string extension, out ContentType contentType); + + /// + /// Gets the content type of a file by its extension. + /// + /// The file. + /// The content type, or for an unknown extension. + ContentType Resolve(FilePath path); +} diff --git a/Kernel/src/Managed/Stellar.Kernel/FileSystem/IDomain.cs b/Kernel/src/Managed/Stellar.Kernel/FileSystem/IDomain.cs index a33ec7e..706d291 100644 --- a/Kernel/src/Managed/Stellar.Kernel/FileSystem/IDomain.cs +++ b/Kernel/src/Managed/Stellar.Kernel/FileSystem/IDomain.cs @@ -1,33 +1,139 @@ using System; +using System.Collections.Generic; +using System.IO; +using System.Threading; +using System.Threading.Tasks; using Stellar.Kernel.Quantization; namespace Stellar.Kernel.FileSystem; /// -/// Represents an abstract location scope (domain) that groups files. +/// A mounted domain: the files of one source (a directory, an assembly, an archive, a network) under one name. /// /// -/// A domain defines a root or a container for files. Examples: a physical folder, an assembly, -/// a ZIP archive, or a network share. Each domain has a type () and a string value -/// (e.g., absolute path or assembly name). -/// Domains are meta‑quants (), labeled (), and equatable. +/// A domain is what its driver made of a , and it holds all the state of that +/// source: there is no lock or cache shared between domains, file systems or engine instances. +/// Paths are : relative to the root of the domain and already in the one form of +/// , so a domain does not check them again and nothing it is given leaves its root. +/// A domain over a directory still refuses links that lead out of it. +/// Every member is safe to call from any thread. A member the domain cannot do +/// () throws . +/// Unmounting () disposes the domain; streams it opened stay usable until +/// they are closed. /// public interface IDomain - : IMetaQuant, ILabeled, IEquatable + : IQuant, IDisposable { /// - /// Gets the type of this domain (e.g., directory, assembly). + /// Gets the name of the domain, in . /// - DomainType Type { get; } + string Name { get; } /// - /// Gets the domain's native value (e.g., full directory path, assembly name). + /// Gets the scheme of the driver that mounted it. /// - string Value { get; } + DomainScheme Scheme { get; } /// - /// Returns the domain as a string (typically the ). + /// Gets where the driver found it, in the terms of the driver (). /// - /// The domain string representation. - string ToString(); + string Source { get; } + + /// + /// Gets what the domain can do. + /// + DomainCapabilities Capabilities { get; } + + /// + /// Gets whether a file or a directory exists. + /// + /// The path inside the domain. + /// true if there is a file or a directory at . + bool Exists(string path); + + /// + /// Reads what is known of a file or a directory. + /// + /// The path inside the domain. + /// The entry, with its filled. + /// true if there is a file or a directory at . + bool TryGetEntry(string path, out FileEntry entry); + + /// + /// Lists the entries of a directory. Needs . + /// + /// The directory inside the domain; an empty string for the root. + /// The names to list: * for any run of characters, ? for one. + /// Whether to go into the directories inside. + /// The entries, as they are found; files and directories alike. + /// Thrown if there is no such directory. + IEnumerable Enumerate(string directory, string pattern = "*", bool recursive = false); + + /// + /// Opens a file as a stream. Writing needs . + /// + /// The path inside the domain. + /// How to open it. + /// The stream; the caller closes it. + /// Thrown if the file must exist and does not. + Stream Open(string path, FileOpenOptions options); + + /// + /// Opens a file as a stream, without blocking on a slow source. Writing needs . + /// + /// The path inside the domain. + /// How to open it. + /// Stops the opening. + /// The stream; the caller closes it. + /// Thrown if the file must exist and does not. + ValueTask OpenAsync(string path, FileOpenOptions options, CancellationToken cancellationToken = default); + + /// + /// Opens a file for reads at any offset. Needs . + /// + /// The path inside the domain. + /// The file; the caller disposes it. + /// Thrown if there is no such file. + IRandomAccessFile OpenRandomAccess(string path); + + /// + /// Gets the bytes of a file the domain holds in memory, without a copy. + /// + /// The path inside the domain. + /// The bytes; they never change: a write gives the file new memory. + /// true if the domain holds the file in memory; false otherwise, then open it. + bool TryGetMemory(string path, out ReadOnlyMemory data); + + /// + /// Creates a directory and the directories above it. Needs . + /// + /// The path inside the domain. + void CreateDirectory(string path); + + /// + /// Deletes a file or a directory. Needs . + /// + /// The path inside the domain. + /// Whether a directory goes with what it holds; without it, only an empty one goes. + /// true if something was deleted; false if there was nothing. + bool Delete(string path, bool recursive = false); + + /// + /// Moves or renames a file or a directory inside the domain. Needs . + /// + /// The path to move. + /// The new path. + /// Whether a file at is replaced. + void Move(string source, string destination, bool overwrite = false); + + /// + /// Reports the changes under a directory. Needs . + /// + /// The directory inside the domain; an empty string for the whole domain. + /// Whether the directories inside are watched too. + /// + /// Called for each change, from any thread and possibly at once from several: it must be quick and safe. + /// + /// Stops the watch when disposed. + IDisposable Watch(string directory, bool recursive, Action handler); } diff --git a/Kernel/src/Managed/Stellar.Kernel/FileSystem/IFile.cs b/Kernel/src/Managed/Stellar.Kernel/FileSystem/IFile.cs deleted file mode 100644 index cb7230c..0000000 --- a/Kernel/src/Managed/Stellar.Kernel/FileSystem/IFile.cs +++ /dev/null @@ -1,26 +0,0 @@ -using System; -using Stellar.Kernel.Quantization; - -namespace Stellar.Kernel.FileSystem; - -/// -/// Represents an abstract quantum file stored at a quantum location. -/// -/// -/// A file is identified by its and has a -/// (e.g., text, binary, image). Files are meta‑quants and can be compared for equality. -/// This interface does not provide direct I/O; use or file provider methods. -/// -public interface IFile - : IMetaQuant, IEquatable -{ - /// - /// Gets the location of the file (domain + path). - /// - IPath Path { get; } - - /// - /// Gets the file type descriptor. - /// - IFileType Type { get; } -} diff --git a/Kernel/src/Managed/Stellar.Kernel/FileSystem/IFileDriver.cs b/Kernel/src/Managed/Stellar.Kernel/FileSystem/IFileDriver.cs new file mode 100644 index 0000000..e211026 --- /dev/null +++ b/Kernel/src/Managed/Stellar.Kernel/FileSystem/IFileDriver.cs @@ -0,0 +1,33 @@ +using Stellar.Kernel.Quantization; + +namespace Stellar.Kernel.FileSystem; + +/// +/// Mounts the domains of one scheme: directories, assembly resources, archives, a network, a world of a game. +/// +/// +/// A driver is registered in a file system (), and the file system +/// picks it by when a domain is mounted: one lookup, once, not a question per file. +/// The driver keeps no state of its domains: what a domain needs (its root, an open archive, a connection) +/// lives in the it returns. One driver may serve several file systems, so several engine +/// instances. +/// +public interface IFileDriver + : IQuant +{ + /// + /// Gets the scheme of the domains this driver mounts. + /// + DomainScheme Scheme { get; } + + /// + /// Mounts a domain. + /// + /// What to mount; its scheme is . + /// + /// The file system mounting it: for drivers built on other domains (an archive inside a domain, an overlay of + /// domains) and for . + /// + /// The mounted domain. + IDomain Mount(DomainMount mount, IFileSystem fileSystem); +} diff --git a/Kernel/src/Managed/Stellar.Kernel/FileSystem/IFileSystem.cs b/Kernel/src/Managed/Stellar.Kernel/FileSystem/IFileSystem.cs new file mode 100644 index 0000000..1f46db9 --- /dev/null +++ b/Kernel/src/Managed/Stellar.Kernel/FileSystem/IFileSystem.cs @@ -0,0 +1,91 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using Stellar.Kernel.Quantization; + +namespace Stellar.Kernel.FileSystem; + +/// +/// The files of an engine instance: drivers, the domains they mounted and the content types, behind +/// . +/// +/// +/// Each engine instance has its own file system; nothing of it is static. Code above names domains +/// (assets://, user://), never locations of the machine: those are given to drivers once, when the +/// domains are mounted. +/// The file system routes a path to its domain (); the operations on paths are the +/// extensions of . The data of files, cached and shared, is the business of the +/// resource system (), built on this one. +/// Every member is safe to call from any thread. +/// +public interface IFileSystem + : IQuant, IDisposable +{ + /// + /// Gets the content types of this file system, by extension. + /// + IContentTypeRegistry ContentTypes { get; } + + /// + /// Gets the domains mounted now. + /// + IReadOnlyCollection Domains { get; } + + /// + /// Raised after a domain is mounted. + /// + event Action? Mounted; + + /// + /// Raised before a domain is unmounted, while it still works: caches drop what they hold of it. + /// + event Action? Unmounting; + + /// + /// Registers the driver of a scheme. + /// + /// The driver. + /// Thrown if another driver has the same scheme. + void RegisterDriver(IFileDriver driver); + + /// + /// Finds the driver of a scheme. + /// + /// The scheme. + /// The driver, or null. + /// true if a driver of is registered. + bool TryGetDriver(DomainScheme scheme, [NotNullWhen(true)] out IFileDriver? driver); + + /// + /// Mounts a domain with the driver of its scheme. + /// + /// What to mount. + /// The mounted domain. + /// + /// Thrown if a domain of that name is mounted, or no driver has the scheme. + /// + IDomain Mount(DomainMount mount); + + /// + /// Unmounts a domain and disposes it. + /// + /// The name of the domain. + /// true if the domain was mounted. + bool Unmount(string name); + + /// + /// Finds a mounted domain. + /// + /// The name of the domain. + /// The domain, or null. + /// true if a domain of that name is mounted. + bool TryGetDomain(string name, [NotNullWhen(true)] out IDomain? domain); + + /// + /// Gets a mounted domain. + /// + /// The name of the domain. + /// The domain. + /// Thrown if no domain of that name is mounted. + IDomain GetDomain(string name); +} diff --git a/Kernel/src/Managed/Stellar.Kernel/FileSystem/IFileType.cs b/Kernel/src/Managed/Stellar.Kernel/FileSystem/IFileType.cs deleted file mode 100644 index de0360e..0000000 --- a/Kernel/src/Managed/Stellar.Kernel/FileSystem/IFileType.cs +++ /dev/null @@ -1,22 +0,0 @@ -using System; -using Stellar.Kernel.Quantization; - -namespace Stellar.Kernel.FileSystem; - -/// -/// Describes the format or kind of quantum file. -/// -/// -/// File types are registrable meta‑quants (), labeled, -/// and equatable. They can be used to associate MIME types, extensions, or custom handlers. -/// Examples: "text/plain", "image/png", "application/json". -/// -public interface IFileType - : IRegistrableMetaQuant, ILabeled, IEquatable -{ - /// - /// Returns the file type as a string (e.g., its name or MIME type). - /// - /// The string representation of the file type. - string ToString(); -} diff --git a/Kernel/src/Managed/Stellar.Kernel/FileSystem/IPath.cs b/Kernel/src/Managed/Stellar.Kernel/FileSystem/IPath.cs deleted file mode 100644 index 220eee0..0000000 --- a/Kernel/src/Managed/Stellar.Kernel/FileSystem/IPath.cs +++ /dev/null @@ -1,33 +0,0 @@ -using System; -using Stellar.Kernel.Quantization; - -namespace Stellar.Kernel.FileSystem; - -/// -/// Represents the address of a file within a specific domain. -/// -/// -/// A location combines a and a relative string. -/// It uniquely identifies a file in the quantum file system. -/// Locations are meta‑quants and equatable. They can be created by combining a domain and a path, -/// or by parsing a string representation (implementation‑specific). -/// -public interface IPath - : IMetaQuant, IEquatable -{ - /// - /// Gets the domain that contains this location. - /// - IDomain Domain { get; } - - /// - /// Gets the relative path of the file inside the domain. - /// - string Value { get; } - - /// - /// Returns the full location as a string (typically "domain://path" or similar). - /// - /// The string representation of the location. - string ToString(); -} diff --git a/Kernel/src/Managed/Stellar.Kernel/FileSystem/IRandomAccessFile.cs b/Kernel/src/Managed/Stellar.Kernel/FileSystem/IRandomAccessFile.cs new file mode 100644 index 0000000..bcd0322 --- /dev/null +++ b/Kernel/src/Managed/Stellar.Kernel/FileSystem/IRandomAccessFile.cs @@ -0,0 +1,42 @@ +using System; +using System.Threading; +using System.Threading.Tasks; + +namespace Stellar.Kernel.FileSystem; + +/// +/// A file read at any offset, with no position and no stream: packed archives, streaming of large data. +/// +/// +/// Reads at different offsets may run at once, from any thread. +/// +public interface IRandomAccessFile + : IDisposable +{ + /// + /// Gets the path of the file. + /// + FilePath Path { get; } + + /// + /// Gets the length of the file in bytes. + /// + long Length { get; } + + /// + /// Reads bytes at an offset. + /// + /// Where to start, from the beginning of the file. + /// Where to put the bytes. + /// How many bytes were read; fewer than asked only at the end of the file. + int Read(long offset, Span buffer); + + /// + /// Reads bytes at an offset. + /// + /// Where to start, from the beginning of the file. + /// Where to put the bytes. + /// Stops the read. + /// How many bytes were read; fewer than asked only at the end of the file. + ValueTask ReadAsync(long offset, Memory buffer, CancellationToken cancellationToken = default); +} diff --git a/Kernel/src/Managed/Stellar.Kernel/FileSystem/IResource.cs b/Kernel/src/Managed/Stellar.Kernel/FileSystem/IResource.cs deleted file mode 100644 index 07b4054..0000000 --- a/Kernel/src/Managed/Stellar.Kernel/FileSystem/IResource.cs +++ /dev/null @@ -1,18 +0,0 @@ -using System; -using System.Collections.ObjectModel; -using Stellar.Kernel.Quantization; - -namespace Stellar.Kernel.FileSystem; - -/// -/// A resource served by the engine file system. -/// -public interface IResource - : IMetaQuant, IEquatable -{ - /// Gets the file reference (domain + path). - IFile File { get; } - - /// Gets the raw loaded bytes. - ReadOnlyCollection Data { get; } -} diff --git a/Kernel/src/Managed/Stellar.Kernel/FileSystem/IResourceOrchestrator.cs b/Kernel/src/Managed/Stellar.Kernel/FileSystem/IResourceOrchestrator.cs deleted file mode 100644 index 238ed60..0000000 --- a/Kernel/src/Managed/Stellar.Kernel/FileSystem/IResourceOrchestrator.cs +++ /dev/null @@ -1,47 +0,0 @@ -using System.IO; -using System.Threading; -using System.Threading.Tasks; -using Stellar.Kernel.FileSystem.Provider; -using Stellar.Kernel.Quantization; - -namespace Stellar.Kernel.FileSystem; - -/// -/// Main coordinator of the file system: domain resolving, provider selection, factories, caching. -/// -public interface IResourceOrchestrator : IQuant -{ - // ----- Component registration ----- - - /// Registers a provider for a domain type. - void RegisterProvider(DomainType domainType, IFileProvider provider); - - /// Registers a factory for an extension (with or without the dot). - void RegisterFactory(string extension, IResourceFactory factory); - - /// Mounts a domain (root or nested). - void MountDomain(IDomain domain, IDomain? parentDomain = null); - - // ----- Resource loading (sync, async, streaming) ----- - - /// Loads a resource synchronously (may block the thread). - IResource Load(IPath path); - - /// Loads a resource asynchronously. - Task LoadAsync(IPath path, CancellationToken cancellationToken = default); - - /// Opens a stream to read a resource (streaming). - Stream OpenStream(IPath path); - - /// Checks whether a resource is in the cache. - bool IsLoaded(IPath path); - - /// Evicts a resource from the cache unless someone holds it. - void Unload(IPath path); - - /// Gets the file metadata. - IFileInfo GetFileInfo(IPath path); - - /// Checks whether a file exists. - bool Exists(IPath path); -} diff --git a/Kernel/src/Managed/Stellar.Kernel/FileSystem/Provider/IFileProvider.cs b/Kernel/src/Managed/Stellar.Kernel/FileSystem/Provider/IFileProvider.cs deleted file mode 100644 index f5ab174..0000000 --- a/Kernel/src/Managed/Stellar.Kernel/FileSystem/Provider/IFileProvider.cs +++ /dev/null @@ -1,67 +0,0 @@ -using System.IO; -using Stellar.Kernel.Quantization; - -namespace Stellar.Kernel.FileSystem.Provider; - -/// -/// Provides low‑level file operations for a specific domain type. -/// -/// -/// A file provider is a quant () that implements actual file I/O -/// for a particular domain (e.g., physical directory, assembly resource, network share). -/// Providers are obtained from an based on the domain. -/// -public interface IFileProvider - : IQuant -{ - /// - /// Determines whether this provider can handle files in the specified domain. - /// - /// The domain to test. - /// true if this provider supports the domain; otherwise, false. - bool CanHandle(IDomain domain); - - /// - /// Checks whether a file exists at the given location. - /// - /// The file location to check. - /// true if the file exists; otherwise, false. - bool Exists(IPath path); - - /// - /// Retrieves metadata information about the file at the specified location. - /// - /// The file location. - /// An instance containing file metadata. - /// Thrown if the file does not exist. - IFileInfo GetFileInfo(IPath path); - - /// - /// Opens the file for read‑only access. - /// - /// The file location. - /// A readable . - Stream OpenRead(IPath path); - - /// - /// Opens the file for write‑only access. - /// - /// The file location. - /// A writable . - Stream OpenWrite(IPath path); - - /// - /// Opens the file for both reading and writing. - /// - /// The file location. - /// A readable and writable . - Stream OpenReadWrite(IPath path); - - /// - /// Opens the file with the specified access mode. - /// - /// The file location. - /// The desired (Read, Write, or ReadWrite). - /// A with the requested access. - Stream Open(IPath path, FileAccess access); -} diff --git a/Kernel/src/Managed/Stellar.Kernel/FileSystem/Provider/IFileProviderFactory.cs b/Kernel/src/Managed/Stellar.Kernel/FileSystem/Provider/IFileProviderFactory.cs deleted file mode 100644 index da657a4..0000000 --- a/Kernel/src/Managed/Stellar.Kernel/FileSystem/Provider/IFileProviderFactory.cs +++ /dev/null @@ -1,24 +0,0 @@ -using System; -using Stellar.Kernel.Quantization; - -namespace Stellar.Kernel.FileSystem.Provider; - -/// -/// Resolves an appropriate file provider for a given domain. -/// -/// -/// The factory is a quant that maintains a mapping from domain types (or domain instances) -/// to registered implementations. It is used by higher‑level file system APIs -/// to delegate operations to the correct provider. -/// -public interface IFileProviderFactory - : IQuant -{ - /// - /// Returns a file provider capable of handling the specified domain. - /// - /// The domain for which a provider is needed. - /// An that can operate on the given domain. - /// Thrown if no provider can handle the domain. - IFileProvider GetFileProvider(IDomain domain); -} diff --git a/Kernel/src/Managed/Stellar.Kernel/FileSystem/Provider/IResourceFactory.cs b/Kernel/src/Managed/Stellar.Kernel/FileSystem/Provider/IResourceFactory.cs deleted file mode 100644 index 4fc1b50..0000000 --- a/Kernel/src/Managed/Stellar.Kernel/FileSystem/Provider/IResourceFactory.cs +++ /dev/null @@ -1,23 +0,0 @@ -using System.IO; -using System.Threading; -using System.Threading.Tasks; -using Stellar.Kernel.Quantization; - -namespace Stellar.Kernel.FileSystem.Provider; - -/// -/// Creates an from raw data and file metadata. -/// -public interface IResourceFactory - : IQuant -{ - /// Creates a resource from a byte array. - IResource CreateResource(IFile file, byte[] data); - - /// Creates a resource from a stream, reading all bytes. - IResource CreateResource(IFile file, Stream dataStream); - - /// Creates a resource from a stream asynchronously. - Task CreateResourceAsync(IFile file, Stream dataStream, - CancellationToken cancellationToken = default); -} diff --git a/Kernel/src/Managed/Stellar.Kernel/FileSystem/Resources/IResource.cs b/Kernel/src/Managed/Stellar.Kernel/FileSystem/Resources/IResource.cs new file mode 100644 index 0000000..5021fe7 --- /dev/null +++ b/Kernel/src/Managed/Stellar.Kernel/FileSystem/Resources/IResource.cs @@ -0,0 +1,83 @@ +using System; +using System.IO; +using System.Threading; +using System.Threading.Tasks; + +namespace Stellar.Kernel.FileSystem.Resources; + +/// +/// A lease on the data of a file: what the file system finds, the resource system holds and shares. +/// +/// +/// A file is an address and what is known of it (, ); a resource +/// is its data. Every lease counts as a reference: the resource system frees the data when the last lease is +/// disposed, as says. Dispose each lease once. +/// A lease is a snapshot: its data stays the same for its whole life, even when the file changes. Then +/// becomes true and is raised, and whoever wants the new data +/// acquires the resource again. Under nothing is held, so each +/// reads the file as it is now. +/// What the data becomes (a texture, a level) is decided above, by the asset system: a resource is bytes +/// with a . +/// +public interface IResource + : IDisposable +{ + /// + /// Gets the path of the file. + /// + FilePath Path { get; } + + /// + /// Gets what was known of the file when the data of this lease was read. + /// + FileEntry Entry { get; } + + /// + /// Gets how the data is held. + /// + ResourcePolicy Policy { get; } + + /// + /// Gets the version of the data of this lease: it grows each time the resource system reads the file anew. + /// + long Version { get; } + + /// + /// Gets whether the file changed after the data of this lease was read. + /// + bool IsStale { get; } + + /// + /// Raised once, when the file changes after the data of this lease was read; from any thread. + /// + event Action? Changed; + + /// + /// Opens the data as a stream, from its start. + /// + /// A stream of its own, read-only; the caller closes it. + /// Thrown if the lease is disposed. + Stream Open(); + + /// + /// Opens the data as a stream, from its start, without blocking on a slow source. + /// + /// Stops the opening. + /// A stream of its own, read-only; the caller closes it. + /// Thrown if the lease is disposed. + ValueTask OpenAsync(CancellationToken cancellationToken = default); + + /// + /// Gets the data in memory, without a copy, when it is there. + /// + /// The bytes; valid while the lease lives. + /// true if the data is in memory; false otherwise, then use . + bool TryGetMemory(out ReadOnlyMemory data); + + /// + /// Takes another lease on the same data, for another owner. + /// + /// A lease of its own, to dispose on its own. + /// Thrown if the lease is disposed. + IResource Share(); +} diff --git a/Kernel/src/Managed/Stellar.Kernel/FileSystem/Resources/IResourceSystem.cs b/Kernel/src/Managed/Stellar.Kernel/FileSystem/Resources/IResourceSystem.cs new file mode 100644 index 0000000..6a1a530 --- /dev/null +++ b/Kernel/src/Managed/Stellar.Kernel/FileSystem/Resources/IResourceSystem.cs @@ -0,0 +1,82 @@ +using System; +using System.Threading; +using System.Threading.Tasks; +using Stellar.Kernel.Quantization; + +namespace Stellar.Kernel.FileSystem.Resources; + +/// +/// The data of files, read once and shared: leases with reference counts, a cache, and reloads when files change. +/// +/// +/// Built on an : one per engine instance, like it. The file system answers where a +/// file is and what is known of it; the resource system holds its data. +/// It watches what it holds, where the domain can (), and coalesces the +/// bursts of changes: a changed file gets a new on its next acquisition, and the +/// leases on its old data become stale (). A domain being unmounted drops what is +/// held of it. +/// Every member is safe to call from any thread. +/// +public interface IResourceSystem + : IQuant, IDisposable +{ + /// + /// Gets the file system the data comes from. + /// + IFileSystem FileSystem { get; } + + /// + /// Gets or sets how many bytes the cache keeps for resources that no lease holds; 0 keeps none. + /// + long CacheBudget { get; set; } + + /// + /// Gets how many bytes are held now, leased or not. + /// + long HeldBytes { get; } + + /// + /// Raised when a file that is held changed, after the changes were coalesced; from any thread. + /// + event Action? Changed; + + /// + /// Takes a lease on the data of a file, reading it if it is not held. + /// + /// The file. + /// How to hold the data. + /// The lease; the caller disposes it. + /// Thrown if there is no such file. + /// Thrown if the domain is not mounted. + IResource Acquire(FilePath path, ResourcePolicy policy = ResourcePolicy.Cache); + + /// + /// Takes a lease on the data of a file, reading it if it is not held, without blocking on a slow source. + /// + /// The file. + /// How to hold the data. + /// Stops the reading; a read shared with other callers goes on for them. + /// The lease; the caller disposes it. + /// Thrown if there is no such file. + /// Thrown if the domain is not mounted. + ValueTask AcquireAsync(FilePath path, ResourcePolicy policy = ResourcePolicy.Cache, CancellationToken cancellationToken = default); + + /// + /// Gets whether the data of a file is held now, leased or cached. + /// + /// The file. + /// true if the next acquisition reads nothing. + bool IsHeld(FilePath path); + + /// + /// Forgets the data of a file, as if it had changed: the next acquisition reads it anew, and the leases on it + /// become stale. + /// + /// The file, or a directory for everything under it. + void Invalidate(FilePath path); + + /// + /// Frees the data that no lease holds. + /// + void Trim(); +} diff --git a/Kernel/src/Managed/Stellar.Kernel/FileSystem/Resources/ResourcePolicy.cs b/Kernel/src/Managed/Stellar.Kernel/FileSystem/Resources/ResourcePolicy.cs new file mode 100644 index 0000000..41a1e96 --- /dev/null +++ b/Kernel/src/Managed/Stellar.Kernel/FileSystem/Resources/ResourcePolicy.cs @@ -0,0 +1,29 @@ +namespace Stellar.Kernel.FileSystem.Resources; + +/// +/// How the resource system holds the data of a resource while it is leased. +/// +/// +/// Leases of one path share one entry, and the entry holds by the strongest policy of its leases: +/// over over . +/// +public enum ResourcePolicy : byte +{ + /// + /// Nothing is held: each opens the file as it is now. For large data read once, + /// such as music or video. + /// + Stream, + + /// + /// The bytes are held in memory and shared by every lease. With no lease left they stay, until the cache + /// needs the room (). + /// + Cache, + + /// + /// The source is held open while a lease lives (a file handle, a connection), and nothing is read twice; with no + /// lease left it is closed at once. + /// + Keep +} diff --git a/Kernel/src/Managed/Stellar.Kernel/Stellar.Kernel.csproj b/Kernel/src/Managed/Stellar.Kernel/Stellar.Kernel.csproj index a81a6fe..33b6d17 100644 --- a/Kernel/src/Managed/Stellar.Kernel/Stellar.Kernel.csproj +++ b/Kernel/src/Managed/Stellar.Kernel/Stellar.Kernel.csproj @@ -23,6 +23,7 @@ + diff --git a/Shared/Build/Stellar.Versions.props b/Shared/Build/Stellar.Versions.props index d0deccd..6ff1fe5 100644 --- a/Shared/Build/Stellar.Versions.props +++ b/Shared/Build/Stellar.Versions.props @@ -7,18 +7,18 @@ --> - 0.8.1 + 0.9.0 - 0.8.0 - 0.8.0 - 0.8.0 + 0.9.0 + 0.9.0 + 0.9.0 0.3.1 0.4.0 0.2.2 - 0.8.1 + 0.9.0 2 From 2185350da02f6d4bc3c047aa75e35975df423848 Mon Sep 17 00:00:00 2001 From: MarcT1me Date: Mon, 16 Nov 2026 21:53:41 +0700 Subject: [PATCH 2/9] [KERNEL] [CORE] [DOCS] identifiers and labels are values of the Kernel Identifiers - Stellar.Kernel.Identifier: a blittable value of 16 bytes, never registered; New, Parse, TryParse, ToBytes, FromBytes, Empty. No Guid in the API of the engine: code works with identifiers. - The registries of identifiers are gone: native, exports, both wrappers. MetaQuant makes its identifier without a native call. Labels - Stellar.Kernel.Label: an identifier and a name, a value. No registry, no lookup by name, no string converted into a label. - IEventType is a labeled meta quant; the entry point has its own label. ABI - P/Invoke exports 3.0: stellar_identifier_register, _unregister, _contains, _count, _snapshot and stellar_label_* are gone. StellarNativeAbiVersion 3. Docs - Migration-0.9: identifiers, labels, the file system. NativeAbi: identifiers. --- .../Collections/ConcurrentIdentifierMap.cs | 8 +- .../Data/Collections/ConstantTable.cs | 4 +- .../Data/Collections/DataContainer.cs | 28 +-- .../FastConcurrentIdentifierMap.cs | 30 +-- .../Data/Collections/IdentifierComparer.cs | 32 --- .../Stellar.Core/Data/Collections/Roster.cs | 28 +-- .../Data/Collections/WritableTable.cs | 8 +- .../Data/Registry/ConcurrentRegistry.cs | 36 +--- .../Data/Registry/DataContainerRegistry.cs | 2 +- .../Data/Registry/MetaQuantsRegistry.cs | 2 +- .../Data/Registry/QuantsRegistry.cs | 2 +- .../Data/Registry/RegistryBinding.cs | 2 +- .../Failures/BaseLevels/FailureLevel.cs | 7 +- .../Stellar.Core/Failures/FailureCatch.cs | 2 +- .../Failures/FailureDispatcher.cs | 3 +- .../Handlers/FailureHandlerProvider.cs | 4 +- .../Managed/Stellar.Core/Global/CoreEngine.cs | 2 - .../src/Managed/Stellar.Core/Global/Engine.cs | 2 - .../Stellar.Core/Quantization/MetaQuant.cs | 13 +- .../Stellar.Core/Quantization/Quant.cs | 2 +- .../Quantization/RegistrableMetaQuant.cs | 2 +- .../Quantization/TimedMetaQuant.cs | 4 +- .../Stellar.Native.Core/CoreContext.cpp | 12 -- .../Native/Stellar.Native.Core/CoreContext.h | 8 +- .../Data/Registry/IdentifierRegistry.cpp | 44 ----- .../Data/Registry/IdentifierRegistry.h | 48 ----- .../Data/Registry/LabelRegistry.cpp | 106 ---------- .../Data/Registry/LabelRegistry.h | 59 ------ Core/src/Native/Stellar.Native.Core/Label.h | 4 +- .../Stellar.Native.Core.vcxproj | 2 - .../Stellar.Native.Core/include/Core/core.h | 2 - .../include/Core/core_interop.h | 2 - .../Stellar.Native.Core.Wrapper.Cli.vcxproj | 4 - .../Data/Registry/ContainerRegistry.cli.h | 30 +-- .../Data/Registry/ContainerRegistry.cpp | 34 ++-- .../Data/Registry/IdentifierRegistry.cli.h | 54 ------ .../Data/Registry/IdentifierRegistry.cpp | 68 ------- .../Wrapper/Data/Registry/LabelRegistry.cli.h | 55 ------ .../Wrapper/Data/Registry/LabelRegistry.cpp | 74 ------- .../Wrapper/Identifier.cli.h | 91 --------- .../Wrapper/Identifier.cpp | 126 ------------ .../Wrapper/Interop.cli.h | 18 +- .../Wrapper/Label.cli.h | 99 ---------- .../Wrapper/Label.cpp | 130 ------------- .../Wrapper/Native/CoreContext.cli.h | 6 - .../Wrapper/Native/CoreContext.cpp | 6 - .../Wrapper/Native/NativeCore.cpp | 2 +- .../Data/Registry/ContainerRegistry.cs | 31 +-- .../Data/Registry/IdentifierRegistry.cs | 96 --------- .../Data/Registry/LabelRegistry.cs | 127 ------------ .../Identifier.cs | 182 ------------------ .../Label.cs | 177 ----------------- .../Native/CoreContext.cs | 8 - .../Native/Exports.cs | 111 +++-------- .../Native/NativeCore.cs | 2 +- .../Exports/Exports.cpp | 96 --------- .../include/PInvoke/exports.h | 17 +- .../Stellar.Core.Tests/CollectionTests.cs | 32 +-- .../Stellar.Core.Tests/EngineInstanceTests.cs | 22 +-- .../Stellar.Core.Tests/FailureTests.cs | 3 +- .../Stellar.Core.Tests/IdentifierTests.cs | 152 +++++---------- .../Managed/Stellar.Core.Tests/QuantTests.cs | 6 +- .../Stellar.Core.Tests/WrapperTests.cs | 75 +++----- .../Stellar.Native.Core.Tests/Tests.cpp | 83 +------- Docs/Architecture/NativeAbi.md | 32 +-- Docs/Migration-0.9.md | 48 +++++ Docs/index.md | 1 + Docs/toc.yml | 2 + .../Data/Collections/IDataContainer.cs | 4 +- .../Stellar.Kernel/Data/Registry/IRegistry.cs | 10 +- .../EntryPoint/StellarEntryPoint.cs | 49 +---- .../Stellar.Kernel/EventSystem/IEventBus.cs | 8 +- .../EventSystem/IEventPostContext.cs | 2 +- .../Stellar.Kernel/EventSystem/IEventType.cs | 6 +- .../src/Managed/Stellar.Kernel/IIdentifier.cs | 33 ---- Kernel/src/Managed/Stellar.Kernel/ILabel.cs | 34 ---- Kernel/src/Managed/Stellar.Kernel/ILabeled.cs | 14 +- .../src/Managed/Stellar.Kernel/Identifier.cs | 137 +++++++++++++ .../Managed/Stellar.Kernel/JobSystem/IJob.cs | 2 +- .../Stellar.Kernel/JobSystem/IJobScheduler.cs | 2 +- Kernel/src/Managed/Stellar.Kernel/Label.cs | 80 ++++++++ .../IIdentifiableQuantumObject.cs | 4 +- README.md | 3 +- .../Stellar.Runtime.Tests/MainLoopTests.cs | 4 +- Shared/Build/Stellar.Versions.props | 2 +- 85 files changed, 604 insertions(+), 2400 deletions(-) delete mode 100644 Core/src/Managed/Stellar.Core/Data/Collections/IdentifierComparer.cs delete mode 100644 Core/src/Native/Stellar.Native.Core/Data/Registry/IdentifierRegistry.cpp delete mode 100644 Core/src/Native/Stellar.Native.Core/Data/Registry/IdentifierRegistry.h delete mode 100644 Core/src/Native/Stellar.Native.Core/Data/Registry/LabelRegistry.cpp delete mode 100644 Core/src/Native/Stellar.Native.Core/Data/Registry/LabelRegistry.h delete mode 100644 Core/src/NativeInterop/Stellar.Native.Core.Wrapper.Cli/Wrapper/Data/Registry/IdentifierRegistry.cli.h delete mode 100644 Core/src/NativeInterop/Stellar.Native.Core.Wrapper.Cli/Wrapper/Data/Registry/IdentifierRegistry.cpp delete mode 100644 Core/src/NativeInterop/Stellar.Native.Core.Wrapper.Cli/Wrapper/Data/Registry/LabelRegistry.cli.h delete mode 100644 Core/src/NativeInterop/Stellar.Native.Core.Wrapper.Cli/Wrapper/Data/Registry/LabelRegistry.cpp delete mode 100644 Core/src/NativeInterop/Stellar.Native.Core.Wrapper.Cli/Wrapper/Identifier.cli.h delete mode 100644 Core/src/NativeInterop/Stellar.Native.Core.Wrapper.Cli/Wrapper/Identifier.cpp delete mode 100644 Core/src/NativeInterop/Stellar.Native.Core.Wrapper.Cli/Wrapper/Label.cli.h delete mode 100644 Core/src/NativeInterop/Stellar.Native.Core.Wrapper.Cli/Wrapper/Label.cpp delete mode 100644 Core/src/NativeInterop/Stellar.Native.Core.Wrapper.Managed/Data/Registry/IdentifierRegistry.cs delete mode 100644 Core/src/NativeInterop/Stellar.Native.Core.Wrapper.Managed/Data/Registry/LabelRegistry.cs delete mode 100644 Core/src/NativeInterop/Stellar.Native.Core.Wrapper.Managed/Identifier.cs delete mode 100644 Core/src/NativeInterop/Stellar.Native.Core.Wrapper.Managed/Label.cs create mode 100644 Docs/Migration-0.9.md delete mode 100644 Kernel/src/Managed/Stellar.Kernel/IIdentifier.cs delete mode 100644 Kernel/src/Managed/Stellar.Kernel/ILabel.cs create mode 100644 Kernel/src/Managed/Stellar.Kernel/Identifier.cs create mode 100644 Kernel/src/Managed/Stellar.Kernel/Label.cs diff --git a/Core/src/Managed/Stellar.Core/Data/Collections/ConcurrentIdentifierMap.cs b/Core/src/Managed/Stellar.Core/Data/Collections/ConcurrentIdentifierMap.cs index 73a4ef1..32d3abc 100644 --- a/Core/src/Managed/Stellar.Core/Data/Collections/ConcurrentIdentifierMap.cs +++ b/Core/src/Managed/Stellar.Core/Data/Collections/ConcurrentIdentifierMap.cs @@ -8,13 +8,13 @@ namespace Stellar.Core.Data.Collections; /// /// The type of stored values. public sealed class ConcurrentIdentifierMap - : ConcurrentDictionary + : ConcurrentDictionary { /// /// Creates an empty map. /// public ConcurrentIdentifierMap() - : base(IdentifierComparer.Instance) + : base() { } @@ -22,8 +22,8 @@ public ConcurrentIdentifierMap() /// Creates a map with initial data. /// /// The initial data. - public ConcurrentIdentifierMap(IEnumerable> data) - : base(data, IdentifierComparer.Instance) + public ConcurrentIdentifierMap(IEnumerable> data) + : base(data) { } } diff --git a/Core/src/Managed/Stellar.Core/Data/Collections/ConstantTable.cs b/Core/src/Managed/Stellar.Core/Data/Collections/ConstantTable.cs index ca98142..6a61924 100644 --- a/Core/src/Managed/Stellar.Core/Data/Collections/ConstantTable.cs +++ b/Core/src/Managed/Stellar.Core/Data/Collections/ConstantTable.cs @@ -21,7 +21,7 @@ public ConstantTable(MetaQuant meta, FastConcurrentIdentifierMap data) } /// - public ConstantTable(MetaQuant meta, Dictionary data) + public ConstantTable(MetaQuant meta, Dictionary data) : base(meta, data) { } @@ -43,7 +43,7 @@ public ConstantTable() #region item support /// - public override IIdentifiableQuantumObject? Get(IIdentifier identifier) + public override IIdentifiableQuantumObject? Get(Identifier identifier) { return Data.GetValueOrDefault(identifier); } diff --git a/Core/src/Managed/Stellar.Core/Data/Collections/DataContainer.cs b/Core/src/Managed/Stellar.Core/Data/Collections/DataContainer.cs index fa1f314..a16c47d 100644 --- a/Core/src/Managed/Stellar.Core/Data/Collections/DataContainer.cs +++ b/Core/src/Managed/Stellar.Core/Data/Collections/DataContainer.cs @@ -45,13 +45,13 @@ protected DataContainer(MetaQuant meta, FastConcurrentIdentifierMap data) ArgumentNullException.ThrowIfNull(data); Data = data; - Native.Create(UID.UID); + Native.Create(UID); foreach (var item in data.GetSnapshot()) - Native.Add(UID.UID, item.UID.UID); + Native.Add(UID, item.UID); if (IsReadOnly) - Native.Seal(UID.UID); + Native.Seal(UID); Register(_home); } @@ -61,7 +61,7 @@ protected DataContainer(MetaQuant meta, FastConcurrentIdentifierMap data) /// /// A meta quant of this container. /// Initial data stored in a dictionary. - protected DataContainer(MetaQuant meta, Dictionary data) + protected DataContainer(MetaQuant meta, Dictionary data) : this(meta, new FastConcurrentIdentifierMap(data)) { } @@ -88,7 +88,7 @@ protected DataContainer(MetaQuant meta) /// /// The identifier of the container. /// The container, or null if it is not registered. - public static IDataContainer? GetContainer(IIdentifier identifier) + public static IDataContainer? GetContainer(Identifier identifier) { return Global.CoreEngine.Current.Registry.DataContainers.Get(identifier); } @@ -96,7 +96,7 @@ protected DataContainer(MetaQuant meta) #region Item support /// - public abstract IIdentifiableQuantumObject? Get(IIdentifier identifier); + public abstract IIdentifiableQuantumObject? Get(Identifier identifier); /// /// Stores a quantum object by its identifier. @@ -113,7 +113,7 @@ public virtual bool Set(IIdentifiableQuantumObject obj) /// /// The unique identifier of the object. /// The object if found; otherwise, default. - public virtual T? Pop(IIdentifier id) + public virtual T? Pop(Identifier id) { return default; } @@ -123,7 +123,7 @@ public virtual bool Set(IIdentifiableQuantumObject obj) /// /// The unique identifier of the object. /// Thrown if is not found in the container. - public T this[IIdentifier key] + public T this[Identifier key] { get => Get(key) is T value ? value : throw new KeyNotFoundException($"{key} is not in the container"); set => Set(value); @@ -146,9 +146,9 @@ public void RefreshSnapshot() } /// - public bool ContainsKey(IIdentifier key) + public bool ContainsKey(Identifier key) { - return key is not null && Native.Contains(UID.UID, key.UID); + return Native.Contains(UID, key); } /// @@ -158,7 +158,7 @@ public bool Contains(IIdentifiableQuantumObject obj) } /// - public int Count => Native.Count(UID.UID); + public int Count => Native.Count(UID); /// public bool IsEmpty => Count == 0; @@ -171,7 +171,7 @@ public bool Contains(IIdentifiableQuantumObject obj) /// /// Gets the identifiers of the items, as the native side knows them. This is what is passed to native systems. /// - public Guid[] Identifiers => Native.Items(UID.UID); + public Identifier[] Identifiers => Native.Items(UID); /// /// Clears the container. @@ -179,7 +179,7 @@ public bool Contains(IIdentifiableQuantumObject obj) /// false if the container is read-only. public bool Clear() { - if (!Native.Clear(UID.UID)) + if (!Native.Clear(UID)) return false; Data.Clear(); @@ -239,6 +239,6 @@ public void Unregister(IQuantumObject? registry = null) public void Dispose() { Unregister(); - Native.Destroy(UID.UID); + Native.Destroy(UID); } } diff --git a/Core/src/Managed/Stellar.Core/Data/Collections/FastConcurrentIdentifierMap.cs b/Core/src/Managed/Stellar.Core/Data/Collections/FastConcurrentIdentifierMap.cs index 0909c7b..2b989d2 100644 --- a/Core/src/Managed/Stellar.Core/Data/Collections/FastConcurrentIdentifierMap.cs +++ b/Core/src/Managed/Stellar.Core/Data/Collections/FastConcurrentIdentifierMap.cs @@ -4,7 +4,7 @@ namespace Stellar.Core.Data.Collections; /// -/// High-performance thread-safe dictionary for keys. +/// High-performance thread-safe dictionary for keys. /// Uses snapshot-based iteration to avoid per-frame allocations and supports immediate visibility for "hot" items. /// /// The type of stored values. @@ -28,7 +28,7 @@ namespace Stellar.Core.Data.Collections; public sealed class FastConcurrentIdentifierMap : IEnumerable { - private readonly Dictionary _dict; + private readonly Dictionary _dict; private readonly ReaderWriterLockSlim _lock = new(); // Both arrays are replaced, never mutated: a reader that grabbed one iterates it with no lock. @@ -39,9 +39,9 @@ public sealed class FastConcurrentIdentifierMap /// Creates the map. Initial data is visible in the snapshot right away. /// /// The initial data. - public FastConcurrentIdentifierMap(IEnumerable>? data = null) + public FastConcurrentIdentifierMap(IEnumerable>? data = null) { - _dict = new Dictionary(data ?? [], IdentifierComparer.Instance); + _dict = new Dictionary(data ?? []); _snapshot = _dict.Values.ToArray(); } @@ -80,7 +80,7 @@ private void RebuildSnapshot() /// /// The key. /// The value, or default. - public T? GetValueOrDefault(IIdentifier key) + public T? GetValueOrDefault(Identifier key) { return TryGetValue(key, out var value) ? value : default; } @@ -91,9 +91,9 @@ private void RebuildSnapshot() /// The key. /// The found value, or default if not found. /// true if the key was found; otherwise, false. - public bool TryGetValue(IIdentifier key, out T? value) + public bool TryGetValue(Identifier key, out T? value) { - if (key is null) + if (key.IsEmpty) { value = default; return false; @@ -120,9 +120,9 @@ public bool TryGetValue(IIdentifier key, out T? value) /// If false, it becomes visible only after the next call. /// /// true if the addition succeeded; false if the key already exists. - public bool TryAdd(IIdentifier key, T value, bool immediate = false) + public bool TryAdd(Identifier key, T value, bool immediate = false) { - if (key is null) return false; + if (key.IsEmpty) return false; _lock.EnterWriteLock(); try @@ -150,9 +150,9 @@ public bool TryAdd(IIdentifier key, T value, bool immediate = false) /// This method rebuilds the snapshot inside the write lock, which may be expensive for bulk removals. /// For mass deletions, consider using . /// - public bool TryRemove(IIdentifier key, out T? value) + public bool TryRemove(Identifier key, out T? value) { - if (key is null) + if (key.IsEmpty) { value = default; return false; @@ -182,9 +182,9 @@ public bool TryRemove(IIdentifier key, out T? value) /// The element will disappear from iterations only after the next call. /// Useful for bulk removals to avoid repeated snapshot copies. /// - public bool TryRemoveDeferred(IIdentifier key, out T? value) + public bool TryRemoveDeferred(Identifier key, out T? value) { - if (key is null) + if (key.IsEmpty) { value = default; return false; @@ -204,9 +204,9 @@ public bool TryRemoveDeferred(IIdentifier key, out T? value) /// /// Checks whether the dictionary contains the specified key. /// - public bool ContainsKey(IIdentifier key) + public bool ContainsKey(Identifier key) { - if (key is null) return false; + if (key.IsEmpty) return false; _lock.EnterReadLock(); try diff --git a/Core/src/Managed/Stellar.Core/Data/Collections/IdentifierComparer.cs b/Core/src/Managed/Stellar.Core/Data/Collections/IdentifierComparer.cs deleted file mode 100644 index c9c05f1..0000000 --- a/Core/src/Managed/Stellar.Core/Data/Collections/IdentifierComparer.cs +++ /dev/null @@ -1,32 +0,0 @@ -using Stellar.Kernel; - -namespace Stellar.Core.Data.Collections; - -/// -/// Compares identifiers by value: two instances with the same UID are equal, -/// whatever their implementation is. -/// -public sealed class IdentifierComparer - : IEqualityComparer -{ - /// - /// Gets the shared instance. - /// - public static IdentifierComparer Instance { get; } = new(); - - private IdentifierComparer() - { - } - - /// - public bool Equals(IIdentifier? x, IIdentifier? y) - { - return ReferenceEquals(x, y) || (x is not null && y is not null && x.UID == y.UID); - } - - /// - public int GetHashCode(IIdentifier obj) - { - return obj.UID.GetHashCode(); - } -} diff --git a/Core/src/Managed/Stellar.Core/Data/Collections/Roster.cs b/Core/src/Managed/Stellar.Core/Data/Collections/Roster.cs index 5acbdf9..be8e54f 100644 --- a/Core/src/Managed/Stellar.Core/Data/Collections/Roster.cs +++ b/Core/src/Managed/Stellar.Core/Data/Collections/Roster.cs @@ -20,7 +20,7 @@ public class Roster /// Creates a roster with typed data and branches. /// public Roster(MetaQuant meta, FastConcurrentIdentifierMap data, - IEnumerable>> branches) + IEnumerable>> branches) : base(meta, data) { Branches = new ConcurrentIdentifierMap>(); @@ -32,8 +32,8 @@ public Roster(MetaQuant meta, FastConcurrentIdentifierMap data, /// /// Creates a roster with data and branches. /// - public Roster(MetaQuant metaData, Dictionary data, - IEnumerable>> branches) + public Roster(MetaQuant metaData, Dictionary data, + IEnumerable>> branches) : this(metaData, new FastConcurrentIdentifierMap(data), branches) { } @@ -41,8 +41,8 @@ public Roster(MetaQuant metaData, Dictionary data, /// /// Creates a roster with data. /// - public Roster(MetaQuant metaData, Dictionary data) - : this(metaData, data, new Dictionary>()) + public Roster(MetaQuant metaData, Dictionary data) + : this(metaData, data, new Dictionary>()) { } @@ -50,7 +50,7 @@ public Roster(MetaQuant metaData, Dictionary data) /// Creates an empty roster. /// public Roster(MetaQuant metaData) - : this(metaData, new Dictionary()) + : this(metaData, new Dictionary()) { } @@ -75,7 +75,7 @@ public Roster() /// Gets a branch. /// /// Thrown if there is no such branch. - public Roster GetBranch(IIdentifier identifier) + public Roster GetBranch(Identifier identifier) { return Branches.GetValueOrDefault(identifier) ?? throw new KeyNotFoundException($"{identifier} is not a branch"); @@ -89,7 +89,7 @@ public bool SaveBranch(Roster branch) { ArgumentNullException.ThrowIfNull(branch); - if (!Native.AddBranch(UID.UID, branch.UID.UID)) + if (!Native.AddBranch(UID, branch.UID)) return false; return Branches.TryAdd(branch.UID, branch); @@ -99,9 +99,9 @@ public bool SaveBranch(Roster branch) /// Removes a branch. /// /// The branch, or null if there is no such branch. - public Roster? PopBranch(IIdentifier identifier) + public Roster? PopBranch(Identifier identifier) { - if (identifier is null || !Native.RemoveBranch(UID.UID, identifier.UID)) + if (!Native.RemoveBranch(UID, identifier)) return null; Branches.TryRemove(identifier, out var branch); @@ -111,7 +111,7 @@ public bool SaveBranch(Roster branch) /// /// Creates and adds a branch with data. /// - public Roster NewBranch(MetaQuant meta, Dictionary data) + public Roster NewBranch(MetaQuant meta, Dictionary data) { var branch = new Roster(meta, data); SaveBranch(branch); @@ -123,15 +123,15 @@ public Roster NewBranch(MetaQuant meta, Dictionary data) /// public Roster NewBranch(MetaQuant metaData) { - return NewBranch(metaData, new Dictionary()); + return NewBranch(metaData, new Dictionary()); } /// /// Checks for a branch. /// - public bool ContainsBranch(IIdentifier identifier) + public bool ContainsBranch(Identifier identifier) { - return identifier is not null && Native.ContainsBranch(UID.UID, identifier.UID); + return Native.ContainsBranch(UID, identifier); } #endregion diff --git a/Core/src/Managed/Stellar.Core/Data/Collections/WritableTable.cs b/Core/src/Managed/Stellar.Core/Data/Collections/WritableTable.cs index ba3095a..7aa843e 100644 --- a/Core/src/Managed/Stellar.Core/Data/Collections/WritableTable.cs +++ b/Core/src/Managed/Stellar.Core/Data/Collections/WritableTable.cs @@ -21,7 +21,7 @@ public WritableTable(MetaQuant meta, FastConcurrentIdentifierMap data) } /// - public WritableTable(MetaQuant meta, Dictionary data) + public WritableTable(MetaQuant meta, Dictionary data) : base(meta, data) { } @@ -47,16 +47,16 @@ public WritableTable() /// public override bool Set(IIdentifiableQuantumObject obj) { - if (obj is not T typed || !Native.Add(UID.UID, obj.UID.UID)) + if (obj is not T typed || !Native.Add(UID, obj.UID)) return false; return Data.TryAdd(obj.UID, typed, true); } /// - public override T? Pop(IIdentifier id) + public override T? Pop(Identifier id) { - if (id is null || !Native.Remove(UID.UID, id.UID)) + if (!Native.Remove(UID, id)) return default; Data.TryRemove(id, out var quant); diff --git a/Core/src/Managed/Stellar.Core/Data/Registry/ConcurrentRegistry.cs b/Core/src/Managed/Stellar.Core/Data/Registry/ConcurrentRegistry.cs index bdfa95c..338d880 100644 --- a/Core/src/Managed/Stellar.Core/Data/Registry/ConcurrentRegistry.cs +++ b/Core/src/Managed/Stellar.Core/Data/Registry/ConcurrentRegistry.cs @@ -13,59 +13,43 @@ public abstract class ConcurrentRegistry : IRegistry where T : class, IRegistrableQuantumObject { - private readonly ConcurrentDictionary _items = new(); + private readonly ConcurrentDictionary _items = new(); /// /// Gets the identifier an object is stored under. /// - protected abstract IIdentifier IdentifierOf(T obj); + protected abstract Identifier IdentifierOf(T obj); /// - public bool Exists(IIdentifier id) + public bool Exists(Identifier id) { - return id is not null && _items.ContainsKey(id.UID); + return _items.ContainsKey(id); } /// public virtual bool Register(T obj) { ArgumentNullException.ThrowIfNull(obj); - return _items.TryAdd(IdentifierOf(obj).UID, obj); + return _items.TryAdd(IdentifierOf(obj), obj); } /// - public T? Get(IIdentifier id) + public T? Get(Identifier id) { - return id is null ? null : Get(id.UID); - } - - /// - /// Retrieves a registered object by the value of its identifier. - /// - public T? Get(Guid uid) - { - return _items.GetValueOrDefault(uid); + return _items.GetValueOrDefault(id); } /// - public T? Pop(IIdentifier id) - { - return id is null ? null : Pop(id.UID); - } - - /// - /// Removes and returns a registered object by the value of its identifier. - /// - public virtual T? Pop(Guid uid) + public virtual T? Pop(Identifier id) { - return _items.TryRemove(uid, out var obj) ? obj : null; + return _items.TryRemove(id, out var obj) ? obj : null; } /// public int Size => _items.Count; /// - public ICollection Keys => _items.Values.Select(IdentifierOf).ToArray(); + public ICollection Keys => _items.Keys.ToArray(); /// public ICollection Values => _items.Values.ToArray(); diff --git a/Core/src/Managed/Stellar.Core/Data/Registry/DataContainerRegistry.cs b/Core/src/Managed/Stellar.Core/Data/Registry/DataContainerRegistry.cs index 2b077e8..fe5e70a 100644 --- a/Core/src/Managed/Stellar.Core/Data/Registry/DataContainerRegistry.cs +++ b/Core/src/Managed/Stellar.Core/Data/Registry/DataContainerRegistry.cs @@ -17,7 +17,7 @@ public DataContainerRegistry() } /// - protected override IIdentifier IdentifierOf(IDataContainer obj) + protected override Identifier IdentifierOf(IDataContainer obj) { return obj.UID; } diff --git a/Core/src/Managed/Stellar.Core/Data/Registry/MetaQuantsRegistry.cs b/Core/src/Managed/Stellar.Core/Data/Registry/MetaQuantsRegistry.cs index d79703f..dfb6928 100644 --- a/Core/src/Managed/Stellar.Core/Data/Registry/MetaQuantsRegistry.cs +++ b/Core/src/Managed/Stellar.Core/Data/Registry/MetaQuantsRegistry.cs @@ -19,7 +19,7 @@ public MetaQuantsRegistry() } /// - protected override IIdentifier IdentifierOf(TMeta obj) + protected override Identifier IdentifierOf(TMeta obj) { return obj.UID; } diff --git a/Core/src/Managed/Stellar.Core/Data/Registry/QuantsRegistry.cs b/Core/src/Managed/Stellar.Core/Data/Registry/QuantsRegistry.cs index fd01884..9c35aa6 100644 --- a/Core/src/Managed/Stellar.Core/Data/Registry/QuantsRegistry.cs +++ b/Core/src/Managed/Stellar.Core/Data/Registry/QuantsRegistry.cs @@ -19,7 +19,7 @@ public QuantsRegistry() } /// - protected override IIdentifier IdentifierOf(T obj) + protected override Identifier IdentifierOf(T obj) { return obj.UID; } diff --git a/Core/src/Managed/Stellar.Core/Data/Registry/RegistryBinding.cs b/Core/src/Managed/Stellar.Core/Data/Registry/RegistryBinding.cs index 088d560..aca82e3 100644 --- a/Core/src/Managed/Stellar.Core/Data/Registry/RegistryBinding.cs +++ b/Core/src/Managed/Stellar.Core/Data/Registry/RegistryBinding.cs @@ -20,7 +20,7 @@ public static void Register(IQuantumObject registry, T item) Cast(registry).Register(item); } - public static void Unregister(IQuantumObject registry, IIdentifier id) + public static void Unregister(IQuantumObject registry, Identifier id) where T : IRegistrableQuantumObject { Cast(registry).Pop(id); diff --git a/Core/src/Managed/Stellar.Core/Failures/BaseLevels/FailureLevel.cs b/Core/src/Managed/Stellar.Core/Failures/BaseLevels/FailureLevel.cs index ea35784..b47bb1a 100644 --- a/Core/src/Managed/Stellar.Core/Failures/BaseLevels/FailureLevel.cs +++ b/Core/src/Managed/Stellar.Core/Failures/BaseLevels/FailureLevel.cs @@ -21,18 +21,17 @@ protected FailureLevel(string name, IFailureDispatcherMeta dispatcherMeta) ArgumentNullException.ThrowIfNull(dispatcherMeta); // Levels belong to their dispatcher and two dispatchers may both have an "Error": the label is not global. - Label = Core.Label.Create(name, UID, false) - ?? throw new ArgumentException("A failure level needs a name", nameof(name)); + Label = new Label(UID, name); _dispatcherMeta = dispatcherMeta; Register(_dispatcherMeta.FailureLevels); } /// - public IIdentifier UID { get; } = Identifier.CreateAndRegister(); + public Identifier UID { get; } = Identifier.New(); /// - public ILabel Label { get; } + public Label Label { get; } /// public abstract bool IsEnabled { get; set; } diff --git a/Core/src/Managed/Stellar.Core/Failures/FailureCatch.cs b/Core/src/Managed/Stellar.Core/Failures/FailureCatch.cs index e50b9e0..a606422 100644 --- a/Core/src/Managed/Stellar.Core/Failures/FailureCatch.cs +++ b/Core/src/Managed/Stellar.Core/Failures/FailureCatch.cs @@ -24,7 +24,7 @@ public sealed class FailureCatch( private Action? _finally; /// - public IIdentifier UID { get; } = Identifier.Create(); + public Identifier UID { get; } = Identifier.New(); /// public Exception? Caught { get; private set; } diff --git a/Core/src/Managed/Stellar.Core/Failures/FailureDispatcher.cs b/Core/src/Managed/Stellar.Core/Failures/FailureDispatcher.cs index cdc3b59..9ba1696 100644 --- a/Core/src/Managed/Stellar.Core/Failures/FailureDispatcher.cs +++ b/Core/src/Managed/Stellar.Core/Failures/FailureDispatcher.cs @@ -1,6 +1,7 @@ using Stellar.Core.Data.Collections; using Stellar.Core.Failures.Handlers; using Stellar.Core.Quantization; +using Stellar.Kernel; using Stellar.Kernel.Failures; using Stellar.Kernel.Failures.Handlers; using Stellar.Kernel.Quantization; @@ -30,7 +31,7 @@ public interface IFailureDispatcherMeta public class FailureDispatcherMeta( DataContainer? failureLevels = null, IFailureHandlerProvider? failureHandlerProvider = null -) : MetaQuant(Identifier.CreateAndRegister()), IFailureDispatcherMeta +) : MetaQuant(Identifier.New()), IFailureDispatcherMeta { /// public DataContainer FailureLevels { get; } = diff --git a/Core/src/Managed/Stellar.Core/Failures/Handlers/FailureHandlerProvider.cs b/Core/src/Managed/Stellar.Core/Failures/Handlers/FailureHandlerProvider.cs index b0d0307..c7d497c 100644 --- a/Core/src/Managed/Stellar.Core/Failures/Handlers/FailureHandlerProvider.cs +++ b/Core/src/Managed/Stellar.Core/Failures/Handlers/FailureHandlerProvider.cs @@ -30,7 +30,7 @@ public bool Matches(IFailure failure) /// /// The container of handlers. A new one is created when omitted. public class HandlerProviderMeta(DataContainer? handlers = null) - : MetaQuant(Identifier.CreateAndRegister()) + : MetaQuant(Identifier.New()) { /// /// Gets the handlers. @@ -40,7 +40,7 @@ public class HandlerProviderMeta(DataContainer? handlers = null /// /// Gets the binding of each handler. /// - public ConcurrentDictionary Bindings { get; } = new(IdentifierComparer.Instance); + public ConcurrentDictionary Bindings { get; } = new(); } /// diff --git a/Core/src/Managed/Stellar.Core/Global/CoreEngine.cs b/Core/src/Managed/Stellar.Core/Global/CoreEngine.cs index 4e6957b..570f929 100644 --- a/Core/src/Managed/Stellar.Core/Global/CoreEngine.cs +++ b/Core/src/Managed/Stellar.Core/Global/CoreEngine.cs @@ -193,10 +193,8 @@ internal CoreRegistries(CoreEngine engine) } /// Gets the registry of identifiers. - public IRegistry Identifiers => _engine.Native.Identifiers; /// Gets the registry of labels. - public IRegistry /// The lifetime. When null, the meta quant never expires. /// Unique ID. A new one is created when omitted. - public TimedMetaQuant(TimeSpan? lifetime = null, IIdentifier? identifier = null) - : base(identifier ?? Identifier.CreateAndRegister()) + public TimedMetaQuant(TimeSpan? lifetime = null, Identifier? identifier = null) + : base(identifier ?? Identifier.New()) { CreatedAt = StartAt = DateTime.UtcNow; Lifetime = lifetime; diff --git a/Core/src/Native/Stellar.Native.Core/CoreContext.cpp b/Core/src/Native/Stellar.Native.Core/CoreContext.cpp index 1584a87..a60fbd5 100644 --- a/Core/src/Native/Stellar.Native.Core/CoreContext.cpp +++ b/Core/src/Native/Stellar.Native.Core/CoreContext.cpp @@ -6,8 +6,6 @@ namespace Stellar::Native::Core struct CoreContext::Impl { // Declared in reverse order of dependence: modules go first when the context is destroyed - Data::Registry::IdentifierRegistry identifiers; - Data::Registry::LabelRegistry labels; Data::Registry::ContainerRegistry containers; Modules::ModuleRegistry modules; }; @@ -23,16 +21,6 @@ namespace Stellar::Native::Core return instance; } - Link CoreContext::Identifiers() const - { - return _impl->identifiers; - } - - Link CoreContext::Labels() const - { - return _impl->labels; - } - Link CoreContext::Containers() const { return _impl->containers; diff --git a/Core/src/Native/Stellar.Native.Core/CoreContext.h b/Core/src/Native/Stellar.Native.Core/CoreContext.h index 53609d4..ed12907 100644 --- a/Core/src/Native/Stellar.Native.Core/CoreContext.h +++ b/Core/src/Native/Stellar.Native.Core/CoreContext.h @@ -8,14 +8,12 @@ #include -#include "Data/Registry/IdentifierRegistry.h" -#include "Data/Registry/LabelRegistry.h" #include "Data/Registry/ContainerRegistry.h" #include "Modules/ModuleRegistry.h" namespace Stellar::Native::Core { - /// @brief Everything the native core keeps for one engine: its identifiers, labels, containers and modules. + /// @brief Everything the native core keeps for one engine: its containers and modules. /// /// Engines are objects, not the process: an editor and the game it runs each have a context, and destroying one /// takes its registries with it without touching the other. The default context serves code that runs outside @@ -35,11 +33,7 @@ namespace Stellar::Native::Core /// @brief Gets the default context of the process. [[nodiscard]] static Link Default(); - /// @brief Gets the registry of identifiers. - [[nodiscard]] Link Identifiers() const; - /// @brief Gets the registry of labels. - [[nodiscard]] Link Labels() const; /// @brief Gets the registry of the membership of containers. [[nodiscard]] Link Containers() const; diff --git a/Core/src/Native/Stellar.Native.Core/Data/Registry/IdentifierRegistry.cpp b/Core/src/Native/Stellar.Native.Core/Data/Registry/IdentifierRegistry.cpp deleted file mode 100644 index 7a26382..0000000 --- a/Core/src/Native/Stellar.Native.Core/Data/Registry/IdentifierRegistry.cpp +++ /dev/null @@ -1,44 +0,0 @@ -#include "pch.h" -#include "Data/Registry/IdentifierRegistry.h" - -#include "Data/Collections/ConcurrentUnorderedMap.h" - -namespace Stellar::Native::Core::Data::Registry -{ - struct IdentifierRegistry::Impl - { - Collections::ConcurrentUnorderedIdentifierMap identifiers{64}; - }; - - IdentifierRegistry::IdentifierRegistry() : - _impl(std::make_unique()) {} - - IdentifierRegistry::~IdentifierRegistry() = default; - - - bool IdentifierRegistry::Register(Link id) - { - return !id.IsNull() && _impl->identifiers.TryAdd(id, id); - } - - bool IdentifierRegistry::Unregister(Link id) - { - Identifier removed; - return _impl->identifiers.TryRemove(id, removed); - } - - bool IdentifierRegistry::Contains(Link id) const - { - return _impl->identifiers.Contains(id); - } - - std::size_t IdentifierRegistry::size() const - { - return _impl->identifiers.size(); - } - - std::vector IdentifierRegistry::Snapshot() const - { - return _impl->identifiers.Keys(); - } -} diff --git a/Core/src/Native/Stellar.Native.Core/Data/Registry/IdentifierRegistry.h b/Core/src/Native/Stellar.Native.Core/Data/Registry/IdentifierRegistry.h deleted file mode 100644 index 2b43575..0000000 --- a/Core/src/Native/Stellar.Native.Core/Data/Registry/IdentifierRegistry.h +++ /dev/null @@ -1,48 +0,0 @@ -// StellarEngine -// Copyright (c) 2026 QuantumDevTeam -// SPDX-License-Identifier: PolyForm-Noncommercial-1.0.0 - -/// @file Data/Registry/IdentifierRegistry.h -/// @brief The registry of identifiers: the single source of truth for both sides of the engine. -#pragma once - -#include -#include -#include - -#include "Identifier.h" - -namespace Stellar::Native::Core::Data::Registry -{ - /// @brief The registry of identifiers of one engine (CoreContext). - /// - /// Managed code has no registry of its own: it reaches this one through the wrappers. - class STELLAR_CORE_API IdentifierRegistry final - { - struct Impl; - UniquePtr _impl; - - public: - /// @brief Creates an empty registry. A CoreContext owns one; tests may make their own. - IdentifierRegistry(); - ~IdentifierRegistry(); - - IdentifierRegistry(const IdentifierRegistry&) = delete; - IdentifierRegistry& operator=(const IdentifierRegistry&) = delete; - - /// @brief Adds an identifier. @return False if it is registered already or null. - bool Register(Link id); - - /// @brief Removes an identifier. @return False if it is not registered. - bool Unregister(Link id); - - /// @brief Checks for an identifier. - [[nodiscard]] bool Contains(Link id) const; - - /// @brief Gets the number of identifiers. - [[nodiscard]] std::size_t size() const; - - /// @brief Gets a snapshot of the identifiers. - [[nodiscard]] std::vector Snapshot() const; - }; -} diff --git a/Core/src/Native/Stellar.Native.Core/Data/Registry/LabelRegistry.cpp b/Core/src/Native/Stellar.Native.Core/Data/Registry/LabelRegistry.cpp deleted file mode 100644 index 6e10fee..0000000 --- a/Core/src/Native/Stellar.Native.Core/Data/Registry/LabelRegistry.cpp +++ /dev/null @@ -1,106 +0,0 @@ -#include "pch.h" -#include "Data/Registry/LabelRegistry.h" - -#include -#include -#include -#include - -namespace Stellar::Native::Core::Data::Registry -{ - struct LabelRegistry::Impl - { - // One lock for both maps: registering a label must be atomic across them - mutable std::shared_mutex mutex; - std::unordered_map> byId; - std::unordered_map byName; - - bool EraseLocked(Link id) - { - const auto it = byId.find(id); - if (it == byId.end()) - return false; - - // The key of byName views the stored string, so it goes first - byName.erase(*it->second); - byId.erase(it); - return true; - } - }; - - LabelRegistry::LabelRegistry() : - _impl(std::make_unique()) {} - - LabelRegistry::~LabelRegistry() = default; - - - std::optional - - - - diff --git a/Core/src/NativeInterop/Stellar.Native.Core.Wrapper.Cli/Wrapper/Data/Registry/ContainerRegistry.cli.h b/Core/src/NativeInterop/Stellar.Native.Core.Wrapper.Cli/Wrapper/Data/Registry/ContainerRegistry.cli.h index 8ad70e9..a47be79 100644 --- a/Core/src/NativeInterop/Stellar.Native.Core.Wrapper.Cli/Wrapper/Data/Registry/ContainerRegistry.cli.h +++ b/Core/src/NativeInterop/Stellar.Native.Core.Wrapper.Cli/Wrapper/Data/Registry/ContainerRegistry.cli.h @@ -32,54 +32,54 @@ namespace Stellar::Core::Data::Registry public: /// Creates an empty container. /// false if it exists already. - bool Create(Guid container); + bool Create(::Stellar::Kernel::Identifier container); /// Destroys a container. /// false if it does not exist. - bool Destroy(Guid container); + bool Destroy(::Stellar::Kernel::Identifier container); /// Checks whether a container exists. - bool Exists(Guid container); + bool Exists(::Stellar::Kernel::Identifier container); /// Makes a container read-only, for good. - void Seal(Guid container); + void Seal(::Stellar::Kernel::Identifier container); /// Checks whether a container is read-only. - bool IsSealed(Guid container); + bool IsSealed(::Stellar::Kernel::Identifier container); /// Adds an item. /// false if it is there already or the container is sealed. - bool Add(Guid container, Guid item); + bool Add(::Stellar::Kernel::Identifier container, ::Stellar::Kernel::Identifier item); /// Removes an item. /// false if it is not there or the container is sealed. - bool Remove(Guid container, Guid item); + bool Remove(::Stellar::Kernel::Identifier container, ::Stellar::Kernel::Identifier item); /// Checks for an item. - bool Contains(Guid container, Guid item); + bool Contains(::Stellar::Kernel::Identifier container, ::Stellar::Kernel::Identifier item); /// Gets the number of items. - int Count(Guid container); + int Count(::Stellar::Kernel::Identifier container); /// Gets a snapshot of the items. - array^ Items(Guid container); + array<::Stellar::Kernel::Identifier>^ Items(::Stellar::Kernel::Identifier container); /// Removes every item. /// false if the container is sealed. - bool Clear(Guid container); + bool Clear(::Stellar::Kernel::Identifier container); /// Nests a container. The branch must exist. /// false if it is nested already or is the container itself. - bool AddBranch(Guid container, Guid branch); + bool AddBranch(::Stellar::Kernel::Identifier container, ::Stellar::Kernel::Identifier branch); /// Removes a nested container. /// false if it is not nested. - bool RemoveBranch(Guid container, Guid branch); + bool RemoveBranch(::Stellar::Kernel::Identifier container, ::Stellar::Kernel::Identifier branch); /// Checks for a nested container. - bool ContainsBranch(Guid container, Guid branch); + bool ContainsBranch(::Stellar::Kernel::Identifier container, ::Stellar::Kernel::Identifier branch); /// Gets a snapshot of the nested containers. - array^ Branches(Guid container); + array<::Stellar::Kernel::Identifier>^ Branches(::Stellar::Kernel::Identifier container); }; } diff --git a/Core/src/NativeInterop/Stellar.Native.Core.Wrapper.Cli/Wrapper/Data/Registry/ContainerRegistry.cpp b/Core/src/NativeInterop/Stellar.Native.Core.Wrapper.Cli/Wrapper/Data/Registry/ContainerRegistry.cpp index ccec0f2..6c17fac 100644 --- a/Core/src/NativeInterop/Stellar.Native.Core.Wrapper.Cli/Wrapper/Data/Registry/ContainerRegistry.cpp +++ b/Core/src/NativeInterop/Stellar.Native.Core.Wrapper.Cli/Wrapper/Data/Registry/ContainerRegistry.cpp @@ -10,9 +10,9 @@ namespace Stellar::Core::Data::Registry { namespace { - array^ ToManaged(Link> identifiers) + array<::Stellar::Kernel::Identifier>^ ToManaged(Link> identifiers) { - auto result = gcnew array(static_cast(identifiers.size())); + auto result = gcnew array<::Stellar::Kernel::Identifier>(static_cast(identifiers.size())); for (int i = 0; i < result->Length; ++i) result[i] = NativeConvert::ToManaged(identifiers[static_cast(i)]); @@ -21,77 +21,77 @@ namespace Stellar::Core::Data::Registry } } - bool ContainerRegistry::Create(Guid container) + bool ContainerRegistry::Create(::Stellar::Kernel::Identifier container) { return NativeCall<&NativeRegistry::Create>(_context->Native().Containers(), NativeConvert::ToNative(container)); } - bool ContainerRegistry::Destroy(Guid container) + bool ContainerRegistry::Destroy(::Stellar::Kernel::Identifier container) { return NativeCall<&NativeRegistry::Destroy>(_context->Native().Containers(), NativeConvert::ToNative(container)); } - bool ContainerRegistry::Exists(Guid container) + bool ContainerRegistry::Exists(::Stellar::Kernel::Identifier container) { return NativeCall<&NativeRegistry::Exists>(_context->Native().Containers(), NativeConvert::ToNative(container)); } - void ContainerRegistry::Seal(Guid container) + void ContainerRegistry::Seal(::Stellar::Kernel::Identifier container) { NativeCall<&NativeRegistry::Seal>(_context->Native().Containers(), NativeConvert::ToNative(container)); } - bool ContainerRegistry::IsSealed(Guid container) + bool ContainerRegistry::IsSealed(::Stellar::Kernel::Identifier container) { return NativeCall<&NativeRegistry::IsSealed>(_context->Native().Containers(), NativeConvert::ToNative(container)); } - bool ContainerRegistry::Add(Guid container, Guid item) + bool ContainerRegistry::Add(::Stellar::Kernel::Identifier container, ::Stellar::Kernel::Identifier item) { return NativeCall<&NativeRegistry::Add>(_context->Native().Containers(), NativeConvert::ToNative(container), NativeConvert::ToNative(item)); } - bool ContainerRegistry::Remove(Guid container, Guid item) + bool ContainerRegistry::Remove(::Stellar::Kernel::Identifier container, ::Stellar::Kernel::Identifier item) { return NativeCall<&NativeRegistry::Remove>(_context->Native().Containers(), NativeConvert::ToNative(container), NativeConvert::ToNative(item)); } - bool ContainerRegistry::Contains(Guid container, Guid item) + bool ContainerRegistry::Contains(::Stellar::Kernel::Identifier container, ::Stellar::Kernel::Identifier item) { return NativeCall<&NativeRegistry::Contains>(_context->Native().Containers(), NativeConvert::ToNative(container), NativeConvert::ToNative(item)); } - int ContainerRegistry::Count(Guid container) + int ContainerRegistry::Count(::Stellar::Kernel::Identifier container) { return static_cast(NativeCall<&NativeRegistry::Count>(_context->Native().Containers(), NativeConvert::ToNative(container))); } - array^ ContainerRegistry::Items(Guid container) + array<::Stellar::Kernel::Identifier>^ ContainerRegistry::Items(::Stellar::Kernel::Identifier container) { return ToManaged(NativeCall<&NativeRegistry::Items>(_context->Native().Containers(), NativeConvert::ToNative(container))); } - bool ContainerRegistry::Clear(Guid container) + bool ContainerRegistry::Clear(::Stellar::Kernel::Identifier container) { return NativeCall<&NativeRegistry::Clear>(_context->Native().Containers(), NativeConvert::ToNative(container)); } - bool ContainerRegistry::AddBranch(Guid container, Guid branch) + bool ContainerRegistry::AddBranch(::Stellar::Kernel::Identifier container, ::Stellar::Kernel::Identifier branch) { return NativeCall<&NativeRegistry::AddBranch>(_context->Native().Containers(), NativeConvert::ToNative(container), NativeConvert::ToNative(branch)); } - bool ContainerRegistry::RemoveBranch(Guid container, Guid branch) + bool ContainerRegistry::RemoveBranch(::Stellar::Kernel::Identifier container, ::Stellar::Kernel::Identifier branch) { return NativeCall<&NativeRegistry::RemoveBranch>(_context->Native().Containers(), NativeConvert::ToNative(container), NativeConvert::ToNative(branch)); } - bool ContainerRegistry::ContainsBranch(Guid container, Guid branch) + bool ContainerRegistry::ContainsBranch(::Stellar::Kernel::Identifier container, ::Stellar::Kernel::Identifier branch) { return NativeCall<&NativeRegistry::ContainsBranch>(_context->Native().Containers(), NativeConvert::ToNative(container), NativeConvert::ToNative(branch)); } - array^ ContainerRegistry::Branches(Guid container) + array<::Stellar::Kernel::Identifier>^ ContainerRegistry::Branches(::Stellar::Kernel::Identifier container) { return ToManaged(NativeCall<&NativeRegistry::Branches>(_context->Native().Containers(), NativeConvert::ToNative(container))); } diff --git a/Core/src/NativeInterop/Stellar.Native.Core.Wrapper.Cli/Wrapper/Data/Registry/IdentifierRegistry.cli.h b/Core/src/NativeInterop/Stellar.Native.Core.Wrapper.Cli/Wrapper/Data/Registry/IdentifierRegistry.cli.h deleted file mode 100644 index c482cde..0000000 --- a/Core/src/NativeInterop/Stellar.Native.Core.Wrapper.Cli/Wrapper/Data/Registry/IdentifierRegistry.cli.h +++ /dev/null @@ -1,54 +0,0 @@ -// StellarEngine -// Copyright (c) 2026 QuantumDevTeam -// SPDX-License-Identifier: PolyForm-Noncommercial-1.0.0 - -/// @file Wrapper/Data/Registry/IdentifierRegistry.cli.h -/// @brief The managed face of Stellar::Native::Core::Data::Registry::IdentifierRegistry. -#pragma once - -#include "Wrapper/Identifier.cli.h" -#include "Wrapper/Native/CoreContext.cli.h" - -namespace Stellar::Core::Data::Registry -{ - using namespace System; - using namespace System::Collections::Generic; - using namespace Stellar::Kernel; - - /// - /// The registry of identifiers. It holds no state: it is a view of the native registry. - /// - public ref class IdentifierRegistry sealed : Stellar::Kernel::Data::Registry::IRegistry - { - Stellar::Core::Native::CoreContext^ _context; - - internal: - /// The registry of a context: only the context makes one. - IdentifierRegistry(Stellar::Core::Native::CoreContext^ context) : _context(context) {} - - public: - /// - virtual bool Exists(IIdentifier^ id); - - /// - virtual bool Register(Identifier^ obj); - - /// - virtual Identifier^ Get(IIdentifier^ id); - - /// Finds a registered identifier by its value. - Identifier^ Get(Guid uid); - - /// - virtual Identifier^ Pop(IIdentifier^ id); - - /// - virtual property int Size { int get(); } - - /// - virtual property ICollection^ Keys { ICollection^ get(); } - - /// - virtual property ICollection^ Values { ICollection^ get(); } - }; -} diff --git a/Core/src/NativeInterop/Stellar.Native.Core.Wrapper.Cli/Wrapper/Data/Registry/IdentifierRegistry.cpp b/Core/src/NativeInterop/Stellar.Native.Core.Wrapper.Cli/Wrapper/Data/Registry/IdentifierRegistry.cpp deleted file mode 100644 index f6ce5e0..0000000 --- a/Core/src/NativeInterop/Stellar.Native.Core.Wrapper.Cli/Wrapper/Data/Registry/IdentifierRegistry.cpp +++ /dev/null @@ -1,68 +0,0 @@ -#include "Wrapper/Data/Registry/IdentifierRegistry.cli.h" - -using Stellar::Core::Native::NativeCall; -using Stellar::Core::Native::NativeConvert; -using NativeRegistry = nc::Data::Registry::IdentifierRegistry; - -namespace Stellar::Core::Data::Registry -{ - bool IdentifierRegistry::Exists(IIdentifier^ id) - { - if (id == nullptr) - return false; - - return NativeCall<&NativeRegistry::Contains>(_context->Native().Identifiers(), NativeConvert::ToNative(id->UID)); - } - - bool IdentifierRegistry::Register(Identifier^ obj) - { - if (obj == nullptr) - throw gcnew ArgumentNullException("obj"); - - return NativeCall<&NativeRegistry::Register>(_context->Native().Identifiers(), NativeConvert::ToNative(obj->UID)); - } - - Identifier^ IdentifierRegistry::Get(IIdentifier^ id) - { - return id == nullptr ? nullptr : Get(id->UID); - } - - Identifier^ IdentifierRegistry::Get(Guid uid) - { - return NativeCall<&NativeRegistry::Contains>(_context->Native().Identifiers(), NativeConvert::ToNative(uid)) ? gcnew Identifier(uid) : nullptr; - } - - Identifier^ IdentifierRegistry::Pop(IIdentifier^ id) - { - if (id == nullptr) - return nullptr; - - return NativeCall<&NativeRegistry::Unregister>(_context->Native().Identifiers(), NativeConvert::ToNative(id->UID)) ? gcnew Identifier(id->UID) : nullptr; - } - - int IdentifierRegistry::Size::get() - { - return static_cast(_context->Native().Identifiers().size()); - } - - ICollection^ IdentifierRegistry::Keys::get() - { - auto keys = gcnew List(); - - for each (Identifier^ id in Values) - keys->Add(id); - - return keys; - } - - ICollection^ IdentifierRegistry::Values::get() - { - const auto snapshot = NativeCall<&NativeRegistry::Snapshot>(_context->Native().Identifiers()); - auto values = gcnew List(static_cast(snapshot.size())); - - for (Link id : snapshot) - values->Add(gcnew Identifier(NativeConvert::ToManaged(id))); - - return values; - } -} diff --git a/Core/src/NativeInterop/Stellar.Native.Core.Wrapper.Cli/Wrapper/Data/Registry/LabelRegistry.cli.h b/Core/src/NativeInterop/Stellar.Native.Core.Wrapper.Cli/Wrapper/Data/Registry/LabelRegistry.cli.h deleted file mode 100644 index 41b70a9..0000000 --- a/Core/src/NativeInterop/Stellar.Native.Core.Wrapper.Cli/Wrapper/Data/Registry/LabelRegistry.cli.h +++ /dev/null @@ -1,55 +0,0 @@ -// StellarEngine -// Copyright (c) 2026 QuantumDevTeam -// SPDX-License-Identifier: PolyForm-Noncommercial-1.0.0 - -/// @file Wrapper/Data/Registry/LabelRegistry.cli.h -/// @brief The managed face of Stellar::Native::Core::Data::Registry::LabelRegistry. -#pragma once - -#include "Wrapper/Label.cli.h" -#include "Wrapper/Native/CoreContext.cli.h" - -namespace Stellar::Core::Data::Registry -{ - using namespace System; - using namespace System::Collections::Generic; - using namespace Stellar::Kernel; - - /// - /// The registry of labels. It holds no state: it is a view of the native registry. - /// - public ref class LabelRegistry sealed : Stellar::Kernel::Data::Registry::IRegistry - { - Stellar::Core::Native::CoreContext^ _context; - - internal: - /// The registry of a context: only the context makes one. - LabelRegistry(Stellar::Core::Native::CoreContext^ context) : _context(context) {} - - public: - /// - virtual bool Exists(IIdentifier^ id); - - /// - virtual bool Register(Label^ obj); - - /// - virtual Label^ Get(IIdentifier^ id); - - /// Finds a label by its name. - /// The label, or null if the name is not registered. - Label^ GetByName(String^ name); - - /// - virtual Label^ Pop(IIdentifier^ id); - - /// - virtual property int Size { int get(); } - - /// Not supported: the native registry does not enumerate labels. - virtual property ICollection^ Keys { ICollection^ get(); } - - /// Not supported: the native registry does not enumerate labels. - virtual property ICollection^ Values { ICollection^ get(); } - }; -} diff --git a/Core/src/NativeInterop/Stellar.Native.Core.Wrapper.Cli/Wrapper/Data/Registry/LabelRegistry.cpp b/Core/src/NativeInterop/Stellar.Native.Core.Wrapper.Cli/Wrapper/Data/Registry/LabelRegistry.cpp deleted file mode 100644 index 2d25a2d..0000000 --- a/Core/src/NativeInterop/Stellar.Native.Core.Wrapper.Cli/Wrapper/Data/Registry/LabelRegistry.cpp +++ /dev/null @@ -1,74 +0,0 @@ -#include "Wrapper/Data/Registry/LabelRegistry.cli.h" - -using Stellar::Core::Native::NativeCall; -using Stellar::Core::Native::NativeConvert; -using NativeRegistry = nc::Data::Registry::LabelRegistry; - -namespace -{ - // The native registry looks labels up by identifier and by name: a member pointer must say which one - constexpr auto NativeGetById = static_cast (NativeRegistry::*)(Link) const>(&NativeRegistry::Get); - constexpr auto NativeGetByName = static_cast (NativeRegistry::*)(std::string_view) const>(&NativeRegistry::Get); - constexpr auto NativeUnregisterById = static_cast)>(&NativeRegistry::Unregister); -} - -namespace Stellar::Core::Data::Registry -{ - bool LabelRegistry::Exists(IIdentifier^ id) - { - if (id == nullptr) - return false; - - return NativeCall<&NativeRegistry::Contains>(_context->Native().Labels(), NativeConvert::ToNative(id->UID)); - } - - bool LabelRegistry::Register(Label^ obj) - { - if (obj == nullptr) - throw gcnew ArgumentNullException("obj"); - - return NativeCall<&NativeRegistry::Register>(_context->Native().Labels(), NativeConvert::ToNative(obj->Name), NativeConvert::ToNative(obj->UID->UID)).has_value(); - } - - Label^ LabelRegistry::Get(IIdentifier^ id) - { - if (id == nullptr) - return nullptr; - - const auto label = NativeCall(_context->Native().Labels(), NativeConvert::ToNative(id->UID)); - return label.has_value() ? Label::FromNative(id->UID, NativeConvert::ToManaged(label->GetName())) : nullptr; - } - - Label^ LabelRegistry::GetByName(String^ name) - { - if (String::IsNullOrEmpty(name)) - return nullptr; - - const auto label = NativeCall(_context->Native().Labels(), NativeConvert::ToNative(name)); - return label.has_value() ? Label::FromNative(NativeConvert::ToManaged(label->GetUID()), name) : nullptr; - } - - Label^ LabelRegistry::Pop(IIdentifier^ id) - { - Label^ label = Get(id); - if (label == nullptr) - return nullptr; - - return NativeCall(_context->Native().Labels(), NativeConvert::ToNative(id->UID)) ? label : nullptr; - } - - int LabelRegistry::Size::get() - { - return static_cast(_context->Native().Labels().size()); - } - - ICollection^ LabelRegistry::Keys::get() - { - throw gcnew NotSupportedException("Labels are looked up, not enumerated"); - } - - ICollection^ LabelRegistry::Values::get() - { - throw gcnew NotSupportedException("Labels are looked up, not enumerated"); - } -} diff --git a/Core/src/NativeInterop/Stellar.Native.Core.Wrapper.Cli/Wrapper/Identifier.cli.h b/Core/src/NativeInterop/Stellar.Native.Core.Wrapper.Cli/Wrapper/Identifier.cli.h deleted file mode 100644 index 169c143..0000000 --- a/Core/src/NativeInterop/Stellar.Native.Core.Wrapper.Cli/Wrapper/Identifier.cli.h +++ /dev/null @@ -1,91 +0,0 @@ -// StellarEngine -// Copyright (c) 2026 QuantumDevTeam -// SPDX-License-Identifier: PolyForm-Noncommercial-1.0.0 - -/// @file Wrapper/Identifier.cli.h -/// @brief The managed face of Stellar::Native::Core::Identifier. -#pragma once - -#include "Wrapper/Interop.cli.h" - -namespace Stellar::Core -{ - using namespace System; - using namespace Stellar::Kernel; - using namespace Stellar::Kernel::Quantization; - - /// - /// The unique identifier of the engine, a managed face of Stellar::Native::Core::Identifier. - /// - /// - /// Native systems address their objects by identifier: managed code passes an identifier instead of marshalling the - /// object. The registry of identifiers exists only on the native side. - /// - public ref class Identifier sealed : IIdentifier, IEquatable - { - Guid _uid; - - public: - /// Wraps an existing value. - Identifier(Guid uid); - - /// - virtual property Guid UID { Guid get(); } - - /// Gets a value indicating whether the identifier is in the native registry. - property bool IsRegistered { bool get(); } - - /// Registers the identifier in the native registry. - void Register(); - - /// - virtual void Register(IQuantumObject^ registry); - - /// Removes the identifier from the native registry. - void Unregister(); - - /// - virtual void Unregister(IQuantumObject^ registry); - - /// - virtual ~Identifier(); - - /// - virtual bool Equals(IIdentifier^ other); - - /// - bool Equals(Object^ obj) override; - - /// - int GetHashCode() override; - - /// Gets the canonical text, formatted by the native side. - String^ ToCanonicalString(); - - /// - String^ ToString() override; - - /// Creates a new random identifier on the native side, without registering it. - static Identifier^ Create(); - - /// Creates a new random identifier and registers it. - static Identifier^ CreateAndRegister(); - - /// Parses the canonical text on the native side. - /// The identifier, or null if the text is malformed. - static Identifier^ Parse(String^ text); - - /// Finds a registered identifier. - /// The identifier, or null if it is not registered. - static Identifier^ Get(Guid data); - - /// - static Identifier^ Get(array^ data); - - /// - static Identifier^ Get(String^ data); - - /// - static Identifier^ Get(IIdentifier^ data); - }; -} diff --git a/Core/src/NativeInterop/Stellar.Native.Core.Wrapper.Cli/Wrapper/Identifier.cpp b/Core/src/NativeInterop/Stellar.Native.Core.Wrapper.Cli/Wrapper/Identifier.cpp deleted file mode 100644 index 752ff99..0000000 --- a/Core/src/NativeInterop/Stellar.Native.Core.Wrapper.Cli/Wrapper/Identifier.cpp +++ /dev/null @@ -1,126 +0,0 @@ -#include "Wrapper/Identifier.cli.h" -#include "Wrapper/Data/Registry/IdentifierRegistry.cli.h" -#include "Wrapper/Native/CoreContext.cli.h" - -using namespace Stellar::Kernel::Data::Registry; -using Stellar::Core::Native::NativeCall; -using Stellar::Core::Native::NativeConvert; - -namespace Stellar::Core -{ - namespace - { - IRegistry^ RegistryOf(IQuantumObject^ registry) - { - Object^ target = registry == nullptr ? Native::CoreContext::Current->Identifiers : registry; - auto typed = dynamic_cast^>(target); - - if (typed == nullptr) - throw gcnew ArgumentException(target->GetType()->Name + " cannot store identifiers", "registry"); - - return typed; - } - } - - Identifier::Identifier(Guid uid) : - _uid(uid) {} - - Guid Identifier::UID::get() - { - return _uid; - } - - bool Identifier::IsRegistered::get() - { - return Native::CoreContext::Current->Identifiers->Exists(this); - } - - void Identifier::Register() - { - Register(nullptr); - } - - void Identifier::Register(IQuantumObject^ registry) - { - RegistryOf(registry)->Register(this); - } - - void Identifier::Unregister() - { - Unregister(nullptr); - } - - void Identifier::Unregister(IQuantumObject^ registry) - { - RegistryOf(registry)->Pop(this); - } - - Identifier::~Identifier() - { - Unregister(); - } - - bool Identifier::Equals(IIdentifier^ other) - { - return other != nullptr && _uid == other->UID; - } - - bool Identifier::Equals(Object^ obj) - { - return Equals(dynamic_cast(obj)); - } - - int Identifier::GetHashCode() - { - return _uid.GetHashCode(); - } - - String^ Identifier::ToCanonicalString() - { - const nc::Identifier native = NativeConvert::ToNative(_uid); - return NativeConvert::ToManaged(NativeCall<&nc::Identifier::ToString>(native)); - } - - String^ Identifier::ToString() - { - return "Identifier#" + _uid.ToString(); - } - - Identifier^ Identifier::Create() - { - return gcnew Identifier(NativeConvert::ToManaged(nc::Identifier::Create())); - } - - Identifier^ Identifier::CreateAndRegister() - { - Identifier^ id = Create(); - id->Register(); - return id; - } - - Identifier^ Identifier::Parse(String^ text) - { - const auto parsed = nc::Identifier::Parse(NativeConvert::ToNative(text)); - return parsed.has_value() ? gcnew Identifier(NativeConvert::ToManaged(*parsed)) : nullptr; - } - - Identifier^ Identifier::Get(Guid data) - { - return Native::CoreContext::Current->Identifiers->Get(data); - } - - Identifier^ Identifier::Get(array^ data) - { - return Get(Guid(data)); - } - - Identifier^ Identifier::Get(String^ data) - { - return Get(Guid(data)); - } - - Identifier^ Identifier::Get(IIdentifier^ data) - { - return Get(data->UID); - } -} diff --git a/Core/src/NativeInterop/Stellar.Native.Core.Wrapper.Cli/Wrapper/Interop.cli.h b/Core/src/NativeInterop/Stellar.Native.Core.Wrapper.Cli/Wrapper/Interop.cli.h index bfc9bad..8765c26 100644 --- a/Core/src/NativeInterop/Stellar.Native.Core.Wrapper.Cli/Wrapper/Interop.cli.h +++ b/Core/src/NativeInterop/Stellar.Native.Core.Wrapper.Cli/Wrapper/Interop.cli.h @@ -31,23 +31,21 @@ namespace Stellar::Core::Native private ref class NativeConvert abstract sealed { public: - static nc::Identifier ToNative(Guid uid) + // The identifier of the Kernel has the layout of the native one: 16 bytes, copied as they are + static nc::Identifier ToNative(::Stellar::Kernel::Identifier id) { - pin_ptr pinned = &uid; - + pin_ptr<::Stellar::Kernel::Identifier> pinned = &id; nc::Identifier::Bytes bytes; std::memcpy(bytes.data(), pinned, bytes.size()); - return nc::Identifier(bytes); } - static Guid ToManaged(Link id) + static ::Stellar::Kernel::Identifier ToManaged(Link id) { - Guid uid; - pin_ptr pinned = &uid; - - std::memcpy(pinned, id.GetData().data(), sizeof(Guid)); - return uid; + ::Stellar::Kernel::Identifier result; + pin_ptr<::Stellar::Kernel::Identifier> pinned = &result; + std::memcpy(pinned, id.GetData().data(), id.GetData().size()); + return result; } static StellarHandle ToNative(Stellar::Kernel::Interop::NativeHandle handle) diff --git a/Core/src/NativeInterop/Stellar.Native.Core.Wrapper.Cli/Wrapper/Label.cli.h b/Core/src/NativeInterop/Stellar.Native.Core.Wrapper.Cli/Wrapper/Label.cli.h deleted file mode 100644 index 5d32ff8..0000000 --- a/Core/src/NativeInterop/Stellar.Native.Core.Wrapper.Cli/Wrapper/Label.cli.h +++ /dev/null @@ -1,99 +0,0 @@ -// StellarEngine -// Copyright (c) 2026 QuantumDevTeam -// SPDX-License-Identifier: PolyForm-Noncommercial-1.0.0 - -/// @file Wrapper/Label.cli.h -/// @brief The managed face of Stellar::Native::Core::Label. -#pragma once - -#include "Wrapper/Identifier.cli.h" - -namespace Stellar::Core -{ - using namespace System; - using namespace Stellar::Kernel; - using namespace Stellar::Kernel::Quantization; - - /// - /// A human-readable name bound to an identifier, a managed face of Stellar::Native::Core::Label. - /// - /// - /// A label is a value: two labels with the same identifier and name are equal. The registry of labels exists only - /// on the native side, which owns the names. - /// - public ref class Label sealed : ILabel, IEquatable - { - Identifier^ _uid; - String^ _name; - - Label(Identifier^ identifier, String^ name); - - internal: - static Label^ FromNative(Guid identifier, String^ name); - - public: - /// - virtual property IIdentifier^ UID { IIdentifier^ get(); } - - /// - virtual property String^ Name { String^ get(); } - - /// Registers the label in the native registry. - void Register(); - - /// - virtual void Register(IQuantumObject^ registry); - - /// Removes the label from the native registry. - void Unregister(); - - /// - virtual void Unregister(IQuantumObject^ registry); - - /// - virtual ~Label(); - - /// - virtual bool Equals(Label^ other); - - /// - bool Equals(Object^ obj) override; - - /// - int GetHashCode() override; - - /// - String^ ToString() override; - - // Overloads, not optional parameters: C++/CLI does not write default values to metadata, so C# would pass - // false for an omitted bool. Both wrappers declare exactly these four. - - /// Creates a label bound to a new identifier and registers it. - /// The label, or null if the name is blank or taken. - static Label^ Create(String^ name); - - /// Creates a label bound to an identifier and registers it. - /// The label, or null if the name is blank or taken. - static Label^ Create(String^ name, IIdentifier^ identifier); - - /// Creates a label bound to a new identifier. - /// The label, or null if the name is blank or registration found the name already taken. - static Label^ Create(String^ name, bool shouldRegister); - - /// Creates a label. - /// The human-readable name. - /// The identifier to bind the label to. A new one is created when null. - /// Whether to put the label to the registry. - /// The label, or null if the name is blank or registration found the name already taken. - static Label^ Create(String^ name, IIdentifier^ identifier, bool shouldRegister); - - /// Finds a registered label by the identifier it is bound to. - static Label^ Get(IIdentifier^ identifier); - - /// Finds a registered label by its name. - static Label^ Get(String^ name); - - /// Finds the label with this name, creating it on first use. - static operator Label^(String^ name); - }; -} diff --git a/Core/src/NativeInterop/Stellar.Native.Core.Wrapper.Cli/Wrapper/Label.cpp b/Core/src/NativeInterop/Stellar.Native.Core.Wrapper.Cli/Wrapper/Label.cpp deleted file mode 100644 index d5eb0c4..0000000 --- a/Core/src/NativeInterop/Stellar.Native.Core.Wrapper.Cli/Wrapper/Label.cpp +++ /dev/null @@ -1,130 +0,0 @@ -#include "Wrapper/Label.cli.h" -#include "Wrapper/Data/Registry/LabelRegistry.cli.h" -#include "Wrapper/Native/CoreContext.cli.h" - -using namespace Stellar::Kernel::Data::Registry; - -namespace Stellar::Core -{ - namespace - { - IRegistry^ RegistryOf(IQuantumObject^ registry) - { - Object^ target = registry == nullptr ? Native::CoreContext::Current->Labels : registry; - auto typed = dynamic_cast^>(target); - - if (typed == nullptr) - throw gcnew ArgumentException(target->GetType()->Name + " cannot store labels", "registry"); - - return typed; - } - } - - Label::Label(Identifier^ identifier, String^ name) : - _uid(identifier), - _name(name) {} - - Label^ Label::FromNative(Guid identifier, String^ name) - { - return gcnew Label(gcnew Identifier(identifier), name); - } - - IIdentifier^ Label::UID::get() - { - return _uid; - } - - String^ Label::Name::get() - { - return _name; - } - - void Label::Register() - { - Register(nullptr); - } - - void Label::Register(IQuantumObject^ registry) - { - RegistryOf(registry)->Register(this); - } - - void Label::Unregister() - { - Unregister(nullptr); - } - - void Label::Unregister(IQuantumObject^ registry) - { - RegistryOf(registry)->Pop(_uid); - } - - Label::~Label() - { - Unregister(); - } - - bool Label::Equals(Label^ other) - { - return other != nullptr && _uid->UID == other->_uid->UID && _name == other->_name; - } - - bool Label::Equals(Object^ obj) - { - return Equals(dynamic_cast(obj)); - } - - int Label::GetHashCode() - { - return HashCode::Combine(_uid->UID, _name); - } - - String^ Label::ToString() - { - return "Label#" + _name; - } - - Label^ Label::Create(String^ name) - { - return Create(name, nullptr, true); - } - - Label^ Label::Create(String^ name, IIdentifier^ identifier) - { - return Create(name, identifier, true); - } - - Label^ Label::Create(String^ name, bool shouldRegister) - { - return Create(name, nullptr, shouldRegister); - } - - Label^ Label::Create(String^ name, IIdentifier^ identifier, bool shouldRegister) - { - if (String::IsNullOrWhiteSpace(name)) - return nullptr; - - auto label = gcnew Label(identifier == nullptr ? Identifier::Create() : gcnew Identifier(identifier->UID), name); - - if (shouldRegister && !Native::CoreContext::Current->Labels->Register(label)) - return nullptr; - - return label; - } - - Label^ Label::Get(IIdentifier^ identifier) - { - return Native::CoreContext::Current->Labels->Get(identifier); - } - - Label^ Label::Get(String^ name) - { - return Native::CoreContext::Current->Labels->GetByName(name); - } - - Label::operator Label^(String^ name) - { - Label^ existing = Get(name); - return existing != nullptr ? existing : Create(name, nullptr, true); - } -} diff --git a/Core/src/NativeInterop/Stellar.Native.Core.Wrapper.Cli/Wrapper/Native/CoreContext.cli.h b/Core/src/NativeInterop/Stellar.Native.Core.Wrapper.Cli/Wrapper/Native/CoreContext.cli.h index 677d9c5..7f82e97 100644 --- a/Core/src/NativeInterop/Stellar.Native.Core.Wrapper.Cli/Wrapper/Native/CoreContext.cli.h +++ b/Core/src/NativeInterop/Stellar.Native.Core.Wrapper.Cli/Wrapper/Native/CoreContext.cli.h @@ -8,8 +8,6 @@ namespace Stellar::Core::Data::Registry { - ref class IdentifierRegistry; - ref class LabelRegistry; ref class ContainerRegistry; } @@ -40,8 +38,6 @@ namespace Stellar::Core::Native nc::CoreContext* _native; bool _owned; - Data::Registry::IdentifierRegistry^ _identifiers; - Data::Registry::LabelRegistry^ _labels; Data::Registry::ContainerRegistry^ _containers; ::Stellar::Core::Modules::ModuleRegistry^ _modules; @@ -75,10 +71,8 @@ namespace Stellar::Core::Native property bool IsDisposed { bool get() { return _native == nullptr; } } /// Gets the registry of identifiers. - property Data::Registry::IdentifierRegistry^ Identifiers { Data::Registry::IdentifierRegistry^ get(); } /// Gets the registry of labels. - property Data::Registry::LabelRegistry^ Labels { Data::Registry::LabelRegistry^ get(); } /// Gets the registry of the membership of containers. property Data::Registry::ContainerRegistry^ Containers { Data::Registry::ContainerRegistry^ get(); } diff --git a/Core/src/NativeInterop/Stellar.Native.Core.Wrapper.Cli/Wrapper/Native/CoreContext.cpp b/Core/src/NativeInterop/Stellar.Native.Core.Wrapper.Cli/Wrapper/Native/CoreContext.cpp index f826cbb..b5322f9 100644 --- a/Core/src/NativeInterop/Stellar.Native.Core.Wrapper.Cli/Wrapper/Native/CoreContext.cpp +++ b/Core/src/NativeInterop/Stellar.Native.Core.Wrapper.Cli/Wrapper/Native/CoreContext.cpp @@ -1,6 +1,4 @@ #include "Wrapper/Native/CoreContext.cli.h" -#include "Wrapper/Data/Registry/IdentifierRegistry.cli.h" -#include "Wrapper/Data/Registry/LabelRegistry.cli.h" #include "Wrapper/Data/Registry/ContainerRegistry.cli.h" #include "Wrapper/Modules/ModuleRegistry.cli.h" @@ -13,8 +11,6 @@ namespace Stellar::Core::Native _native(native), _owned(owned) { - _identifiers = gcnew Data::Registry::IdentifierRegistry(this); - _labels = gcnew Data::Registry::LabelRegistry(this); _containers = gcnew Data::Registry::ContainerRegistry(this); _modules = gcnew ::Stellar::Core::Modules::ModuleRegistry(this); } @@ -68,9 +64,7 @@ namespace Stellar::Core::Native return true; } - Data::Registry::IdentifierRegistry^ CoreContext::Identifiers::get() { return _identifiers; } - Data::Registry::LabelRegistry^ CoreContext::Labels::get() { return _labels; } Data::Registry::ContainerRegistry^ CoreContext::Containers::get() { return _containers; } diff --git a/Core/src/NativeInterop/Stellar.Native.Core.Wrapper.Cli/Wrapper/Native/NativeCore.cpp b/Core/src/NativeInterop/Stellar.Native.Core.Wrapper.Cli/Wrapper/Native/NativeCore.cpp index fda4c70..fe5414e 100644 --- a/Core/src/NativeInterop/Stellar.Native.Core.Wrapper.Cli/Wrapper/Native/NativeCore.cpp +++ b/Core/src/NativeInterop/Stellar.Native.Core.Wrapper.Cli/Wrapper/Native/NativeCore.cpp @@ -18,6 +18,6 @@ namespace Stellar::Core::Native void NativeCore::EnsureAvailable() { // Linked at load time: reaching here means Stellar.Native.Core.dll was found. Touch it to be sure. - (void)nc::CoreContext::Default().Identifiers().size(); + (void)nc::CoreContext::Default().Modules(); } } diff --git a/Core/src/NativeInterop/Stellar.Native.Core.Wrapper.Managed/Data/Registry/ContainerRegistry.cs b/Core/src/NativeInterop/Stellar.Native.Core.Wrapper.Managed/Data/Registry/ContainerRegistry.cs index 372406e..3d53cc3 100644 --- a/Core/src/NativeInterop/Stellar.Native.Core.Wrapper.Managed/Data/Registry/ContainerRegistry.cs +++ b/Core/src/NativeInterop/Stellar.Native.Core.Wrapper.Managed/Data/Registry/ContainerRegistry.cs @@ -1,3 +1,4 @@ +using Stellar.Kernel; using Stellar.Core.Native; namespace Stellar.Core.Data.Registry; @@ -16,55 +17,55 @@ internal ContainerRegistry(CoreContext context) } /// Creates a container. False if it exists already. - public bool Create(Guid container) + public bool Create(Identifier container) { int created; return Exports.Ask(Exports.stellar_container_create(_context.Handle, &container, &created), created); } /// Destroys a container. False if it does not exist. - public bool Destroy(Guid container) + public bool Destroy(Identifier container) { int destroyed; return Exports.Ask(Exports.stellar_container_destroy(_context.Handle, &container, &destroyed), destroyed); } /// Checks for a container. - public bool Exists(Guid container) + public bool Exists(Identifier container) { int exists; return Exports.Ask(Exports.stellar_container_exists(_context.Handle, &container, &exists), exists); } /// Seals a container: it cannot change any more. - public void Seal(Guid container) + public void Seal(Identifier container) { Exports.Check(Exports.stellar_container_seal(_context.Handle, &container)); } /// Checks whether a container is sealed. - public bool IsSealed(Guid container) + public bool IsSealed(Identifier container) { int isSealed; return Exports.Ask(Exports.stellar_container_is_sealed(_context.Handle, &container, &isSealed), isSealed); } /// Adds an item. False if it is there already. - public bool Add(Guid container, Guid item) + public bool Add(Identifier container, Identifier item) { int added; return Exports.Ask(Exports.stellar_container_add(_context.Handle, &container, &item, &added), added); } /// Removes an item. False if it is not there. - public bool Remove(Guid container, Guid item) + public bool Remove(Identifier container, Identifier item) { int removed; return Exports.Ask(Exports.stellar_container_remove(_context.Handle, &container, &item, &removed), removed); } /// Checks for an item. - public bool Contains(Guid container, Guid item) + public bool Contains(Identifier container, Identifier item) { int contained; return Exports.Ask(Exports.stellar_container_contains(_context.Handle, &container, &item, &contained), @@ -72,7 +73,7 @@ public bool Contains(Guid container, Guid item) } /// Gets the number of items. - public int Count(Guid container) + public int Count(Identifier container) { nuint count; Exports.Check(Exports.stellar_container_count(_context.Handle, &container, &count)); @@ -80,7 +81,7 @@ public int Count(Guid container) } /// Gets the items. - public Guid[] Items(Guid container) + public Identifier[] Items(Identifier container) { var context = _context.Handle; return Exports.ReadIdentifiers((buffer, capacity, required) => @@ -91,21 +92,21 @@ public Guid[] Items(Guid container) } /// Removes every item. False if the container does not exist. - public bool Clear(Guid container) + public bool Clear(Identifier container) { int cleared; return Exports.Ask(Exports.stellar_container_clear(_context.Handle, &container, &cleared), cleared); } /// Adds a branch. False if it is there already. - public bool AddBranch(Guid container, Guid branch) + public bool AddBranch(Identifier container, Identifier branch) { int added; return Exports.Ask(Exports.stellar_container_add_branch(_context.Handle, &container, &branch, &added), added); } /// Removes a branch. False if it is not there. - public bool RemoveBranch(Guid container, Guid branch) + public bool RemoveBranch(Identifier container, Identifier branch) { int removed; return Exports.Ask(Exports.stellar_container_remove_branch(_context.Handle, &container, &branch, &removed), @@ -113,7 +114,7 @@ public bool RemoveBranch(Guid container, Guid branch) } /// Checks for a branch. - public bool ContainsBranch(Guid container, Guid branch) + public bool ContainsBranch(Identifier container, Identifier branch) { int contained; return Exports.Ask(Exports.stellar_container_contains_branch(_context.Handle, &container, &branch, &contained), @@ -121,7 +122,7 @@ public bool ContainsBranch(Guid container, Guid branch) } /// Gets the branches. - public Guid[] Branches(Guid container) + public Identifier[] Branches(Identifier container) { var context = _context.Handle; return Exports.ReadIdentifiers((buffer, capacity, required) => diff --git a/Core/src/NativeInterop/Stellar.Native.Core.Wrapper.Managed/Data/Registry/IdentifierRegistry.cs b/Core/src/NativeInterop/Stellar.Native.Core.Wrapper.Managed/Data/Registry/IdentifierRegistry.cs deleted file mode 100644 index bd7f624..0000000 --- a/Core/src/NativeInterop/Stellar.Native.Core.Wrapper.Managed/Data/Registry/IdentifierRegistry.cs +++ /dev/null @@ -1,96 +0,0 @@ -using Stellar.Core.Native; -using Stellar.Kernel; -using Stellar.Kernel.Data.Registry; - -namespace Stellar.Core.Data.Registry; - -/// -/// The registry of identifiers of a . It holds no state: it is a view of the native registry. -/// -public sealed unsafe class IdentifierRegistry - : IRegistry -{ - private readonly CoreContext _context; - - internal IdentifierRegistry(CoreContext context) - { - _context = context; - } - - /// - public bool Exists(IIdentifier id) - { - return id is not null && Contains(id.UID); - } - - /// - public bool Register(Identifier obj) - { - ArgumentNullException.ThrowIfNull(obj); - - var uid = obj.UID; - int added; - return Exports.Ask(Exports.stellar_identifier_register(_context.Handle, &uid, &added), added); - } - - /// - public Identifier? Get(IIdentifier id) - { - return id is null ? null : Get(id.UID); - } - - /// - /// Gets a registered identifier by value. - /// - /// The value. - /// The identifier, or null if it is not registered. - public Identifier? Get(Guid uid) - { - return Contains(uid) ? new Identifier(uid) : null; - } - - /// - public Identifier? Pop(IIdentifier id) - { - if (id is null) return null; - - var uid = id.UID; - int removed; - return Exports.Ask(Exports.stellar_identifier_unregister(_context.Handle, &uid, &removed), removed) - ? new Identifier(uid) - : null; - } - - /// - public int Size - { - get - { - nuint count; - Exports.Check(Exports.stellar_identifier_count(_context.Handle, &count)); - return (int)count; - } - } - - /// - public ICollection Keys => Values.Cast().ToArray(); - - /// - public ICollection Values - { - get - { - var context = _context.Handle; - return Exports.ReadIdentifiers((buffer, capacity, required) => - Exports.stellar_identifier_snapshot(context, buffer, capacity, required)) - .Select(uid => new Identifier(uid)) - .ToArray(); - } - } - - private bool Contains(Guid uid) - { - int contained; - return Exports.Ask(Exports.stellar_identifier_contains(_context.Handle, &uid, &contained), contained); - } -} diff --git a/Core/src/NativeInterop/Stellar.Native.Core.Wrapper.Managed/Data/Registry/LabelRegistry.cs b/Core/src/NativeInterop/Stellar.Native.Core.Wrapper.Managed/Data/Registry/LabelRegistry.cs deleted file mode 100644 index bde572d..0000000 --- a/Core/src/NativeInterop/Stellar.Native.Core.Wrapper.Managed/Data/Registry/LabelRegistry.cs +++ /dev/null @@ -1,127 +0,0 @@ -using System.Text; -using Stellar.Core.Native; -using Stellar.Kernel; -using Stellar.Kernel.Data.Registry; -using Stellar.Kernel.Interop; - -namespace Stellar.Core.Data.Registry; - -/// -/// The registry of labels of a : names are unique within it. It holds no state: it is a -/// view of the native registry. -/// -public sealed unsafe class LabelRegistry - : IRegistry