TlvWriter.TlvScope Class
Namespace: Yubico.Core.Tlv Assembly: Yubico.Core.dllThe struct that defines the scope of a Nested TLV. An instance of this Struct is returned by a call to TlvWriter.WriteNestedTlv.
public sealed class TlvScope : ValueType, IDisposable
Implements
Remarks
The way the caller is supposed to build Nested schemas using TlvWriter is as follows.
var writer = new TlvWriter();
using (writer.WriteNestedTlv(tag0))
{
writer.WriteValue(tag1, element1);
writer.WriteValue(tag2, element2);
}
byte[] encoding = tlvWriter.Encode();
The using directive in this case means that when the variable goes out of scope, the Dispose method will be called immediately. Furthermore, when written this way (with the curly braces), the variable goes out of scope upon completion of the close curly brace.
The WriteNestedTlv method returns an instance of TlvWriter.TlvScope. So in the above construction, the variable for which the using is constructed is the TlvWriter.TlvScope returned by the method.
Normally, a Dispose method overwrites sensitive data or releases resources (files, internet connections, etc.). However, the Dispose in this class simply calls the TlvWriter.EndNestedTlv.
When we're building a schema, we want to make sure the elements that belong under a particular NestedTlv are placed there and not anywhere else. In order to do so, we have a method that says, Start Nested TLV. Now, every Element that is added, until we hit the end, will be subordinate to this Nested TLV. When we have added all the sub-elements to a Nested TLV, we can call the End method. However, a decision was made not to expose the End method, but to use this "using" construction. The reason is so that code can be written to have a structure where the indentations in the code match the schema.
Really, that's why it is done this way. To make the code have the same visual style of the schema. For example:
Suppose you have an encoding that will look something like this:
7C len Nested TLV
81 len value
82 len value
7D len Nested TLV
83 len value
84 len value
85 len value
Code following the pattern that uses "using" and TlvWriter.TlvScope
would look something like this.
var writer = new TlvWriter();
using (writer.WriteNestedTlv(0x7C))
{
writer.WriteValue(0x81, value81);
writer.WriteValue(0x82, value82);
using (writer.WriteNestedTlv(0x7C))
{
writer.WriteValue(0x83, value83);
writer.WriteValue(0x84, value84);
}
writer.WriteValue(0x85, value85);
}
byte[] encoding = tlvWriter.Encode();
Methods
Name | Description |
---|---|
Dispose() | When the Scope object goes out of scope, this method is called. It will make sure the Nested TLV is ended and any new additions to the TlvWriter object will be associated with the Nested TLV's parent. |