rust: Use Self wherever possible

Use Self instead of the struct name whenever possible.
Automagically replace struct name with Self:
`cargo clippy --fix -- -W clippy::use_self`

This streamlines the code.

Reviewed-by: Marc Hartmayer <mhartmay@linux.ibm.com>
Reviewed-by: Jan Höppner <hoeppner@linux.ibm.com>
Signed-off-by: Steffen Eiden <seiden@linux.ibm.com>
Signed-off-by: Jan Höppner <hoeppner@linux.ibm.com>
This commit is contained in:
Steffen Eiden
2024-10-15 14:01:22 +02:00
committed by Jan Höppner
parent 300f8d23b5
commit d30d272523
19 changed files with 98 additions and 98 deletions

View File

@@ -149,7 +149,7 @@ impl BootHdrTags {
let mut tag = [0u8; BootHdrHead::TAG_SIZE];
img.read_exact(tag.as_mut_slice())?;
Ok(BootHdrTags {
Ok(Self {
pld: hdr_head.pld,
ald: hdr_head.ald,
tld: hdr_head.tld,

View File

@@ -68,7 +68,7 @@ impl<C: Zeroize> Confidential<C> {
///
/// Prefer using [`Into`]
pub fn new(v: C) -> Self {
Confidential(v)
Self(v)
}
/// Get a reference to the contained value
@@ -100,8 +100,8 @@ impl<C: Zeroize + Debug> Debug for Confidential<C> {
}
impl<C: Zeroize> From<C> for Confidential<C> {
fn from(v: C) -> Confidential<C> {
Confidential(v)
fn from(v: C) -> Self {
Self(v)
}
}

View File

@@ -39,11 +39,11 @@ impl fmt::Debug for AkidCheckResult {
}
impl AkidCheckResult {
pub const OK: AkidCheckResult = AkidCheckResult(openssl_sys::X509_V_OK);
pub const OK: Self = Self(openssl_sys::X509_V_OK);
/// Creates an `AkidCheckResult` from a raw error number.
unsafe fn from_raw(err: c_int) -> AkidCheckResult {
AkidCheckResult(err)
unsafe fn from_raw(err: c_int) -> Self {
Self(err)
}
}

View File

@@ -73,7 +73,7 @@ impl X509StoreContextExtension for X509StoreContextRef {
with_context: F,
) -> Result<T, ErrorStack>
where
F: FnOnce(&mut X509StoreContextRef) -> Result<T, ErrorStack>,
F: FnOnce(&mut Self) -> Result<T, ErrorStack>,
{
struct Cleanup<'a>(&'a mut X509StoreContextRef);

View File

@@ -20,8 +20,8 @@ impl ForeignType for StackableX509Crl {
type CType = openssl_sys::X509_CRL;
type Ref = X509CrlRef;
unsafe fn from_ptr(ptr: *mut openssl_sys::X509_CRL) -> StackableX509Crl {
StackableX509Crl(ptr)
unsafe fn from_ptr(ptr: *mut openssl_sys::X509_CRL) -> Self {
Self(ptr)
}
fn as_ptr(&self) -> *mut openssl_sys::X509_CRL {
@@ -132,7 +132,7 @@ impl From<X509Crl> for StackableX509Crl {
fn from(value: X509Crl) -> Self {
unsafe {
openssl_sys::X509_CRL_up_ref(value.as_ptr());
StackableX509Crl::from_ptr(value.as_ptr())
Self::from_ptr(value.as_ptr())
}
}
}
@@ -140,7 +140,7 @@ impl From<StackableX509Crl> for X509Crl {
fn from(value: StackableX509Crl) -> Self {
unsafe {
openssl_sys::X509_CRL_up_ref(value.as_ptr());
X509Crl::from_ptr(value.as_ptr())
Self::from_ptr(value.as_ptr())
}
}
}

View File

@@ -148,7 +148,7 @@ impl ReqEncrCtx {
let prot_key = prot_key
.into()
.unwrap_or(SymKey::random(SymKeyType::Aes256)?);
Ok(ReqEncrCtx {
Ok(Self {
iv,
priv_key,
prot_key,

View File

@@ -247,7 +247,7 @@ impl TryFrom<u32> for AttestationVersion {
impl From<AttestationVersion> for RequestVersion {
fn from(val: AttestationVersion) -> Self {
val as RequestVersion
val as Self
}
}

View File

@@ -33,7 +33,7 @@ assert_size!(ReqAuthData, 0x1e8);
impl ReqAuthData {
fn new<F: Into<UvFlags>>(boot_tags: BootHdrTags, flags: F) -> Self {
ReqAuthData {
Self {
flags: flags.into(),
boot_tags,
cuid: [0; 0x10],
@@ -102,7 +102,7 @@ pub enum AddSecretVersion {
impl From<AddSecretVersion> for RequestVersion {
fn from(val: AddSecretVersion) -> Self {
val as RequestVersion
val as Self
}
}
@@ -154,7 +154,7 @@ impl AddSecretRequest {
boot_tags: BootHdrTags,
flags: AddSecretFlags,
) -> Self {
AddSecretRequest {
Self {
conf: ReqConfData {
extension_secret: Confidential::new([0; 32]),
secret,

View File

@@ -47,7 +47,7 @@ impl GuestSecret {
/// # Errors
///
/// This function will return an error if OpenSSL cannot create a hash.
pub fn association<O>(name: &str, secret: O) -> Result<GuestSecret>
pub fn association<O>(name: &str, secret: O) -> Result<Self>
where
O: Into<Option<[u8; ASSOC_SECRET_SIZE]>>,
{
@@ -60,7 +60,7 @@ impl GuestSecret {
None => random_array()?,
};
Ok(GuestSecret::Association {
Ok(Self::Association {
name: name.to_string(),
id: id.into(),
secret: secret.into(),
@@ -70,15 +70,15 @@ impl GuestSecret {
/// Reference to the confidential data
pub(crate) fn confidential(&self) -> &[u8] {
match &self {
GuestSecret::Null => &[],
GuestSecret::Association { secret, .. } => secret.value().as_slice(),
Self::Null => &[],
Self::Association { secret, .. } => secret.value().as_slice(),
}
}
/// Creates the non-confidential part of the secret ad-hoc
pub(crate) fn auth(&self) -> SecretAuth {
match &self {
GuestSecret::Null => SecretAuth::Null,
Self::Null => SecretAuth::Null,
// Panic: every non null secret type is listable -> no panic
listable => {
SecretAuth::Listable(ListableSecretHdr::from_guest_secret(listable).unwrap())
@@ -90,24 +90,24 @@ impl GuestSecret {
fn kind(&self) -> u16 {
match self {
// Null is not listable, but the ListableSecretType provides the type constant (1)
GuestSecret::Null => ListableSecretType::NULL,
GuestSecret::Association { .. } => ListableSecretType::ASSOCIATION,
Self::Null => ListableSecretType::NULL,
Self::Association { .. } => ListableSecretType::ASSOCIATION,
}
}
/// Size of the secret value
fn secret_len(&self) -> u32 {
match self {
GuestSecret::Null => 0,
GuestSecret::Association { secret, .. } => secret.value().len() as u32,
Self::Null => 0,
Self::Association { secret, .. } => secret.value().len() as u32,
}
}
/// Returns the ID of the secret type (if any)
fn id(&self) -> Option<SecretId> {
match self {
GuestSecret::Null => None,
GuestSecret::Association { id, .. } => Some(id.to_owned()),
Self::Null => None,
Self::Association { id, .. } => Some(id.to_owned()),
}
}
}
@@ -115,7 +115,7 @@ impl GuestSecret {
impl Display for GuestSecret {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
GuestSecret::Null => write!(f, "Meta"),
Self::Null => write!(f, "Meta"),
gs => {
let kind: U16<BigEndian> = gs.kind().into();
let st: ListableSecretType = kind.into();
@@ -134,8 +134,8 @@ pub(crate) enum SecretAuth {
impl SecretAuth {
pub fn get(&self) -> &[u8] {
match self {
SecretAuth::Null => &[0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
SecretAuth::Listable(h) => h.as_bytes(),
Self::Null => &[0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
Self::Listable(h) => h.as_bytes(),
}
}
}

View File

@@ -156,8 +156,8 @@ impl UserData {
pub(super) fn sign(&self, buf: &mut [u8], user_data_offset: usize) -> Result<()> {
// get signing info or return if no signature is required
let signed_data = match self {
UserData::Null | UserData::Unsigned(_) => return Ok(()),
UserData::Signed(s) => s,
Self::Null | Self::Unsigned(_) => return Ok(()),
Self::Signed(s) => s,
};
debug_assert!(buf.len() >= USER_DATA_SIZE);
@@ -194,9 +194,9 @@ impl UserData {
/// 512 bytes
pub(super) fn data(&self) -> (Option<&[u8]>, Option<Vec<u8>>) {
let buf = match self {
UserData::Null => None,
UserData::Unsigned(d) => Some(d),
UserData::Signed(SignedUserData { data, .. }) => Some(data),
Self::Null => None,
Self::Unsigned(d) => Some(d),
Self::Signed(SignedUserData { data, .. }) => Some(data),
};
let remaining_size = Self::USER_DATA_SIZE - buf.map(|b| b.len()).unwrap_or(0);

View File

@@ -37,7 +37,7 @@ impl AttestationMeasAlg {
/// Report the expected size for a given measurement algorithm
pub const fn exp_size(&self) -> u32 {
match self {
AttestationMeasAlg::HmacSha512 => 64,
Self::HmacSha512 => 64,
}
}
}
@@ -46,7 +46,7 @@ impl<E: ByteOrder> TryFrom<U32<E>> for AttestationMeasAlg {
type Error = Error;
fn try_from(value: U32<E>) -> Result<Self, Self::Error> {
if value.get() == AttestationMeasAlg::HmacSha512 as u32 {
if value.get() == Self::HmacSha512 as u32 {
Ok(Self::HmacSha512)
} else {
Err(Error::BinArcbInvAlgorithm(value.get()))

View File

@@ -204,10 +204,10 @@ impl UvDevice {
std::fs::OpenOptions::new()
.read(true)
.write(true)
.open(UvDevice::PATH)
.open(Self::PATH)
.map_err(|e| Error::FileAccess {
ty: FileAccessErrorType::Open,
path: (UvDevice::PATH).into(),
path: (Self::PATH).into(),
source: e,
})?,
))

View File

@@ -100,18 +100,18 @@ impl AttestationCmd {
Self::verify_size(
exp_measurement,
1,
AttestationCmd::MEASUREMENT_MAX_SIZE,
Self::MEASUREMENT_MAX_SIZE,
"Expected measurement size",
)?;
Self::verify_size(
exp_additional,
0,
AttestationCmd::ADDITIONAL_MAX_SIZE,
Self::ADDITIONAL_MAX_SIZE,
"Expected additional data size",
)?;
Self::verify_slice(&arcb, AttestationCmd::ARCB_MAX_SIZE, "Attestation request")?;
Self::verify_slice(&arcb, Self::ARCB_MAX_SIZE, "Attestation request")?;
if let Some(ref data) = user_data {
Self::verify_slice(data, AttestationCmd::USER_MAX_SIZE, "User data")?;
Self::verify_slice(data, Self::USER_MAX_SIZE, "User data")?;
}
let (user_len, user_data) = match user_data {

View File

@@ -60,8 +60,8 @@ impl Display for SecretId {
}
}
impl From<[u8; SecretId::ID_SIZE]> for SecretId {
fn from(value: [u8; SecretId::ID_SIZE]) -> Self {
impl From<[u8; Self::ID_SIZE]> for SecretId {
fn from(value: [u8; Self::ID_SIZE]) -> Self {
Self(value)
}
}
@@ -251,8 +251,8 @@ impl SecretList {
impl TryFrom<ListCmd> for SecretList {
type Error = Error;
fn try_from(mut list: ListCmd) -> Result<SecretList> {
SecretList::decode(&mut Cursor::new(list.data().unwrap())).map_err(Error::InvSecretList)
fn try_from(mut list: ListCmd) -> Result<Self> {
Self::decode(&mut Cursor::new(list.data().unwrap())).map_err(Error::InvSecretList)
}
}
@@ -315,7 +315,7 @@ impl From<U16<BigEndian>> for ListableSecretType {
match value.get() {
Self::RESERVED_0 => Self::Invalid(Self::RESERVED_0),
Self::NULL => Self::Invalid(Self::NULL),
Self::ASSOCIATION => ListableSecretType::Association,
Self::ASSOCIATION => Self::Association,
n => Self::Unknown(n),
}
}

View File

@@ -41,7 +41,7 @@ impl AddSecretMagic {
/// Get the magic value.
pub fn get(&self) -> RequestMagic {
let mut res = RequestMagic::default();
debug_assert!(res.len() == size_of::<AddSecretMagic>());
debug_assert!(res.len() == size_of::<Self>());
// Panic: does not panic, buf is 8 bytes long
self.write_to(&mut res).unwrap();
res
@@ -51,7 +51,7 @@ impl AddSecretMagic {
///
/// Returns [`None`] if the byte slice does not contain a valid magic value variant.
pub fn try_from_bytes(bytes: &[u8]) -> Result<Self> {
if !Self::starts_with_magic(bytes) || bytes.len() < size_of::<AddSecretMagic>() {
if !Self::starts_with_magic(bytes) || bytes.len() < size_of::<Self>() {
return Err(Error::NoAsrcb);
}
@@ -89,11 +89,11 @@ impl UserDataType {
/// Returns the maximum user-data size in bytes.
pub fn max(&self) -> usize {
match self {
UserDataType::Null => 0,
UserDataType::Unsigned => 512,
UserDataType::SgnEcSECP521R1 => 256,
UserDataType::SgnRsa2048 => 256,
UserDataType::SgnRsa3072 => 128,
Self::Null => 0,
Self::Unsigned => 512,
Self::SgnEcSECP521R1 => 256,
Self::SgnRsa2048 => 256,
Self::SgnRsa3072 => 128,
}
}
}
@@ -118,16 +118,16 @@ impl TryFrom<u16> for UserDataType {
type Error = Error;
fn try_from(value: u16) -> std::result::Result<Self, Self::Error> {
if value == UserDataType::Null as u16 {
Ok(UserDataType::Null)
} else if value == UserDataType::Unsigned as u16 {
Ok(UserDataType::Unsigned)
} else if value == UserDataType::SgnEcSECP521R1 as u16 {
Ok(UserDataType::SgnEcSECP521R1)
} else if value == UserDataType::SgnRsa2048 as u16 {
Ok(UserDataType::SgnRsa2048)
} else if value == UserDataType::SgnRsa3072 as u16 {
Ok(UserDataType::SgnRsa3072)
if value == Self::Null as u16 {
Ok(Self::Null)
} else if value == Self::Unsigned as u16 {
Ok(Self::Unsigned)
} else if value == Self::SgnEcSECP521R1 as u16 {
Ok(Self::SgnEcSECP521R1)
} else if value == Self::SgnRsa2048 as u16 {
Ok(Self::SgnRsa2048)
} else if value == Self::SgnRsa3072 as u16 {
Ok(Self::SgnRsa3072)
} else {
Err(Error::UnsupportedUserData(value))
}

View File

@@ -135,11 +135,11 @@ pub enum ApqnInfo {
}
impl ApqnInfo {
fn accel_info(_carddir: &str, _queuedir: &str) -> Result<ApqnInfo, String> {
Ok(ApqnInfo::Accel(ApqnInfoAccel {}))
fn accel_info(_carddir: &str, _queuedir: &str) -> Result<Self, String> {
Ok(Self::Accel(ApqnInfoAccel {}))
}
fn cca_info(carddir: &str, queuedir: &str) -> Result<ApqnInfo, String> {
fn cca_info(carddir: &str, queuedir: &str) -> Result<Self, String> {
let serialnr = match sysfs_read_string(&format!("{carddir}/serialnr")) {
Ok(r) => r,
Err(err) => {
@@ -202,14 +202,14 @@ impl ApqnInfo {
}
}
}
Ok(ApqnInfo::Cca(ApqnInfoCca {
Ok(Self::Cca(ApqnInfoCca {
serialnr,
mkvp_aes: aes_mkvp,
mkvp_apka: apka_mkvp,
}))
}
fn ep11_info(carddir: &str, queuedir: &str) -> Result<ApqnInfo, String> {
fn ep11_info(carddir: &str, queuedir: &str) -> Result<Self, String> {
let serialnr = match sysfs_read_string(&format!("{carddir}/serialnr")) {
Ok(r) => r,
Err(err) => {
@@ -250,14 +250,14 @@ impl ApqnInfo {
}
}
}
Ok(ApqnInfo::Ep11(ApqnInfoEp11 { serialnr, mkvp }))
Ok(Self::Ep11(ApqnInfoEp11 { serialnr, mkvp }))
}
fn info(mode: &ApqnMode, carddir: &str, queuedir: &str) -> Result<ApqnInfo, String> {
fn info(mode: &ApqnMode, carddir: &str, queuedir: &str) -> Result<Self, String> {
match mode {
ApqnMode::Accel => ApqnInfo::accel_info(carddir, queuedir),
ApqnMode::Cca => ApqnInfo::cca_info(carddir, queuedir),
ApqnMode::Ep11 => ApqnInfo::ep11_info(carddir, queuedir),
ApqnMode::Accel => Self::accel_info(carddir, queuedir),
ApqnMode::Cca => Self::cca_info(carddir, queuedir),
ApqnMode::Ep11 => Self::ep11_info(carddir, queuedir),
}
}
}
@@ -302,8 +302,8 @@ pub struct ApqnList(Vec<Apqn>);
impl ApqnList {
#[cfg(test)] // only used in test code
pub fn from_apqn_vec(apqns: Vec<Apqn>) -> ApqnList {
ApqnList(apqns)
pub fn from_apqn_vec(apqns: Vec<Apqn>) -> Self {
Self(apqns)
}
#[cfg(test)] // only used in test code
@@ -335,7 +335,7 @@ impl ApqnList {
/// static regular expression will result in calling panic.
/// # Panics
/// Panics if the compilation of a static regular expression fails.
pub fn gather_apqns() -> Option<ApqnList> {
pub fn gather_apqns() -> Option<Self> {
let mut apqns: Vec<Apqn> = Vec::new();
let re_card_type = Regex::new(RE_CARD_TYPE).unwrap();
let re_queue_dir = Regex::new(RE_QUEUE_DIR).unwrap();
@@ -462,7 +462,7 @@ impl ApqnList {
});
}
}
Some(ApqnList(apqns))
Some(Self(apqns))
}
/// Sort this Apqnlist by card generation:

View File

@@ -153,8 +153,8 @@ pub struct ApConfigList(Vec<ApConfigEntry>);
impl ApConfigList {
#[cfg(test)] // only used in test code
pub fn from_apconfigentry_vec(apconfigs: Vec<ApConfigEntry>) -> ApConfigList {
ApConfigList(apconfigs)
pub fn from_apconfigentry_vec(apconfigs: Vec<ApConfigEntry>) -> Self {
Self(apconfigs)
}
pub fn iter(&self) -> Iter<'_, ApConfigEntry> {
@@ -205,10 +205,10 @@ impl ApConfigList {
/// Read in and validate the yaml configuration from a file.
/// Returns a Result with Ok(ApConfigList) on success
/// or an Err(errorstring) on failure.
pub fn read_and_validate_yaml_file(fname: &str) -> Result<ApConfigList, String> {
let mut apconfig = ApConfigList::read_yaml_file(fname)?;
ApConfigList::validate(&mut apconfig)?;
Ok(ApConfigList(apconfig))
pub fn read_and_validate_yaml_file(fname: &str) -> Result<Self, String> {
let mut apconfig = Self::read_yaml_file(fname)?;
Self::validate(&mut apconfig)?;
Ok(Self(apconfig))
}
}

View File

@@ -181,7 +181,7 @@ impl LockFile {
.map_err(|err| {
println!("Warning: could not write PID into lockfile {fname}: {err:?}.")
});
Ok(LockFile { lockfile })
Ok(Self { lockfile })
}
}

View File

@@ -70,9 +70,9 @@ impl Entry {
R: Read + Seek,
{
match self {
Entry { size, .. } if size.get() == 0 => Ok(ExpOrData::None),
Entry { size, offset } if offset.get() == 0 => Ok(ExpOrData::Exp(size.get())),
Entry { size, offset } => {
Self { size, .. } if size.get() == 0 => Ok(ExpOrData::None),
Self { size, offset } if offset.get() == 0 => Ok(ExpOrData::Exp(size.get())),
Self { size, offset } => {
reader.seek(SeekFrom::Start(offset.get() as u64))?;
let mut buf = vec![0; size.get() as usize];
reader.read_exact(&mut buf)?;
@@ -100,7 +100,7 @@ assert_size!(ExchangeFormatV1Hdr, 0x40);
impl ExchangeFormatV1Hdr {
fn new_request(arcb: &[u8], measurement: u32, additional: u32) -> Result<Self> {
let mut offset: u32 = size_of::<ExchangeFormatV1Hdr>() as u32;
let mut offset: u32 = size_of::<Self>() as u32;
let arcb_entry = Entry::from_slice(Some(arcb), AttestationCmd::ARCB_MAX_SIZE, &mut offset);
let measurement_entry = Entry::from_exp(Some(measurement));
let exp_add = match additional {
@@ -132,7 +132,7 @@ impl ExchangeFormatV1Hdr {
user: Option<&[u8]>,
config_uid: &[u8],
) -> Result<Self> {
let mut offset: u32 = size_of::<ExchangeFormatV1Hdr>() as u32;
let mut offset: u32 = size_of::<Self>() as u32;
let arcb_entry = Entry::from_slice(Some(arcb), AttestationCmd::ARCB_MAX_SIZE, &mut offset);
let measurement_entry = Entry::from_slice(
Some(measurement),
@@ -219,10 +219,10 @@ impl ExpOrData {
/// calculates the (expected or real) size
fn size(&self) -> u32 {
match self {
ExpOrData::Exp(s) => *s,
Self::Exp(s) => *s,
// size is max u32 large as read in before
ExpOrData::Data(v) => v.len() as u32,
ExpOrData::None => 0,
Self::Data(v) => v.len() as u32,
Self::None => 0,
}
}
@@ -231,7 +231,7 @@ impl ExpOrData {
/// Consumes itself
fn data(self) -> Option<Vec<u8>> {
match self {
ExpOrData::Data(v) => Some(v),
Self::Data(v) => Some(v),
_ => None,
}
}
@@ -240,8 +240,8 @@ impl ExpOrData {
impl From<Option<u32>> for ExpOrData {
fn from(value: Option<u32>) -> Self {
match value {
Some(v) => ExpOrData::Exp(v),
None => ExpOrData::None,
Some(v) => Self::Exp(v),
None => Self::None,
}
}
}