Add from_parts constructors for DeviceKeyId and ServerKeyId

This commit is contained in:
Jonas Platte 2020-08-08 22:37:37 +02:00
parent 1f056b4ba7
commit a183a6c801
No known key found for this signature in database
GPG Key ID: 7D261D771D915378
3 changed files with 39 additions and 2 deletions

View File

@ -4,6 +4,10 @@ Breaking changes:
* Update strum dependency to 0.19
Improvements:
* Add `DeviceKeyId::from_parts` and `ServerKeyId::from_parts`
# 0.17.4
Bug fixes:

View File

@ -1,6 +1,6 @@
//! Identifiers for device keys for end-to-end encryption.
use std::{num::NonZeroU8, str::FromStr};
use std::{convert::TryInto, num::NonZeroU8, str::FromStr};
use ruma_identifiers_validation::{key_algorithms::DeviceKeyAlgorithm, Error};
@ -14,6 +14,23 @@ pub struct DeviceKeyId {
}
impl DeviceKeyId {
/// Create a `DeviceKeyId` from a `DeviceKeyAlgorithm` and a `DeviceId`.
pub fn from_parts(algorithm: DeviceKeyAlgorithm, device_id: &DeviceId) -> Self {
let algorithm: &str = algorithm.as_ref();
let device_id: &str = device_id.as_ref();
let mut res = String::with_capacity(algorithm.len() + 1 + device_id.len());
res.push_str(algorithm);
res.push_str(":");
res.push_str(device_id);
let colon_idx =
NonZeroU8::new(algorithm.len().try_into().expect("no algorithm name len > 255"))
.expect("no empty algorithm name");
DeviceKeyId { full_id: res.into(), colon_idx }
}
/// Returns key algorithm of the device key ID.
pub fn algorithm(&self) -> DeviceKeyAlgorithm {
DeviceKeyAlgorithm::from_str(&self.full_id[..self.colon_idx.get() as usize]).unwrap()

View File

@ -1,6 +1,6 @@
//! Identifiers for homeserver signing keys used for federation.
use std::{num::NonZeroU8, str::FromStr};
use std::{convert::TryInto, num::NonZeroU8, str::FromStr};
use ruma_identifiers_validation::{key_algorithms::ServerKeyAlgorithm, Error};
@ -12,6 +12,22 @@ pub struct ServerKeyId {
}
impl ServerKeyId {
/// Create a `ServerKeyId` from a `ServerKeyAlgorithm` and a `ServerId`.
pub fn from_parts(algorithm: ServerKeyAlgorithm, version: &str) -> Self {
let algorithm: &str = algorithm.as_ref();
let mut res = String::with_capacity(algorithm.len() + 1 + version.len());
res.push_str(algorithm);
res.push_str(":");
res.push_str(version);
let colon_idx =
NonZeroU8::new(algorithm.len().try_into().expect("no algorithm name len > 255"))
.expect("no empty algorithm name");
ServerKeyId { full_id: res.into(), colon_idx }
}
/// Returns key algorithm of the server key ID.
pub fn algorithm(&self) -> ServerKeyAlgorithm {
ServerKeyAlgorithm::from_str(&self.full_id[..self.colon_idx.get() as usize]).unwrap()