### Add VYaml Package Source: https://github.com/hadashia/vyaml/blob/master/README.md Install the VYaml package using the .NET CLI. ```bash dotnet add package VYaml ``` -------------------------------- ### Exception Handling Example Source: https://github.com/hadashia/vyaml/blob/master/_autodocs/errors.md An example demonstrating how to catch and handle YamlSerializerException during deserialization. ```APIDOC ### Exception Handling ```csharp try { var yaml = Encoding.UTF8.GetBytes("value: not-a-number"); var num = YamlSerializer.Deserialize(yaml); } catch (YamlSerializerException ex) { // ex.Message: "Cannot detect a scalar value of System.Int32, not-a-number" Console.WriteLine(ex.Message); } ``` ``` -------------------------------- ### Example: Single Constructor with YamlObject Source: https://github.com/hadashia/vyaml/blob/master/_autodocs/annotations.md Shows a class with a single constructor that is automatically selected for deserialization when using YamlObject. ```csharp [YamlObject] public partial class Point { public int X { get; set; } public int Y { get; set; } // Single constructor: automatically selected public Point(int x, int y) { X = x; Y = y; } } // Deserialization: // x: 10 // y: 20 // Produces: new Point(10, 20) ``` -------------------------------- ### YamlParser Usage Source: https://github.com/hadashia/vyaml/blob/master/_autodocs/parser-api.md Example demonstrating how to parse YAML content from bytes, iterate through events, and extract scalar values. ```APIDOC ## Usage Example ### Description This example demonstrates how to parse YAML content from bytes, iterate through parsing events, and extract scalar values. ### Code ```csharp var yaml = Encoding.UTF8.GetBytes(@" name: Alice age: 30 items: - apple - banana "); var parser = YamlParser.FromBytes(yaml); parser.SkipHeader(); while (parser.Read()) { switch (parser.CurrentEventType) { case ParseEventType.Scalar: Console.WriteLine($"Scalar: {parser.GetScalarAsString()}"); break; case ParseEventType.SequenceStart: Console.WriteLine("Sequence starts"); break; case ParseEventType.MappingStart: Console.WriteLine("Mapping starts"); break; case ParseEventType.StreamEnd: goto End; } } End: parser.ReturnPool(); ``` ``` -------------------------------- ### Example Usage of YamlIgnore Attribute Source: https://github.com/hadashia/vyaml/blob/master/_autodocs/annotations.md Demonstrates how to apply YamlIgnoreAttribute to exclude specific properties from being serialized into YAML. ```csharp [YamlObject] public partial class User { public string Name { get; set; } public int Id { get; set; } [YamlIgnore] public DateTime CreatedAt { get; set; } [YamlIgnore] public string PasswordHash { get; set; } } // YAML output (CreatedAt and PasswordHash are omitted): // name: Alice // id: 1 ``` -------------------------------- ### Add VYaml Unity Package Source: https://github.com/hadashia/vyaml/blob/master/README.md Install the VYaml package for Unity using a Git URL in the Package Manager. ```bash https://github.com/hadashiA/VYaml.git?path=VYaml.Unity/Assets/VYaml#1.4.0 ``` -------------------------------- ### Anchor Class Example Source: https://github.com/hadashia/vyaml/blob/master/_autodocs/types.md Illustrates creating Anchor objects and comparing them for equality. Demonstrates that equality is determined solely by the ID, not the name. ```csharp var anchor1 = new Anchor("first", 0); var anchor2 = new Anchor("first", 0); anchor1.Equals(anchor2); // true (same ID) var anchor3 = new Anchor("second", 1); anchor1.Equals(anchor3); // false (different ID) ``` -------------------------------- ### Custom Composite Resolver Setup Source: https://github.com/hadashia/vyaml/blob/master/_autodocs/options-and-configuration.md Create a composite resolver by combining custom formatters with existing resolvers like StandardResolver.Instance. ```csharp var options = new YamlSerializerOptions { Resolver = CompositeResolver.Create( new IYamlFormatter[] { new MyCustomFormatter(), }, new IYamlFormatterResolver[] { StandardResolver.Instance, }) }; ``` -------------------------------- ### Using StandardResolver for Serialization Source: https://github.com/hadashia/vyaml/blob/master/_autodocs/resolvers.md Example of using the default resolver implicitly or explicitly with YamlSerializer.Serialize. ```csharp // Using default resolver (implicit) var yaml = YamlSerializer.Serialize(new MyType()); // Or explicitly: var options = new YamlSerializerOptions { Resolver = StandardResolver.Instance }; YamlSerializer.Serialize(myObject, options); ``` -------------------------------- ### GeneratedResolver Usage Example Source: https://github.com/hadashia/vyaml/blob/master/_autodocs/resolvers.md Shows how to define a user type with [YamlObject] and 'partial', and how the GeneratedResolver automatically handles its serialization. ```csharp [YamlObject] // Required public partial class User // Must be partial { public string Name { get; set; } public int Age { get; set; } } // At compile time, source generator creates: // partial class User // { // private static class YamlFormatter // { // public static IYamlFormatter Create() { ... } // } // } // GeneratedResolver finds and uses this formatter var user = new User { Name = "Alice", Age = 30 }; YamlSerializer.Serialize(user); // Uses GeneratedResolver ``` -------------------------------- ### Tag Class Example Source: https://github.com/hadashia/vyaml/blob/master/_autodocs/types.md Demonstrates instantiation and property access for the Tag class. Shows how to create a tag and retrieve its handle, suffix, and full string representation. ```csharp var tag = new Tag("!"."str"); tag.Handle; // "!" tag.Suffix; // "str" tag.ToString(); // "!str" ``` -------------------------------- ### BeginSequence Source: https://github.com/hadashia/vyaml/blob/master/_autodocs/emitter-api.md Starts a YAML sequence, which can be formatted in either block style (using '-' markers) or flow style (using '[ ]'). ```APIDOC ## BeginSequence ### Description Starts a YAML sequence (list/array). Block style writes with `-` markers; flow style uses `[ ]`. ### Signature ```csharp public void BeginSequence(SequenceStyle style = SequenceStyle.Block) ``` ### Parameters #### Path Parameters (None) #### Query Parameters (None) #### Request Body (None) ### Parameters - **style** (`SequenceStyle`) - Optional - `Block` for `-` notation or `Flow` for inline `[ ]` ### Throws - `YamlEmitterException` — If the current state does not permit starting a sequence (e.g., inside a mapping key) ### Request Example - Block Sequence ```csharp var buffer = new ArrayBufferWriter(); var emitter = new Utf8YamlEmitter(buffer); emitter.BeginSequence(SequenceStyle.Block); { emitter.WriteString("apple"); emitter.WriteString("banana"); } emitter.EndSequence(); // Output: // - apple // - banana ``` ### Request Example - Flow Sequence ```csharp emitter.BeginSequence(SequenceStyle.Flow); { emitter.WriteInt32(1); emitter.WriteInt32(2); emitter.WriteInt32(3); } emitter.EndSequence(); // Output: [1, 2, 3] ``` ### Response (None) ``` -------------------------------- ### Example: Mixed Constructor and Setter with YAML Deserialization Source: https://github.com/hadashia/vyaml/blob/master/_autodocs/annotations.md Demonstrates deserializing YAML into an object with properties initialized via constructor and others set via setters. ```csharp [YamlObject] public partial class Person { public int Age { get; } // from constructor public string Name { get; } // from constructor public string Bio { get; set; } // from setter public Person(int age, string name) { Age = age; Name = name; } } // Deserialization from YAML: // age: 30 // name: Alice // bio: "Software engineer" // Produces: new Person(30, "Alice") { Bio = "Software engineer" } ``` -------------------------------- ### Example Usage of TryGetCurrentTag Source: https://github.com/hadashia/vyaml/blob/master/_autodocs/parser-api.md Demonstrates how to check for and use an explicit YAML tag retrieved from the parser. If a tag is found, its handle and suffix can be accessed. ```csharp if (parser.TryGetCurrentTag(out var tag)) { // tag.Handle: "!" // tag.Suffix: "custom" } ``` -------------------------------- ### WriteAnchor Method Source: https://github.com/hadashia/vyaml/blob/master/_autodocs/emitter-api.md Internal method used to write a YAML anchor. Example: `&name`. ```csharp internal void WriteAnchor(string anchor) ``` -------------------------------- ### Ordering Example Source: https://github.com/hadashia/vyaml/blob/master/_autodocs/annotations.md Illustrates using YamlMemberAttribute with the 'Order' property to control the sequence of properties in the generated YAML output. Lower values appear first. ```csharp [YamlObject] public partial class Person { [YamlMember(Order = 1)] public string Name { get; set; } [YamlMember(Order = 0)] public int Id { get; set; } [YamlMember(Order = 2)] public string Email { get; set; } } ``` -------------------------------- ### Comprehensive YAML Emission Example Source: https://github.com/hadashia/vyaml/blob/master/_autodocs/emitter-api.md Demonstrates how to use the Utf8YamlEmitter to construct a YAML document with nested mappings, sequences, and various scalar types. Ensure necessary using directives are included. ```csharp using VYaml.Emitter; using System.Buffers; using System.Text; var buffer = new ArrayBufferWriter(); var options = new YamlEmitOptions { IndentWidth = 2 }; var emitter = new Utf8YamlEmitter(buffer, options); // Top-level mapping emitter.BeginMapping(); { // Simple scalar pair emitter.WriteString("name"); emitter.WriteString("Alice"); // Sequence value emitter.WriteString("items"); emitter.BeginSequence(); { emitter.WriteString("apple"); emitter.WriteString("banana"); emitter.WriteInt32(42); } emitter.EndSequence(); // Nested mapping emitter.WriteString("metadata"); emitter.BeginMapping(); { emitter.WriteString("version"); emitter.WriteInt32(1); emitter.WriteString("active"); emitter.WriteBool(true); } emitter.EndMapping(); } emitter.EndMapping(); // Extract result var yaml = Encoding.UTF8.GetString(buffer.WrittenSpan); Console.WriteLine(yaml); ``` -------------------------------- ### Custom Name Example Source: https://github.com/hadashia/vyaml/blob/master/_autodocs/annotations.md Demonstrates using YamlMemberAttribute to specify custom names for YAML keys. If 'name' is null, a naming convention is applied. ```csharp [YamlObject] public partial class Config { [YamlMember("database-url")] public string DatabaseUrl { get; set; } [YamlMember("api-key")] public string ApiKey { get; set; } } ``` -------------------------------- ### Example: Multiple Constructors with YamlConstructor Annotation Source: https://github.com/hadashia/vyaml/blob/master/_autodocs/annotations.md Illustrates using YamlConstructorAttribute to specify which constructor to use for deserialization when a class has multiple constructors. ```csharp [YamlObject] public partial class Config { public string Name { get; set; } public string Value { get; set; } public Config() { } // This constructor will be used for deserialization [YamlConstructor] public Config(string name, string value) { Name = name; Value = value; } } ``` -------------------------------- ### Emitting Sequences and Nested Structures Source: https://github.com/hadashia/vyaml/blob/master/README.md Provides an example of emitting complex YAML structures including nested sequences and mappings. ```APIDOC ## Emitting Sequences and Nested Structures ### Description This example demonstrates how to emit more complex YAML structures, including nested sequences (both block and flow style) and mappings, showcasing the emitter's capability to handle intricate data. ### Method `emitter.BeginSequence()` `emitter.EndSequence()` `emitter.BeginMapping()` `emitter.EndMapping()` `emitter.BeginSequence(SequenceStyle style)` ### Endpoint N/A (In-memory operation) ### Parameters - **style** (SequenceStyle, optional) - Specifies the style for a sequence (e.g., `Flow`). ### Request Example ```csharp emitter.BeginSequence(); { emitter.BeginSequence(SequenceStyle.Flow); { emitter.WriteInt32(100); emitter.WriteString("&hoge"); emitter.WriteString("bra"); } emitter.EndSequence(); emitter.BeginMapping(); { emitter.WriteString("key1"); emitter.WriteString("item1"); emitter.WriteString("key2"); emitter.BeginSequence(); { emitter.WriteString("nested-item1") emitter.WriteString("nested-item2") emitter.BeginMapping(); { emitter.WriteString("nested-key1") emitter.WriteInt32(100) } emitter.EndMapping(); } emitter.EndSequence(); } emitter.EndMapping(); } emitter.EndSequence(); ``` ### Response #### Success Response (YAML Output) ```yaml - [100, "&hoge", bra] - key1: item1 key2: - nested-item1 - nested-item2 - nested-key1: 100 ``` ``` -------------------------------- ### Catching YamlEmitterException Source: https://github.com/hadashia/vyaml/blob/master/_autodocs/errors.md Demonstrates how to catch a YamlEmitterException during YAML emission. This example attempts an invalid operation (starting a block sequence in a flow sequence) which triggers the exception. ```csharp try { var buffer = new ArrayBufferWriter(); var emitter = new Utf8YamlEmitter(buffer); // Try to start block sequence in flow sequence context emitter.BeginSequence(SequenceStyle.Flow); emitter.BeginSequence(SequenceStyle.Block); // Error! } catch (YamlEmitterException ex) { // ex.Message: "To start block-sequence in the flow-sequence is not supported." Console.WriteLine(ex.Message); } ``` -------------------------------- ### WriteTag Method Source: https://github.com/hadashia/vyaml/blob/master/_autodocs/emitter-api.md Internal method used to write a YAML tag. Example: `!custom`. ```csharp internal void WriteTag(string tag) ``` -------------------------------- ### YAML Parsing Error Handling Source: https://github.com/hadashia/vyaml/blob/master/_autodocs/types.md Example of how to catch and report `YamlParserException` during parsing, showing the error location. ```csharp try { var parser = YamlParser.FromBytes(invalidYaml); while (parser.Read()) { } } catch (YamlParserException ex) { Console.WriteLine($"Error at {ex.Message}"); // Output: "Error at Line: 3, Col: 5, Idx: 42" } ``` -------------------------------- ### BuiltinResolver Usage Example Source: https://github.com/hadashia/vyaml/blob/master/_autodocs/resolvers.md Demonstrates how the BuiltinResolver is automatically used by YamlSerializer for common .NET types like arrays and dictionaries. ```csharp // Automatically resolved var numbers = new[] { 1, 2, 3 }; YamlSerializer.Serialize(numbers); // Uses BuiltinResolver var dict = new Dictionary { ["a"] = 1 }; YamlSerializer.Serialize(dict); // Uses BuiltinResolver ``` -------------------------------- ### Begin and End YAML Mapping (Block Style) Source: https://github.com/hadashia/vyaml/blob/master/_autodocs/emitter-api.md Starts and ends a YAML mapping using block style, which uses indented key-value pairs separated by ': '. Ensure EndMapping is called after BeginMapping. ```csharp emitter.BeginMapping(MappingStyle.Block); { emitter.WriteString("name"); emitter.WriteString("Alice"); emitter.WriteString("age"); emitter.WriteInt32(30); } emitter.EndMapping(); ``` -------------------------------- ### Begin and End YAML Mapping (Flow Style) Source: https://github.com/hadashia/vyaml/blob/master/_autodocs/emitter-api.md Starts and ends a YAML mapping using flow style, which uses inline key-value pairs enclosed in curly braces '{}'. Ensure EndMapping is called after BeginMapping. ```csharp emitter.BeginMapping(MappingStyle.Flow); { emitter.WriteString("x"); emitter.WriteInt32(10); emitter.WriteString("y"); emitter.WriteInt32(20); } emitter.EndMapping(); ``` -------------------------------- ### Custom IYamlFormatter Implementation Source: https://github.com/hadashia/vyaml/blob/master/_autodocs/resolvers.md Example of implementing IYamlFormatter for a custom type 'MyType'. It defines how to serialize and deserialize 'MyType' by explicitly handling its fields. ```csharp public class MyTypeFormatter : IYamlFormatter { public void Serialize( ref Utf8YamlEmitter emitter, MyType value, YamlSerializationContext context) { emitter.BeginMapping(); emitter.WriteString("customField"); emitter.WriteString(value.CustomField); emitter.EndMapping(); } public MyType Deserialize( ref YamlParser parser, YamlDeserializationContext context) { parser.ReadWithVerify(ParseEventType.MappingStart); var key = parser.ReadScalarAsString(); parser.Read(); var value = parser.GetScalarAsString(); parser.ReadWithVerify(ParseEventType.MappingEnd); return new MyType { CustomField = value }; } } ``` -------------------------------- ### Begin and End Flow Sequence Source: https://github.com/hadashia/vyaml/blob/master/_autodocs/emitter-api.md Starts and ends a YAML sequence using flow style, enclosed in square brackets. Ensure EndSequence is called after BeginSequence. ```csharp emitter.BeginSequence(SequenceStyle.Flow); { emitter.WriteInt32(1); emitter.WriteInt32(2); emitter.WriteInt32(3); } emitter.EndSequence(); ``` -------------------------------- ### Begin and End Block Sequence Source: https://github.com/hadashia/vyaml/blob/master/_autodocs/emitter-api.md Starts and ends a YAML sequence using block style, indicated by '-' markers. Ensure EndSequence is called after BeginSequence. ```csharp var buffer = new ArrayBufferWriter(); var emitter = new Utf8YamlEmitter(buffer); emitter.BeginSequence(SequenceStyle.Block); { emitter.WriteString("apple"); emitter.WriteString("banana"); } emitter.EndSequence(); ``` -------------------------------- ### Set Naming Convention for YAML Serialization Source: https://github.com/hadashia/vyaml/blob/master/_autodocs/options-and-configuration.md Configure the property naming convention for YAML serialization. This example demonstrates setting the convention to SnakeCase and serializing an object, showing the resulting YAML output. ```csharp var options = YamlSerializerOptions.Standard; options.NamingConvention = NamingConvention.SnakeCase; YamlSerializer.Serialize(new { FooBar = 123 }, options); // Outputs: "foo_bar: 123" ``` -------------------------------- ### Serialize Object to YAML String Source: https://github.com/hadashia/vyaml/blob/master/_autodocs/quick-start.md Use `YamlSerializer.SerializeToString` for a convenient way to get the YAML output as a string, suitable for display or logging. ```csharp var yamlString = YamlSerializer.SerializeToString(person); Console.WriteLine(yamlString); // Output: // name: Alice // age: 30 ``` -------------------------------- ### YamlDeserializationContext.Options Property Source: https://github.com/hadashia/vyaml/blob/master/_autodocs/deserialization-context.md Gets or sets the serialization options used during deserialization. These options control aspects like the naming convention and formatter resolver. ```APIDOC ## Properties ### Options ```csharp public YamlSerializerOptions Options { get; set; } ``` Gets or sets the serialization options used during deserialization. **Type:** `YamlSerializerOptions` ``` -------------------------------- ### Polymorphic Deserialization Example Source: https://github.com/hadashia/vyaml/blob/master/_autodocs/annotations.md Demonstrates how to use YamlObjectUnion attributes to enable polymorphic deserialization for an interface. It shows defining unions for Dog and Cat types, serializing an interface instance, and deserializing it back into the correct concrete type. ```csharp [YamlObject] [YamlObjectUnion("!dog", typeof(Dog))] [YamlObjectUnion("!cat", typeof(Cat))] public partial interface IAnimal { string Name { get; set; } } [YamlObject] public partial class Dog : IAnimal { public string Name { get; set; } public string Breed { get; set; } } [YamlObject] public partial class Cat : IAnimal { public string Name { get; set; } public bool IsIndoor { get; set; } } // Serialization of interface type: var dog = (IAnimal)new Dog { Name = "Fido", Breed = "Labrador" }; var yaml = YamlSerializer.Serialize(dog); // Output: // !dog // name: Fido // breed: Labrador // Deserialization: var animal = YamlSerializer.Deserialize(utf8Bytes); // Returns: Dog instance if YAML starts with !dog, Cat if !cat ``` -------------------------------- ### Configure Unity Type Support Source: https://github.com/hadashia/vyaml/blob/master/README.md To enable support for Unity types, install the Unity package and add UnityResolver to YamlSerializerOptions. This allows serialization and deserialization of Unity-specific data structures. ```csharp YamlSerializer.DefaultOptions = new YamlSerializerOptions { Resolver = CompositeResolver.Create(new IYamlFormatterResolver[] { StandardResolver.Instance, UnityResolver.Instance, }) }; ``` -------------------------------- ### Custom Point Formatter Using Serialization Context Source: https://github.com/hadashia/vyaml/blob/master/_autodocs/serialization-context.md Implement a custom IYamlFormatter to serialize a Point object. This example demonstrates using the YamlSerializationContext to access serialization options, specifically the naming convention, to transform property names before writing them. ```csharp public class PointFormatter : IYamlFormatter { public void Serialize( ref Utf8YamlEmitter emitter, Point value, YamlSerializationContext context) { var convention = context.Options.NamingConvention; emitter.BeginMapping(); // Transform property names according to convention var xKey = NamingConventionMutator.Mutate("X", convention); var yKey = NamingConventionMutator.Mutate("Y", convention); emitter.WriteString(xKey); emitter.WriteInt32(value.X); emitter.WriteString(yKey); emitter.WriteInt32(value.Y); emitter.EndMapping(); } public Point Deserialize(ref YamlParser parser, YamlDeserializationContext context) { // Implement deserialization... throw new NotImplementedException(); } } // If registered and used: // Point(10, 20) serialized with SnakeCase → "x: 10\ny: 20" // Point(10, 20) serialized with KebabCase → "x: 10\ny: 20" (X/Y have no transformation) ``` -------------------------------- ### Get Scalar as UTF-8 Bytes - C# Source: https://github.com/hadashia/vyaml/blob/master/_autodocs/parser-api.md Gets the current scalar value as UTF-8 encoded bytes without allocating new memory. This is useful for performance-sensitive scenarios. ```csharp public readonly ReadOnlySpan GetScalarAsUtf8() ``` -------------------------------- ### YamlDeserializationContext Options Property Source: https://github.com/hadashia/vyaml/blob/master/_autodocs/deserialization-context.md Gets or sets the serialization options used during deserialization. This property is of type YamlSerializerOptions. ```csharp public YamlSerializerOptions Options { get; set; } ``` -------------------------------- ### Basic YAML Mapping Emission in C# Source: https://github.com/hadashia/vyaml/blob/master/README.md Demonstrates the basic usage of Utf8YamlEmitter to write a simple YAML mapping with string, integer, and float values. Ensure the buffer implements IBufferWriter. ```csharp var buffer = new ArrayBufferWriter(); var emitter = new Utf8YamlEmitter(buffer); // It needs buffer implemented `IBufferWriter` emitter.BeginMapping(); // Mapping is a collection like Dictionary in YAML { emitter.WriteString("key1"); emitter.WriteString("value-1"); emitter.WriteString("key2"); emitter.WriteInt32(222); emitter.WriteString("key3"); emitter.WriteFloat(3.333f); } emitter.EndMapping(); ``` ```csharp // If you want to expand a string in memory, you can do this. System.Text.Encoding.UTF8.GetString(buffer.WrittenSpan); ``` ```yaml key1: value-1 key2: 222 key3: 3.333 ``` -------------------------------- ### GetScalarAsUtf8 Source: https://github.com/hadashia/vyaml/blob/master/_autodocs/parser-api.md Gets the current scalar as UTF-8 bytes without allocation. Returns a ReadOnlySpan representing the UTF-8 bytes. ```APIDOC ## GetScalarAsUtf8 ### Description Gets the current scalar as UTF-8 bytes without allocation. ### Method ```csharp public readonly ReadOnlySpan GetScalarAsUtf8() ``` ### Returns `ReadOnlySpan` — UTF-8 bytes ``` -------------------------------- ### GetFormatterWithVerify Extension Method Source: https://github.com/hadashia/vyaml/blob/master/_autodocs/resolvers.md Gets a formatter and throws YamlSerializerException if not found or initialization fails. Ensures a non-null formatter is returned. ```csharp public static IYamlFormatter GetFormatterWithVerify( this IYamlFormatterResolver resolver) ``` -------------------------------- ### YamlDeserializationContext Resolver Property Source: https://github.com/hadashia/vyaml/blob/master/_autodocs/deserialization-context.md Gets or sets the formatter resolver used to locate type formatters. This property is of type IYamlFormatterResolver. ```csharp public IYamlFormatterResolver Resolver { get; set; } ``` -------------------------------- ### YamlEmitOptions Class Source: https://github.com/hadashia/vyaml/blob/master/_autodocs/emitter-api.md Configuration class for emitter behavior. Customize indentation width and string quote style. ```csharp public class YamlEmitOptions { public static readonly YamlEmitOptions Default = new(); /// Indentation width in spaces (default: 2) public int IndentWidth { get; set; } = 2; /// Quote style for strings (default: DoubleQuoted) /// Only SingleQuoted and DoubleQuoted are allowed public ScalarStyle StringQuoteStyle { get; set; } = ScalarStyle.DoubleQuoted; } ``` -------------------------------- ### Basic Usage of Utf8YamlEmitter Source: https://github.com/hadashia/vyaml/blob/master/README.md Demonstrates the fundamental steps to create a Utf8YamlEmitter and write a simple mapping to a buffer. ```APIDOC ## Basic Usage of Utf8YamlEmitter ### Description This example shows how to initialize `Utf8YamlEmitter` with an `IBufferWriter` and write a basic YAML mapping containing string, integer, and float values. ### Method `Utf8YamlEmitter` methods are called sequentially to build the YAML structure. ### Endpoint N/A (In-memory operation) ### Parameters N/A ### Request Example ```csharp var buffer = new ArrayBufferWriter(); var emitter = new Utf8YamlEmitter(buffer); emitter.BeginMapping(); { emitter.WriteString("key1"); emitter.WriteString("value-1"); emitter.WriteString("key2"); emitter.WriteInt32(222); emitter.WriteString("key3"); emitter.WriteFloat(3.333f); } emitter.EndMapping(); // To get the string representation: System.Text.Encoding.UTF8.GetString(buffer.WrittenSpan); ``` ### Response #### Success Response (YAML Output) ```yaml key1: value-1 key2: 222 key3: 3.333 ``` ``` -------------------------------- ### Standard YamlSerializerOptions Source: https://github.com/hadashia/vyaml/blob/master/_autodocs/options-and-configuration.md Use this preset for standard YAML serialization with the built-in StandardResolver and default settings. ```csharp public static YamlSerializerOptions Standard => new() { Resolver = StandardResolver.Instance } ``` -------------------------------- ### YamlDeserializationContext.Resolver Property Source: https://github.com/hadashia/vyaml/blob/master/_autodocs/deserialization-context.md Gets or sets the formatter resolver used to locate type formatters during deserialization. This allows for custom formatting logic. ```APIDOC ### Resolver ```csharp public IYamlFormatterResolver Resolver { get; set; } ``` Gets or sets the formatter resolver used to locate type formatters. **Type:** `IYamlFormatterResolver` ``` -------------------------------- ### TryGetCurrentAnchor C# Method Source: https://github.com/hadashia/vyaml/blob/master/_autodocs/parser-api.md Attempts to retrieve an anchor at the current position. Returns false if no anchor is present. The `anchor` output parameter will contain the anchor's name and ID if found. ```csharp public bool TryGetCurrentAnchor(out Anchor anchor) ``` -------------------------------- ### Access Emit Options Source: https://github.com/hadashia/vyaml/blob/master/_autodocs/serialization-context.md Retrieve emit options from the context to configure output formatting, such as indentation width and string quote style. ```csharp var emitOptions = context.Options.EmitOptions; var indentWidth = emitOptions.IndentWidth; // e.g., 2 var stringQuoteStyle = emitOptions.StringQuoteStyle; // e.g., DoubleQuoted ``` -------------------------------- ### NamingConvention Enum Source: https://github.com/hadashia/vyaml/blob/master/_autodocs/types.md Controls property name transformation for YAML keys. It supports LowerCamelCase, UpperCamelCase, SnakeCase, and KebabCase, providing examples for each transformation. ```APIDOC ## NamingConvention Enum Controls property name transformation for YAML keys. ### Values | Value | Transformation | Example | |---|---|---| | `LowerCamelCase` | camelCase | `MyProperty` → `myProperty` | | `UpperCamelCase` | PascalCase | `MyProperty` → `MyProperty` | | `SnakeCase` | snake_case | `MyProperty` → `my_property` | | `KebabCase` | kebab-case | `MyProperty` → `my-property` | ``` -------------------------------- ### Low-Level YAML Emitting Source: https://github.com/hadashia/vyaml/blob/master/_autodocs/quick-start.md Build YAML programmatically using the low-level emitter. This is useful for constructing YAML structures dynamically. ```csharp var buffer = new ArrayBufferWriter(); var emitter = new Utf8YamlEmitter(buffer); emitter.BeginMapping(); { emitter.WriteString("name"); emitter.WriteString("Alice"); emitter.WriteString("age"); emitter.WriteInt32(30); emitter.WriteString("items"); emitter.BeginSequence(); { emitter.WriteString("apple"); emitter.WriteString("banana"); } emitter.EndSequence(); } emitter.EndMapping(); var yaml = Encoding.UTF8.GetString(buffer.WrittenSpan); Console.WriteLine(yaml); ``` -------------------------------- ### YAML with Anchors and Aliases Source: https://github.com/hadashia/vyaml/blob/master/_autodocs/deserialization-context.md Demonstrates how anchors (&) register values and aliases (*) reference them in YAML. The deserialized result shows that aliases resolve to the same object instance. ```yaml first_item: &item1 name: Apple price: 1.00 second_item: *item1 # Reference to first_item list: - *item1 - *item1 ``` -------------------------------- ### Constructor for YamlSerializationContext Source: https://github.com/hadashia/vyaml/blob/master/_autodocs/serialization-context.md Creates a new serialization context with the given options. Generally not created directly by user code; YamlSerializer manages context creation. ```csharp public YamlSerializationContext(YamlSerializerOptions options) ``` -------------------------------- ### Using Custom Formatter in Composite Resolver Source: https://github.com/hadashia/vyaml/blob/master/_autodocs/resolvers.md Demonstrates how to integrate a custom formatter ('MyTypeFormatter') into the serialization options using a CompositeResolver. This allows VYaml to use the custom logic for 'MyType'. ```csharp // Use in composite resolver var resolver = CompositeResolver.Create( new IYamlFormatter[] { new MyTypeFormatter() }, new IYamlFormatterResolver[] { StandardResolver.Instance }); var options = new YamlSerializerOptions { Resolver = resolver }; ``` -------------------------------- ### Serialize User-Defined Types with YamlObject Source: https://github.com/hadashia/vyaml/blob/master/_autodocs/supported-types.md Decorate custom classes with `[YamlObject]` to enable automatic serialization. This example shows a simple `Person` class. ```csharp [YamlObject] public partial class Person { public string Name { get; set; } public int Age { get; set; } } // Automatically supported YamlSerializer.Serialize(new Person { Name = "Alice", Age = 30 }); ``` -------------------------------- ### Handle Partially Populated Constructors Source: https://github.com/hadashia/vyaml/blob/master/README.md When a constructor does not initialize all members, VYaml will use setters for the remaining members. Ensure that setters are available for these members. ```csharp [YamlObject] public partial class Person { public int Age { get; } // from constructor public string Name { get; } // from constructor public string Profile { get; set; } // from setter // If all members of the construct are not taken as arguments, setters are used for the other members public Person(int age, string name) { this.Age = age; this.Name = name; } } ``` -------------------------------- ### GetScalarAsString Source: https://github.com/hadashia/vyaml/blob/master/_autodocs/parser-api.md Gets the current scalar value as a C# string. Returns null if the scalar is null. Throws YamlParserException if the current event is not a scalar. ```APIDOC ## GetScalarAsString ### Description Gets the current scalar value as a C# `string`, or `null` if the scalar is null. ### Method ```csharp public readonly string? GetScalarAsString() ``` ### Throws `YamlParserException` — If current event is not a scalar ### Example ```csharp if (parser.CurrentEventType == ParseEventType.Scalar) { var text = parser.GetScalarAsString(); } ``` ``` -------------------------------- ### Get Scalar as UInt32 - C# Source: https://github.com/hadashia/vyaml/blob/master/_autodocs/parser-api.md Parses the current scalar value as a 32-bit unsigned integer. Throws YamlParserException if the scalar cannot be parsed as a uint. ```csharp public readonly uint GetScalarAsUInt32() ``` -------------------------------- ### Create CompositeResolver with Formatters and Resolvers Source: https://github.com/hadashia/vyaml/blob/master/_autodocs/resolvers.md Use this factory method to create a composite resolver that first checks custom formatters and then delegates to sub-resolvers. This is useful when you need to apply specific formatting rules before using standard resolution. ```csharp public static CompositeResolver Create( IEnumerable formatters, IEnumerable resolvers) ``` ```csharp var resolver = CompositeResolver.Create( new IYamlFormatter[] { new MyCustomFormatter(), new AnotherFormatter(), }, new IYamlFormatterResolver[] { StandardResolver.Instance, }); var options = new YamlSerializerOptions { Resolver = resolver }; YamlSerializer.Serialize(obj, options); ``` -------------------------------- ### Get Scalar as Int64 - C# Source: https://github.com/hadashia/vyaml/blob/master/_autodocs/parser-api.md Parses the current scalar value as a 64-bit signed integer. Throws YamlParserException if the scalar cannot be parsed as a long. ```csharp public readonly long GetScalarAsInt64() ``` -------------------------------- ### Parse YAML Data with VYamlParser Source: https://github.com/hadashia/vyaml/blob/master/_autodocs/parser-api.md Demonstrates how to parse YAML data from bytes using YamlParser.FromBytes. It iterates through parsing events, extracts scalar values, and handles sequence and mapping structures. Remember to call ReturnPool() when done. ```csharp var yaml = Encoding.UTF8.GetBytes(@" name: Alice age: 30 items: - apple - banana "); var parser = YamlParser.FromBytes(yaml); parser.SkipHeader(); while (parser.Read()) { switch (parser.CurrentEventType) { case ParseEventType.Scalar: Console.WriteLine($"Scalar: {parser.GetScalarAsString()}"); break; case ParseEventType.SequenceStart: Console.WriteLine("Sequence starts"); break; case ParseEventType.MappingStart: Console.WriteLine("Mapping starts"); break; case ParseEventType.StreamEnd: goto End; } } End: parser.ReturnPool(); ``` -------------------------------- ### Get Formatter for Nested Type Source: https://github.com/hadashia/vyaml/blob/master/_autodocs/serialization-context.md Use the resolver from the context to obtain a formatter for a nested type, enabling serialization of complex object structures. ```csharp var nestedFormatter = context.Resolver.GetFormatterWithVerify(); nestedFormatter.Serialize(ref emitter, nestedValue, context); ``` -------------------------------- ### VYaml.Emitter Source: https://github.com/hadashia/vyaml/blob/master/_autodocs/INDEX.md Low-level YAML writing capabilities. ```APIDOC ## VYaml.Emitter Low-level YAML writing. Uses `Utf8YamlEmitter` for streaming YAML generation with configurable options via `YamlEmitOptions`. ``` -------------------------------- ### Catching Specific VYaml Exceptions Source: https://github.com/hadashia/vyaml/blob/master/_autodocs/errors.md Illustrates how to catch specific VYaml exceptions like YamlParserException and YamlSerializerException, followed by a general YamlException catch-all. ```csharp try { var obj = YamlSerializer.Deserialize(yaml); } catch (YamlParserException pex) { // Handle YAML syntax errors Console.WriteLine($"Invalid YAML syntax: {pex.Message}"); } catch (YamlSerializerException sex) { // Handle type conversion errors Console.WriteLine($"Cannot deserialize to type: {sex.Message}"); } catch (YamlException yex) { // Handle other VYaml errors Console.WriteLine($"YAML error: {yex.Message}"); } ``` -------------------------------- ### Omitting Null Values in C# Source: https://github.com/hadashia/vyaml/blob/master/_autodocs/quick-start.md Configure the serializer to ignore properties with null values during serialization. This example shows that 'Age' is not omitted because it's 0, not null. ```csharp var options = new YamlSerializerOptions { DefaultIgnoreCondition = YamlIgnoreCondition.WhenWritingNull }; var person = new Person { Name = "Alice", Age = 0 }; var yaml = YamlSerializer.SerializeToString(person, options); // Output (Age is not omitted because it's 0, not null): // name: Alice // age: 0 ``` -------------------------------- ### Handling Anchors and Aliases in YAML Source: https://github.com/hadashia/vyaml/blob/master/_autodocs/quick-start.md Demonstrates how VYaml automatically handles YAML anchors and aliases, ensuring that repeated values are correctly referenced and deserialized as the same object in memory. ```yaml first_item: &item1 name: Apple price: 1.00 second_item: *item1 list: - *item1 - name: Banana price: 0.50 ``` -------------------------------- ### Low-Level YAML Emission with VYaml Source: https://github.com/hadashia/vyaml/blob/master/_autodocs/README.md Employ Utf8YamlEmitter for constructing YAML output byte by byte. Supports emitting mappings, sequences, and scalars with specified styles. ```csharp var buffer = new ArrayBufferWriter(); var emitter = new Utf8YamlEmitter(buffer); emitter.BeginMapping(); emitter.WriteString("key"); emitter.WriteString("value"); emitter.EndMapping(); ``` -------------------------------- ### Omitting Default Values in C# Source: https://github.com/hadashia/vyaml/blob/master/_autodocs/quick-start.md Configure the serializer to ignore properties with their default values during serialization. This example shows that 'Age' is omitted because it's the default value of 0. ```csharp var options2 = new YamlSerializerOptions { DefaultIgnoreCondition = YamlIgnoreCondition.WhenWritingDefault }; var yaml2 = YamlSerializer.SerializeToString(person, options2); // Output (Age is omitted because it's the default 0): // name: Alice ``` -------------------------------- ### Customizing Serialization Behavior Source: https://github.com/hadashia/vyaml/blob/master/README.md Demonstrates how to customize serialization and deserialization behavior by providing custom formatters and resolvers to YamlSerializerOptions. ```APIDOC ## Customize serialization behaviour - `IYamlFormatter` customizes serialization behavior for a particular type. - `IYamlFormatterResolver` customizes how it searches for `IYamlFormatter` at runtime. To perform Serialize/Deserialize, it needs an `IYamlFormatter` corresponding to a certain C# type. By default, the following `StandardResolver` works and identifies `IYamlFormatter` for that C# type. You can customize this behavior using the following: ```csharp var options = new YamlSerializerOptions { Resolver = CompositeResolver.Create( new IYamlFormatter[] { new YourCustomFormatter1(), // You can add additional formatter }, new IYamlFormatterResolver[] { new YourCustomResolver(), // You can add additional resolver StandardResolver.Instance, // Fallback to default behavior at the end. }) }; YamlSerializer.Deserialize(yaml, options); YamlSerializer.Deserialize(yaml, options); ``` ``` -------------------------------- ### Get Scalar as Boolean - C# Source: https://github.com/hadashia/vyaml/blob/master/_autodocs/parser-api.md Parses the current scalar value as a boolean. It recognizes 'true', 'false', and their case variations. Throws YamlParserException if the scalar cannot be parsed as a boolean. ```csharp public readonly bool GetScalarAsBool() ``` -------------------------------- ### Simple YAML Serialization in C# Source: https://github.com/hadashia/vyaml/blob/master/_autodocs/INDEX.md Use this for basic serialization of C# objects to YAML strings. Ensure your class is marked with [YamlObject]. ```csharp [YamlObject] public partial class Config { ... } ``` ```csharp var yaml = YamlSerializer.SerializeToString(config); ``` -------------------------------- ### Get Scalar as String - C# Source: https://github.com/hadashia/vyaml/blob/master/_autodocs/parser-api.md Retrieves the current scalar value as a C# string. Returns null if the scalar is null. Throws YamlParserException if the current event is not a scalar. ```csharp public readonly string? GetScalarAsString() ``` ```csharp if (parser.CurrentEventType == ParseEventType.Scalar) { var text = parser.GetScalarAsString(); } ``` -------------------------------- ### CompositeResolver.Create (Formatters and Resolvers) Source: https://github.com/hadashia/vyaml/blob/master/_autodocs/resolvers.md Creates a composite resolver with both custom formatters and sub-resolvers. Custom formatters are checked first, followed by the sub-resolvers. ```APIDOC ## CompositeResolver.Create (Formatters and Resolvers) ### Description Creates a composite resolver with both custom formatters and sub-resolvers. ### Method `public static CompositeResolver Create( IEnumerable formatters, IEnumerable resolvers )` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```csharp var resolver = CompositeResolver.Create( new IYamlFormatter[] { new MyCustomFormatter(), new AnotherFormatter(), }, new IYamlFormatterResolver[] { StandardResolver.Instance, }); var options = new YamlSerializerOptions { Resolver = resolver }; YamlSerializer.Serialize(obj, options); ``` ### Response #### Success Response (200) `CompositeResolver` — New composite resolver instance #### Response Example None provided ``` -------------------------------- ### C# Type Mismatch with Alias Source: https://github.com/hadashia/vyaml/blob/master/_autodocs/deserialization-context.md Illustrates a type mismatch error scenario during deserialization when an alias points to a value of an incompatible type. This example shows how to catch the expected YamlSerializerException. ```csharp [YamlObject] public partial class StringList { public string[]Items { get; set; } } [YamlObject] public partial class Config { [YamlMember("stringItems")] public StringList List { get; set; } [YamlMember("numberAlias")] public int Number { get; set; } } // YAML: // stringItems: &myList // items: [a, b] // numberAlias: *myList // Type mismatch: expecting int, got StringList try { var config = YamlSerializer.Deserialize(yaml); } catch (YamlSerializerException ex) { // "The alias value is not a type of Int32" } ``` -------------------------------- ### YamlEmitOptions Source: https://github.com/hadashia/vyaml/blob/master/_autodocs/options-and-configuration.md Controls YAML output formatting, including indentation and string quoting. ```APIDOC ## YamlEmitOptions Controls YAML output formatting. **Namespace:** `VYaml.Emitter` **Source:** `VYaml/Emitter/YamlEmitOptions.cs` ### Static Properties #### Default ```csharp public static readonly YamlEmitOptions Default = new() ``` Predefined default options instance. ### Instance Properties #### IndentWidth ```csharp public int IndentWidth { get; set; } = 2 ``` Gets or sets the indentation width in spaces for block structures. **Type:** `int` **Default:** `2` **Constraints:** Must be positive; no upper limit enforced **Example:** ```csharp var options = new YamlEmitOptions { IndentWidth = 4 }; var serializerOptions = new YamlSerializerOptions { EmitOptions = options }; // Nested structures will use 4-space indentation ``` --- #### StringQuoteStyle ```csharp public ScalarStyle StringQuoteStyle { get; set; } = ScalarStyle.DoubleQuoted ``` Gets or sets the default quote style for string scalars. **Type:** `ScalarStyle` **Default:** `ScalarStyle.DoubleQuoted` **Allowed values:** `ScalarStyle.SingleQuoted` or `ScalarStyle.DoubleQuoted` only **Throws:** `InvalidOperationException` if set to any other `ScalarStyle` value **Example:** ```csharp var options = new YamlEmitOptions { StringQuoteStyle = ScalarStyle.SingleQuoted }; // Strings will default to 'single quotes' instead of "double quotes" ``` ``` -------------------------------- ### Configure Default Ignore Condition for Null Properties Source: https://github.com/hadashia/vyaml/blob/master/_autodocs/options-and-configuration.md Set the default condition for omitting properties during serialization. This example shows how to omit null properties by setting DefaultIgnoreCondition to WhenWritingNull. ```csharp var options = YamlSerializerOptions.Standard; options.DefaultIgnoreCondition = YamlIgnoreCondition.WhenWritingNull; // null properties are omitted from output YamlSerializer.Serialize(new { Name = "Alice", Email = (string)null }, options); // Outputs: "name: Alice" ``` -------------------------------- ### TryGetCurrentAnchor Source: https://github.com/hadashia/vyaml/blob/master/_autodocs/parser-api.md Attempts to retrieve an anchor at the current position. Returns false if no anchor is present. ```APIDOC ## TryGetCurrentAnchor ### Description Attempts to retrieve an anchor at the current position. Returns false if no anchor is present. ### Method Signature ```csharp public bool TryGetCurrentAnchor(out Anchor anchor) ``` ### Parameters #### Output Parameters - **anchor** (`Anchor`) - Output: Anchor with name and ID ### Returns - `bool` - True if an anchor was found ``` -------------------------------- ### Low-Level YAML Emission in C# Source: https://github.com/hadashia/vyaml/blob/master/_autodocs/INDEX.md Use Utf8YamlEmitter for constructing YAML output byte by byte. Useful for building YAML programmatically. ```csharp var buffer = new ArrayBufferWriter(); var emitter = new Utf8YamlEmitter(buffer); emitter.BeginMapping(); emitter.WriteString("key"); emitter.WriteString("value"); emitter.EndMapping(); var yaml = Encoding.UTF8.GetString(buffer.WrittenSpan); ``` -------------------------------- ### TryGetScalarAsSpan Source: https://github.com/hadashia/vyaml/blob/master/_autodocs/parser-api.md Attempts to get the current scalar as a byte span. Returns true if a scalar span was retrieved, false otherwise. The output parameter `span` will contain the UTF-8 bytes or be default if false. ```APIDOC ## TryGetScalarAsSpan ### Description Attempts to get the current scalar as a byte span. Returns false if current event is not a scalar. ### Method ```csharp public readonly bool TryGetScalarAsSpan(out ReadOnlySpan span) ``` ### Parameters #### Path Parameters * `span` (ReadOnlySpan) - Output - UTF-8 bytes (or default if false) ### Returns `bool` — True if a scalar span was retrieved ``` -------------------------------- ### Catching All VYaml Exceptions Source: https://github.com/hadashia/vyaml/blob/master/_autodocs/errors.md Shows a general approach to catching any VYaml-related exception by catching the base YamlException class. ```csharp try { var obj = YamlSerializer.Deserialize(yaml); } catch (YamlException ex) { // Catches YamlParserException, YamlSerializerException, YamlEmitterException, etc. Logger.Error($"YAML operation failed: {ex.Message}", ex); } ``` -------------------------------- ### CompositeResolver.Create (Resolvers Only) Source: https://github.com/hadashia/vyaml/blob/master/_autodocs/resolvers.md Creates a composite resolver with only sub-resolvers, without any custom formatters. ```APIDOC ## CompositeResolver.Create (Resolvers Only) ### Description Creates a composite resolver with only sub-resolvers (no custom formatters). ### Method `public static CompositeResolver Create(IEnumerable resolvers)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None provided ### Response #### Success Response (200) `CompositeResolver` — New composite resolver #### Response Example None provided ``` -------------------------------- ### Try Get Scalar as Span - C# Source: https://github.com/hadashia/vyaml/blob/master/_autodocs/parser-api.md Attempts to retrieve the current scalar value as a byte span. Returns true if successful, false otherwise. The span contains UTF-8 encoded bytes. ```csharp public readonly bool TryGetScalarAsSpan(out ReadOnlySpan span) ``` -------------------------------- ### Create YamlParser from Bytes Source: https://github.com/hadashia/vyaml/blob/master/_autodocs/parser-api.md Use this method to create a YamlParser instance from a Memory containing UTF-8 encoded YAML data. Ensure the input is valid YAML. ```csharp var yaml = Encoding.UTF8.GetBytes("key: value"); var parser = YamlParser.FromBytes(yaml); ``` -------------------------------- ### Get Scalar as Int32 - C# Source: https://github.com/hadashia/vyaml/blob/master/_autodocs/parser-api.md Parses the current scalar value as a 32-bit signed integer. Supports base-10, octal (0o), and hexadecimal (0x) notations. Throws YamlParserException if the scalar cannot be parsed as an int. ```csharp public readonly int GetScalarAsInt32() ``` -------------------------------- ### YamlParser.FromBytes Source: https://github.com/hadashia/vyaml/blob/master/_autodocs/parser-api.md Creates a YamlParser instance from a Memory containing UTF-8 YAML data. ```APIDOC ## YamlParser.FromBytes ### Description Creates a parser from a `Memory` containing UTF-8 YAML. ### Method static YamlParser ### Parameters #### Path Parameters - **bytes** (Memory) - Required - UTF-8 YAML data ### Request Example ```csharp var yaml = Encoding.UTF8.GetBytes("key: value"); var parser = YamlParser.FromBytes(yaml); ``` ### Response #### Success Response (YamlParser) - A new parser instance ``` -------------------------------- ### Skip YAML Header Source: https://github.com/hadashia/vyaml/blob/master/_autodocs/parser-api.md Skips over initial header events such as StreamStart and DocumentStart to reach the actual content of the YAML stream. ```csharp public void SkipHeader() ```