async_coap/option/insert.rs
1// Copyright 2019 Google LLC
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// https://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14//
15
16use super::*;
17use core::convert::Into;
18
19/// Trait for types that allow you to insert CoAP options into them.
20pub trait OptionInsert {
21 /// Inserts an option into the message with the given bytes as the value.
22 /// Calling this method with out-of-order keys will incur a significant performance penalty.
23 fn insert_option_with_bytes(&mut self, key: OptionNumber, value: &[u8]) -> Result<(), Error>;
24
25 /// Inserts an option into the message with no value.
26 /// Calling this method with out-of-order keys will incur a significant performance penalty.
27 fn insert_option_empty(&mut self, key: OptionNumber) -> Result<(), Error> {
28 self.insert_option_with_bytes(key, &[])
29 }
30
31 /// Inserts an option into the message with a string value.
32 /// Calling this method with out-of-order keys will incur a significant performance penalty.
33 fn insert_option_with_str(&mut self, key: OptionNumber, value: &str) -> Result<(), Error> {
34 self.insert_option_with_bytes(key, value.as_bytes())
35 }
36
37 /// Inserts an option into the message with an integer value.
38 /// Calling this method with out-of-order keys will incur a significant performance penalty.
39 fn insert_option_with_u32(&mut self, key: OptionNumber, value: u32) -> Result<(), Error> {
40 self.insert_option_with_bytes(key, encode_u32(value, &mut [0; 4]))
41 }
42}
43
44/// Extension class for additional helper methods for `OptionInsertExt`.
45pub trait OptionInsertExt {
46 /// Inserts an option into the message with a value of the appropriate type.
47 /// Calling this method with out-of-order keys will incur a significant performance penalty.
48 fn insert_option<'a, T>(&mut self, key: OptionKey<T>, value: T) -> Result<(), Error>
49 where
50 T: Into<OptionValue<'a>>;
51}
52
53impl<O> OptionInsertExt for O
54where
55 O: OptionInsert + ?Sized,
56{
57 fn insert_option<'a, T>(&mut self, key: OptionKey<T>, value: T) -> Result<(), Error>
58 where
59 T: Into<OptionValue<'a>>,
60 {
61 match value.into() {
62 OptionValue::Integer(x) => self.insert_option_with_u32(key.0, x),
63 OptionValue::Bytes(x) => self.insert_option_with_bytes(key.0, x),
64 OptionValue::ETag(x) => self.insert_option_with_bytes(key.0, x.as_bytes()),
65 }
66 }
67}