v2 / vlib / x / encoding / asn1 / null.v
62 lines · 54 sloc · 1.69 KB · 58fc4dead559901cad648fb695f31d0f6de9945a
Raw
1// Copyright (c) 2022, 2023 blackshirt. All rights reserved.
2// Use of this source code is governed by a MIT License
3// that can be found in the LICENSE file.
4module asn1
5
6// default_null_tag is the default tag of ASN.1 NULL type.
7pub const default_null_tag = Tag{.universal, false, int(TagType.null)}
8
9// ASN.1 UNIVERSAL CLASS OF NULL TYPE.
10//
11// The ASN.1 NULL type is a placeholder used when there is no value.
12// It's a simple, non-string type with the UNIVERSAL TAG number 5.
13// The NULL type can be used in situations where the presence of a type is important, but no concrete value is needed.
14pub struct Null {}
15
16// tag returns the tag of Null element.
17pub fn (n Null) tag() Tag {
18 return default_null_tag
19}
20
21// payload returns the payload of the Null element, its should empty bytes.
22pub fn (n Null) payload() ![]u8 {
23 return []u8{}
24}
25
26fn (n Null) str() string {
27 return 'NULL'
28}
29
30// `Null.parse` tries to read into Null type from ongoing parser.
31fn Null.parse(mut p Parser) !Null {
32 tag := p.read_tag()!
33 if !tag.equal(default_null_tag) {
34 return error('Get unexpected null tag')
35 }
36 length := p.read_length()!
37 if length != 0 {
38 return error('Get unexpected non-null length for Null type')
39 }
40 return Null{}
41}
42
43// Null.decode read Null from bytes.
44fn Null.decode(bytes []u8) !(Null, int) {
45 tag, length_pos := Tag.decode(bytes)!
46 if !tag.equal(default_null_tag) {
47 return error('Null: get unexpected tag')
48 }
49 length, content_pos := Length.decode_from_offset(bytes, length_pos)!
50 if length != 0 {
51 return error('Null with non-null length')
52 }
53 next := content_pos + length
54 return Null{}, next
55}
56
57fn Null.from_bytes(b []u8) !Null {
58 if b.len != 0 {
59 return error('Null: bad non-null bytes')
60 }
61 return Null{}
62}
63