hickory_proto/op/op_code.rs
1// Copyright 2015-2021 Benjamin Fry <benjaminfry@me.com>
2//
3// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
4// https://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
5// https://opensource.org/licenses/MIT>, at your option. This file may not be
6// copied, modified, or distributed except according to those terms.
7
8//! Operation code for queries, updates, and responses
9
10use std::{convert::From, fmt};
11
12use crate::error::*;
13
14/// Operation code for queries, updates, and responses
15///
16/// [RFC 1035, DOMAIN NAMES - IMPLEMENTATION AND SPECIFICATION, November 1987](https://tools.ietf.org/html/rfc1035)
17///
18/// ```text
19/// OPCODE A four bit field that specifies kind of query in this
20/// message. This value is set by the originator of a query
21/// and copied into the response. The values are:
22///
23/// 0 a standard query (QUERY)
24///
25/// 1 an inverse query (IQUERY)
26///
27/// 2 a server status request (STATUS)
28///
29/// 3-15 reserved for future use
30/// ```
31#[derive(Debug, PartialEq, Eq, PartialOrd, Copy, Clone, Hash)]
32#[allow(dead_code)]
33pub enum OpCode {
34 /// Query request [RFC 1035](https://tools.ietf.org/html/rfc1035)
35 Query,
36
37 /// Status message [RFC 1035](https://tools.ietf.org/html/rfc1035)
38 Status,
39
40 /// Notify of change [RFC 1996](https://tools.ietf.org/html/rfc1996)
41 Notify,
42
43 /// Update message [RFC 2136](https://tools.ietf.org/html/rfc2136)
44 Update,
45}
46
47impl fmt::Display for OpCode {
48 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
49 let s = match self {
50 Self::Query => "QUERY",
51 Self::Status => "STATUS",
52 Self::Notify => "NOTIFY",
53 Self::Update => "UPDATE",
54 };
55
56 f.write_str(s)
57 }
58}
59
60/// Convert from `OpCode` to `u8`
61///
62/// ```
63/// use hickory_proto::op::op_code::OpCode;
64///
65/// let var: u8 = From::from(OpCode::Query);
66/// assert_eq!(0, var);
67///
68/// let var: u8 = OpCode::Query.into();
69/// assert_eq!(0, var);
70/// ```
71impl From<OpCode> for u8 {
72 fn from(rt: OpCode) -> Self {
73 match rt {
74 OpCode::Query => 0,
75 // 1 IQuery (Inverse Query, OBSOLETE) [RFC3425]
76 OpCode::Status => 2,
77 // 3 Unassigned
78 OpCode::Notify => 4,
79 OpCode::Update => 5,
80 // 6-15 Unassigned
81 }
82 }
83}
84
85/// Convert from `u8` to `OpCode`
86///
87/// ```
88/// use hickory_proto::op::op_code::OpCode;
89///
90/// let var: OpCode = OpCode::from_u8(0).unwrap();
91/// assert_eq!(OpCode::Query, var);
92/// ```
93impl OpCode {
94 /// Decodes the binary value of the OpCode
95 pub fn from_u8(value: u8) -> ProtoResult<Self> {
96 match value {
97 0 => Ok(Self::Query),
98 2 => Ok(Self::Status),
99 4 => Ok(Self::Notify),
100 5 => Ok(Self::Update),
101 _ => Err(format!("unknown OpCode: {value}").into()),
102 }
103 }
104}