use std::borrow::Cow;
use std::fmt;
use std::str::FromStr;
use crate::entry::Entry;
use crate::error::{
MutationValueError, ParseEntryError, ParseEntryValueError, ParseKeyError, ValueError,
};
pub(crate) const VERSION_EXCLUDES: [&str; 6] = [
EntryKeys::DBusActivatable.key(),
EntryKeys::Actions.key(),
EntryKeys::Keywords.key(),
EntryKeys::Implements.key(),
EntryKeys::PrefersNonDefaultGPU.key(),
EntryKeys::SingleMainWindow.key(),
];
pub(crate) const APPLICATION: &str = "Application";
pub(crate) const DIRECTORY: &str = "Directory";
pub(crate) const LINK: &str = "Link";
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub enum EntryKeys {
Type,
Version,
Name,
GenericName,
NoDisplay,
Comment,
Icon,
Hidden,
OnlyShowIn,
NotShowIn,
DBusActivatable,
TryExec,
Exec,
Path,
Terminal,
Actions,
MimeType,
Categories,
Implements,
Keywords,
StartupNotify,
StartupWMClass,
URL,
PrefersNonDefaultGPU,
SingleMainWindow,
}
impl EntryKeys {
pub(crate) const KEYS: &[&'static str] = &[
EntryKeys::Type.key(),
EntryKeys::Version.key(),
EntryKeys::Name.key(),
EntryKeys::GenericName.key(),
EntryKeys::NoDisplay.key(),
EntryKeys::Comment.key(),
EntryKeys::Icon.key(),
EntryKeys::Hidden.key(),
EntryKeys::OnlyShowIn.key(),
EntryKeys::NotShowIn.key(),
EntryKeys::DBusActivatable.key(),
EntryKeys::TryExec.key(),
EntryKeys::Exec.key(),
EntryKeys::Path.key(),
EntryKeys::Terminal.key(),
EntryKeys::Actions.key(),
EntryKeys::MimeType.key(),
EntryKeys::Categories.key(),
EntryKeys::Implements.key(),
EntryKeys::Keywords.key(),
EntryKeys::StartupNotify.key(),
EntryKeys::StartupWMClass.key(),
EntryKeys::URL.key(),
EntryKeys::PrefersNonDefaultGPU.key(),
EntryKeys::SingleMainWindow.key(),
];
#[inline]
#[must_use]
pub fn all_keys() -> AllKeys {
AllKeys(Self::KEYS.iter())
}
#[inline]
#[must_use]
pub const fn is_required(self) -> bool {
matches!(self, Self::Type | Self::Name)
}
#[inline]
#[must_use]
pub const fn is_required_for(self, desktop_type: DesktopType) -> bool {
self.is_required() || matches!((self, desktop_type), (Self::URL, DesktopType::Link))
}
#[inline]
#[must_use]
pub const fn key(self) -> &'static str {
match self {
Self::Type => "Type",
Self::Version => "Version",
Self::Name => "Name",
Self::GenericName => "GenericName",
Self::NoDisplay => "NoDisplay",
Self::Comment => "Comment",
Self::Icon => "Icon",
Self::Hidden => "Hidden",
Self::OnlyShowIn => "OnlyShowIn",
Self::NotShowIn => "NotShowIn",
Self::DBusActivatable => "DBusActivatable",
Self::TryExec => "TryExec",
Self::Exec => "Exec",
Self::Path => "Path",
Self::Terminal => "Terminal",
Self::Actions => "Actions",
Self::MimeType => "MimeType",
Self::Categories => "Categories",
Self::Implements => "Implements",
Self::Keywords => "Keywords",
Self::StartupNotify => "StartupNotify",
Self::StartupWMClass => "StartupWMClass",
Self::URL => "URL",
Self::PrefersNonDefaultGPU => "PrefersNonDefaultGPU",
Self::SingleMainWindow => "SingleMainWindow",
}
}
#[inline]
#[must_use]
pub const fn version_introduced(self) -> Option<Version> {
match self {
Self::DBusActivatable | Self::Actions | Self::Keywords => Some(Version::Ver1_1),
Self::Implements => Some(Version::Ver1_2),
Self::PrefersNonDefaultGPU => Some(Version::Ver1_4),
Self::SingleMainWindow => Some(Version::Ver1_5),
_ => None,
}
}
#[must_use]
pub fn localizable_key(self) -> Option<EntryKeys> {
Some(match self {
Self::Name | Self::GenericName | Self::Comment | Self::Icon | Self::Keywords => self,
_ => return None,
})
}
#[must_use]
pub fn parse_localizable_key(s: &str) -> Option<EntryKeys> {
Some(match s {
"Name" => Self::Name,
"GenericName" => Self::GenericName,
"Comment" => Self::Comment,
"Icon" => Self::Icon,
"Keywords" => Self::Keywords,
_ => return None,
})
}
}
impl AsRef<str> for EntryKeys {
fn as_ref(&self) -> &str {
self.key()
}
}
impl fmt::Display for EntryKeys {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
self.key().fmt(f)
}
}
impl From<EntryKeys> for &str {
#[inline]
fn from(entry_key: EntryKeys) -> &'static str {
entry_key.key()
}
}
impl From<EntryKeys> for Cow<'static, str> {
#[inline]
fn from(entry_key: EntryKeys) -> Self {
entry_key.key().into()
}
}
impl FromStr for EntryKeys {
type Err = ParseKeyError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
val if val == EntryKeys::Type.key() => Ok(Self::Type),
val if val == EntryKeys::Version.key() => Ok(Self::Version),
val if val == EntryKeys::Name.key() => Ok(Self::Name),
val if val == EntryKeys::GenericName.key() => Ok(Self::GenericName),
val if val == EntryKeys::NoDisplay.key() => Ok(Self::NoDisplay),
val if val == EntryKeys::Comment.key() => Ok(Self::Comment),
val if val == EntryKeys::Icon.key() => Ok(Self::Icon),
val if val == EntryKeys::Hidden.key() => Ok(Self::Hidden),
val if val == EntryKeys::OnlyShowIn.key() => Ok(Self::OnlyShowIn),
val if val == EntryKeys::NotShowIn.key() => Ok(Self::NotShowIn),
val if val == EntryKeys::DBusActivatable.key() => Ok(Self::DBusActivatable),
val if val == EntryKeys::TryExec.key() => Ok(Self::TryExec),
val if val == EntryKeys::Exec.key() => Ok(Self::Exec),
val if val == EntryKeys::Path.key() => Ok(Self::Path),
val if val == EntryKeys::Terminal.key() => Ok(Self::Terminal),
val if val == EntryKeys::Actions.key() => Ok(Self::Actions),
val if val == EntryKeys::MimeType.key() => Ok(Self::MimeType),
val if val == EntryKeys::Categories.key() => Ok(Self::Categories),
val if val == EntryKeys::Implements.key() => Ok(Self::Implements),
val if val == EntryKeys::Keywords.key() => Ok(Self::Keywords),
val if val == EntryKeys::StartupNotify.key() => Ok(Self::StartupNotify),
val if val == EntryKeys::StartupWMClass.key() => Ok(Self::StartupWMClass),
val if val == EntryKeys::URL.key() => Ok(Self::URL),
val if val == EntryKeys::PrefersNonDefaultGPU.key() => Ok(Self::PrefersNonDefaultGPU),
val if val == EntryKeys::SingleMainWindow.key() => Ok(Self::SingleMainWindow),
_ => Err(ParseKeyError::NonStandardKey),
}
}
}
#[derive(Debug, Clone)]
pub struct AllKeys(std::slice::Iter<'static, &'static str>);
impl Iterator for AllKeys {
type Item = &'static str;
fn next(&mut self) -> Option<Self::Item> {
self.0.next().map(|value| &**value)
}
fn size_hint(&self) -> (usize, Option<usize>) {
self.0.size_hint()
}
}
impl DoubleEndedIterator for AllKeys {
fn next_back(&mut self) -> Option<Self::Item> {
self.0.next_back().map(|value| &**value)
}
}
impl ExactSizeIterator for AllKeys {}
impl std::iter::FusedIterator for AllKeys {}
#[derive(Default, Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum DesktopType {
#[default]
Application,
Link,
Directory,
}
impl DesktopType {
#[inline]
#[must_use]
pub fn as_str(&self) -> &str {
match self {
Self::Application => APPLICATION,
Self::Link => LINK,
Self::Directory => DIRECTORY,
}
}
}
impl AsRef<str> for DesktopType {
fn as_ref(&self) -> &str {
self.as_str()
}
}
impl fmt::Display for DesktopType {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.as_str())
}
}
impl From<DesktopType> for &str {
#[inline]
fn from(value: DesktopType) -> Self {
match value {
DesktopType::Application => APPLICATION,
DesktopType::Link => LINK,
DesktopType::Directory => DIRECTORY,
}
}
}
impl FromStr for DesktopType {
type Err = ParseEntryValueError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
Self::try_from(s)
}
}
impl TryFrom<&str> for DesktopType {
type Error = ParseEntryValueError;
fn try_from(s: &str) -> Result<Self, Self::Error> {
match s {
APPLICATION => Ok(Self::Application),
LINK => Ok(Self::Link),
DIRECTORY => Ok(Self::Directory),
_ => Err(ParseEntryValueError::ParseDesktopType),
}
}
}
impl TryFrom<String> for DesktopType {
type Error = ParseEntryValueError;
fn try_from(s: String) -> Result<Self, Self::Error> {
DesktopType::try_from(s.as_str())
}
}
impl<'a> TryFrom<&'a Entry> for &'a DesktopType {
type Error = ValueError;
fn try_from(entry: &'a Entry) -> Result<Self, Self::Error> {
match entry {
Entry::Type(value) => Ok(value),
entry => Err(ValueError(entry.value_type().to_string())),
}
}
}
#[derive(Default, Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[non_exhaustive]
pub enum Version {
Ver1_0,
Ver1_1,
Ver1_2,
Ver1_3,
Ver1_4,
#[default]
Ver1_5,
}
impl Version {
#[must_use]
pub const fn latest() -> Self {
Self::Ver1_5
}
#[inline]
#[must_use]
pub const fn version(&self) -> &'static str {
match self {
Self::Ver1_0 => "1.0",
Self::Ver1_1 => "1.1",
Self::Ver1_2 => "1.2",
Self::Ver1_3 => "1.3",
Self::Ver1_4 => "1.4",
Self::Ver1_5 => "1.5",
}
}
#[inline]
#[must_use]
pub fn is_valid_version(s: &str) -> bool {
s.parse::<Version>().is_ok()
}
}
impl AsRef<str> for Version {
fn as_ref(&self) -> &str {
self.version()
}
}
impl fmt::Display for Version {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
self.version().fmt(f)
}
}
impl From<Version> for f64 {
fn from(value: Version) -> f64 {
match value {
Version::Ver1_0 => 1.0,
Version::Ver1_1 => 1.1,
Version::Ver1_2 => 1.2,
Version::Ver1_3 => 1.3,
Version::Ver1_4 => 1.4,
Version::Ver1_5 => 1.5,
}
}
}
impl From<Version> for &'static str {
fn from(value: Version) -> &'static str {
value.version()
}
}
impl FromStr for Version {
type Err = ParseEntryValueError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
Self::try_from(s)
}
}
impl TryFrom<&str> for Version {
type Error = ParseEntryValueError;
fn try_from(s: &str) -> Result<Self, Self::Error> {
match s {
val if val == Self::Ver1_0.version() => Ok(Self::Ver1_0),
val if val == Self::Ver1_1.version() => Ok(Self::Ver1_1),
val if val == Self::Ver1_2.version() => Ok(Self::Ver1_2),
val if val == Self::Ver1_3.version() => Ok(Self::Ver1_3),
val if val == Self::Ver1_4.version() => Ok(Self::Ver1_4),
val if val == Self::Ver1_5.version() => Ok(Self::Ver1_5),
_ => Err(ParseEntryValueError::ParseVersion),
}
}
}
impl TryFrom<String> for Version {
type Error = ParseEntryValueError;
fn try_from(s: String) -> Result<Self, Self::Error> {
Version::try_from(s.as_str())
}
}
impl<'a> TryFrom<&'a Entry> for &'a Version {
type Error = ValueError;
fn try_from(entry: &'a Entry) -> Result<Self, Self::Error> {
match entry {
Entry::Version(value) => Ok(value),
entry => Err(ValueError(entry.value_type().to_string())),
}
}
}
impl<'a> TryFrom<&'a mut Entry> for &'a mut Version {
type Error = MutationValueError;
fn try_from(entry: &'a mut Entry) -> Result<Self, Self::Error> {
match entry {
Entry::Version(value) => Ok(value),
entry => Err(MutationValueError(entry.value_type().to_string())),
}
}
}
#[derive(Default, Debug, Copy, Clone, PartialEq, PartialOrd)]
pub struct Numeric(f64);
impl Numeric {
#[inline]
#[must_use]
pub fn new(value: f64) -> Self {
Self(value)
}
#[inline]
#[must_use]
pub fn value(self) -> f64 {
self.0
}
}
impl fmt::Display for Numeric {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.0)
}
}
impl From<f64> for Numeric {
#[inline]
fn from(value: f64) -> Self {
Self(value)
}
}
impl From<Numeric> for f64 {
#[inline]
fn from(value: Numeric) -> Self {
value.0
}
}
impl FromStr for Numeric {
type Err = ParseEntryValueError;
#[inline]
fn from_str(s: &str) -> Result<Self, Self::Err> {
Self::try_from(s)
}
}
impl TryFrom<&str> for Numeric {
type Error = ParseEntryValueError;
#[inline]
fn try_from(s: &str) -> Result<Self, Self::Error> {
s.parse::<f64>()
.map(Self)
.map_err(|_| ParseEntryValueError::ParseNumeric)
}
}
impl TryFrom<String> for Numeric {
type Error = ParseEntryValueError;
#[inline]
fn try_from(s: String) -> Result<Self, Self::Error> {
Self::try_from(s.as_str())
}
}
#[derive(Default, Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Bool(bool);
impl Bool {
#[inline]
#[must_use]
pub fn new(value: bool) -> Self {
Self(value)
}
#[inline]
#[must_use]
pub fn value(self) -> bool {
self.0
}
}
impl fmt::Display for Bool {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.0)
}
}
impl From<bool> for Bool {
#[inline]
fn from(value: bool) -> Self {
Self(value)
}
}
impl From<Bool> for bool {
#[inline]
fn from(value: Bool) -> Self {
value.0
}
}
impl FromStr for Bool {
type Err = ParseEntryValueError;
#[inline]
fn from_str(s: &str) -> Result<Self, Self::Err> {
Self::try_from(s)
}
}
impl TryFrom<&str> for Bool {
type Error = ParseEntryValueError;
#[inline]
fn try_from(s: &str) -> Result<Self, Self::Error> {
s.parse::<bool>()
.map(Self)
.map_err(|_| ParseEntryValueError::ParseBool)
}
}
impl TryFrom<String> for Bool {
type Error = ParseEntryValueError;
#[inline]
fn try_from(s: String) -> Result<Self, Self::Error> {
Self::try_from(s.as_str())
}
}
impl<'a> TryFrom<&'a Entry> for &'a Bool {
type Error = ValueError;
fn try_from(entry: &'a Entry) -> Result<Self, Self::Error> {
match entry {
Entry::NoDisplay(value)
| Entry::Hidden(value)
| Entry::Terminal(value)
| Entry::DBusActivatable(value)
| Entry::StartupNotify(value)
| Entry::PrefersNonDefaultGPU(value)
| Entry::SingleMainWindow(value) => Ok(value),
entry => Err(ValueError(entry.value_type().to_string())),
}
}
}
impl<'a> TryFrom<&'a mut Entry> for &'a mut Bool {
type Error = MutationValueError;
fn try_from(entry: &'a mut Entry) -> Result<Self, Self::Error> {
match entry {
Entry::NoDisplay(value)
| Entry::Hidden(value)
| Entry::Terminal(value)
| Entry::DBusActivatable(value)
| Entry::StartupNotify(value)
| Entry::PrefersNonDefaultGPU(value)
| Entry::SingleMainWindow(value) => Ok(value),
entry => Err(MutationValueError(entry.value_type().to_string())),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct IconString(String);
impl IconString {
#[inline]
#[must_use]
pub fn as_str(&self) -> &str {
&self.0
}
#[inline]
#[must_use]
pub fn is_path(&self) -> bool {
self.0.starts_with('/')
}
#[inline]
#[must_use]
pub fn is_name(&self) -> bool {
!self.is_path()
}
#[inline]
#[must_use]
pub fn into_string(self) -> String {
self.0
}
}
impl AsRef<str> for IconString {
fn as_ref(&self) -> &str {
&self.0
}
}
impl fmt::Display for IconString {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.0)
}
}
impl std::ops::Deref for IconString {
type Target = str;
fn deref(&self) -> &str {
&self.0
}
}
impl From<IconString> for String {
fn from(value: IconString) -> Self {
value.0
}
}
impl std::str::FromStr for IconString {
type Err = ParseEntryValueError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
Self::try_from(s)
}
}
impl TryFrom<&str> for IconString {
type Error = ParseEntryValueError;
#[inline]
fn try_from(s: &str) -> Result<Self, Self::Error> {
validate_string(
s,
validate_no_control,
ParseEntryValueError::ParseIconString,
)?;
Ok(Self(s.to_owned()))
}
}
impl TryFrom<String> for IconString {
type Error = ParseEntryValueError;
fn try_from(s: String) -> Result<Self, Self::Error> {
validate_string(
&s,
validate_no_control,
ParseEntryValueError::ParseIconString,
)?;
Ok(Self(s))
}
}
impl<'a> TryFrom<&'a Entry> for &'a IconString {
type Error = ValueError;
fn try_from(entry: &'a Entry) -> Result<Self, Self::Error> {
match entry {
Entry::Icon(value) => Ok(value),
entry => Err(ValueError(entry.value_type().to_string())),
}
}
}
impl<'a> TryFrom<&'a mut Entry> for &'a mut IconString {
type Error = MutationValueError;
fn try_from(entry: &'a mut Entry) -> Result<Self, Self::Error> {
match entry {
Entry::Icon(value) => Ok(value),
entry => Err(MutationValueError(entry.value_type().to_string())),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct EscapedString(String);
impl EscapedString {
#[inline]
#[must_use]
pub fn as_str(&self) -> &str {
&self.0
}
#[inline]
#[must_use]
pub fn into_string(self) -> String {
self.0
}
}
impl AsRef<str> for EscapedString {
fn as_ref(&self) -> &str {
&self.0
}
}
impl fmt::Display for EscapedString {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.0)
}
}
impl std::ops::Deref for EscapedString {
type Target = str;
fn deref(&self) -> &str {
&self.0
}
}
impl From<EscapedString> for String {
fn from(value: EscapedString) -> Self {
value.0
}
}
impl std::str::FromStr for EscapedString {
type Err = ParseEntryValueError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
Self::try_from(s)
}
}
impl TryFrom<&str> for EscapedString {
type Error = ParseEntryValueError;
#[inline]
fn try_from(s: &str) -> Result<Self, Self::Error> {
validate_string(
s,
validate_ascii_no_control,
ParseEntryValueError::ParseEscapedString,
)?;
Ok(Self(s.to_owned()))
}
}
impl TryFrom<String> for EscapedString {
type Error = ParseEntryValueError;
fn try_from(s: String) -> Result<Self, Self::Error> {
validate_string(
&s,
validate_ascii_no_control,
ParseEntryValueError::ParseEscapedString,
)?;
Ok(Self(s))
}
}
impl<'a> TryFrom<&'a Entry> for &'a EscapedString {
type Error = ValueError;
fn try_from(entry: &'a Entry) -> Result<Self, Self::Error> {
match entry {
Entry::Exec(value)
| Entry::TryExec(value)
| Entry::Path(value)
| Entry::StartupWMClass(value)
| Entry::URL(value) => Ok(value),
entry => Err(ValueError(entry.value_type().to_string())),
}
}
}
impl<'a> TryFrom<&'a mut Entry> for &'a mut EscapedString {
type Error = MutationValueError;
fn try_from(entry: &'a mut Entry) -> Result<Self, Self::Error> {
match entry {
Entry::Exec(value)
| Entry::TryExec(value)
| Entry::Path(value)
| Entry::StartupWMClass(value)
| Entry::URL(value) => Ok(value),
entry => Err(MutationValueError(entry.value_type().to_string())),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Default, Hash)]
pub struct LocaleString(String);
impl LocaleString {
#[inline]
#[must_use]
pub fn as_str(&self) -> &str {
&self.0
}
#[inline]
#[must_use]
pub fn into_string(self) -> String {
self.0
}
}
impl AsRef<str> for LocaleString {
fn as_ref(&self) -> &str {
&self.0
}
}
impl fmt::Display for LocaleString {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.0)
}
}
impl std::ops::Deref for LocaleString {
type Target = str;
fn deref(&self) -> &str {
&self.0
}
}
impl From<LocaleString> for String {
fn from(value: LocaleString) -> Self {
value.0
}
}
impl std::str::FromStr for LocaleString {
type Err = ParseEntryValueError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
Self::try_from(s)
}
}
impl TryFrom<&str> for LocaleString {
type Error = ParseEntryValueError;
#[inline]
fn try_from(s: &str) -> Result<Self, Self::Error> {
validate_string(
s,
validate_no_control,
ParseEntryValueError::ParseLocaleString,
)?;
Ok(Self(s.to_owned()))
}
}
impl TryFrom<String> for LocaleString {
type Error = ParseEntryValueError;
fn try_from(s: String) -> Result<Self, Self::Error> {
validate_string(
&s,
validate_no_control,
ParseEntryValueError::ParseLocaleString,
)?;
Ok(Self(s))
}
}
impl<'a> TryFrom<&'a Entry> for &'a LocaleString {
type Error = ValueError;
fn try_from(entry: &'a Entry) -> Result<Self, Self::Error> {
let error = ValueError(entry.value_type().to_string());
match entry {
Entry::Name(value) | Entry::GenericName(value) | Entry::Comment(value) => Ok(value),
Entry::Localized(localized) => match &localized.value {
LocalizedValue::Localized(value) => Ok(value),
LocalizedValue::LocalizedKeywords(_) => Err(error),
},
_ => Err(error),
}
}
}
impl<'a> TryFrom<&'a mut Entry> for &'a mut LocaleString {
type Error = MutationValueError;
fn try_from(entry: &'a mut Entry) -> Result<Self, Self::Error> {
let error = MutationValueError(entry.value_type().to_string());
match entry {
Entry::Name(value) | Entry::GenericName(value) | Entry::Comment(value) => Ok(value),
Entry::Localized(localized) => match &mut localized.value {
LocalizedValue::Localized(value) => Ok(value),
LocalizedValue::LocalizedKeywords(_) => Err(error),
},
_ => Err(error),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Default, Hash)]
pub struct EscapedStrings(Vec<EscapedString>);
impl EscapedStrings {
#[inline]
#[must_use]
pub fn new(list: Vec<EscapedString>) -> Self {
Self(list)
}
#[inline]
#[must_use]
pub fn as_slice(&self) -> &[EscapedString] {
&self.0
}
#[inline]
pub fn push(&mut self, item: EscapedString) {
self.0.push(item);
}
pub fn iter(&self) -> std::slice::Iter<'_, EscapedString> {
<&Self as IntoIterator>::into_iter(self)
}
}
impl AsRef<[EscapedString]> for EscapedStrings {
fn as_ref(&self) -> &[EscapedString] {
&self.0
}
}
impl fmt::Display for EscapedStrings {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
for value in &self.0 {
for c in value.chars() {
if c == ';' {
f.write_str("\\")?;
}
write!(f, "{c}")?;
}
f.write_str(";")?;
}
Ok(())
}
}
impl std::ops::Deref for EscapedStrings {
type Target = [EscapedString];
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl From<Vec<EscapedString>> for EscapedStrings {
fn from(value: Vec<EscapedString>) -> Self {
Self(value)
}
}
impl FromIterator<EscapedString> for EscapedStrings {
fn from_iter<I>(iter: I) -> Self
where
I: IntoIterator<Item = EscapedString>,
{
Self(iter.into_iter().collect())
}
}
impl FromStr for EscapedStrings {
type Err = ParseEntryValueError;
fn from_str(strings: &str) -> Result<Self, Self::Err> {
Self::try_from(strings)
}
}
impl TryFrom<&str> for EscapedStrings {
type Error = ParseEntryValueError;
fn try_from(list: &str) -> Result<Self, Self::Error> {
Ok(Self(split_semicolon_list::<EscapedString>(
list,
ParseEntryValueError::ParseEscapedStrings,
)?))
}
}
impl TryFrom<String> for EscapedStrings {
type Error = ParseEntryValueError;
#[inline]
fn try_from(value: String) -> Result<Self, Self::Error> {
Self::try_from(value.as_str())
}
}
impl<'a> TryFrom<&'a Entry> for &'a EscapedStrings {
type Error = ValueError;
fn try_from(entry: &'a Entry) -> Result<Self, Self::Error> {
match entry {
Entry::OnlyShowIn(value)
| Entry::NotShowIn(value)
| Entry::Actions(value)
| Entry::Categories(value)
| Entry::MimeType(value)
| Entry::Implements(value) => Ok(value),
entry => Err(ValueError(entry.value_type().to_string())),
}
}
}
impl<'a> TryFrom<&'a mut Entry> for &'a mut EscapedStrings {
type Error = MutationValueError;
fn try_from(entry: &'a mut Entry) -> Result<Self, Self::Error> {
match entry {
Entry::OnlyShowIn(value)
| Entry::NotShowIn(value)
| Entry::Categories(value)
| Entry::MimeType(value)
| Entry::Implements(value) => Ok(value),
entry => Err(MutationValueError(entry.value_type().to_string())),
}
}
}
impl<'a> Extend<&'a EscapedString> for EscapedStrings {
fn extend<I>(&mut self, iter: I)
where
I: IntoIterator<Item = &'a EscapedString>,
{
self.0.extend(iter.into_iter().cloned());
}
}
impl Extend<EscapedString> for EscapedStrings {
fn extend<I>(&mut self, iter: I)
where
I: IntoIterator<Item = EscapedString>,
{
self.0.extend(iter);
}
}
impl IntoIterator for EscapedStrings {
type Item = EscapedString;
type IntoIter = std::vec::IntoIter<EscapedString>;
fn into_iter(self) -> Self::IntoIter {
self.0.into_iter()
}
}
impl<'a> IntoIterator for &'a EscapedStrings {
type Item = &'a EscapedString;
type IntoIter = std::slice::Iter<'a, EscapedString>;
fn into_iter(self) -> Self::IntoIter {
self.0.iter()
}
}
impl std::ops::Index<usize> for EscapedStrings {
type Output = EscapedString;
fn index(&self, index: usize) -> &Self::Output {
&self.0[index]
}
}
impl std::ops::IndexMut<usize> for EscapedStrings {
fn index_mut(&mut self, index: usize) -> &mut Self::Output {
&mut self.0[index]
}
}
#[derive(Debug, Clone, PartialEq, Eq, Default, Hash)]
pub struct LocaleStrings(Vec<LocaleString>);
impl LocaleStrings {
#[inline]
#[must_use]
pub fn new(list: Vec<LocaleString>) -> Self {
Self(list)
}
#[inline]
#[must_use]
pub fn as_slice(&self) -> &[LocaleString] {
&self.0
}
#[inline]
pub fn push(&mut self, item: LocaleString) {
self.0.push(item);
}
pub fn iter(&self) -> std::slice::Iter<'_, LocaleString> {
<&Self as IntoIterator>::into_iter(self)
}
}
impl AsRef<[LocaleString]> for LocaleStrings {
fn as_ref(&self) -> &[LocaleString] {
&self.0
}
}
impl fmt::Display for LocaleStrings {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
for value in &self.0 {
for c in value.chars() {
if c == ';' {
f.write_str("\\")?;
}
write!(f, "{c}")?;
}
f.write_str(";")?;
}
Ok(())
}
}
impl std::ops::Deref for LocaleStrings {
type Target = [LocaleString];
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl FromIterator<LocaleString> for LocaleStrings {
fn from_iter<I>(iter: I) -> Self
where
I: IntoIterator<Item = LocaleString>,
{
Self(iter.into_iter().collect())
}
}
impl From<Vec<LocaleString>> for LocaleStrings {
fn from(value: Vec<LocaleString>) -> Self {
Self(value)
}
}
impl FromStr for LocaleStrings {
type Err = ParseEntryValueError;
fn from_str(strings: &str) -> Result<Self, Self::Err> {
Self::try_from(strings)
}
}
impl TryFrom<&str> for LocaleStrings {
type Error = ParseEntryValueError;
fn try_from(list: &str) -> Result<Self, Self::Error> {
Ok(Self(split_semicolon_list::<LocaleString>(
list,
ParseEntryValueError::ParseLocaleStrings,
)?))
}
}
impl TryFrom<String> for LocaleStrings {
type Error = ParseEntryValueError;
#[inline]
fn try_from(value: String) -> Result<Self, Self::Error> {
Self::try_from(value.as_str())
}
}
impl<'a> TryFrom<&'a Entry> for &'a LocaleStrings {
type Error = ValueError;
fn try_from(entry: &'a Entry) -> Result<Self, Self::Error> {
let error = ValueError(entry.value_type().to_string());
match entry {
Entry::Keywords(value) => Ok(value),
Entry::Localized(localized) => match &localized.value {
LocalizedValue::LocalizedKeywords(value) => Ok(value),
LocalizedValue::Localized(_) => Err(error),
},
_ => Err(error),
}
}
}
impl<'a> TryFrom<&'a mut Entry> for &'a mut LocaleStrings {
type Error = MutationValueError;
fn try_from(entry: &'a mut Entry) -> Result<Self, Self::Error> {
let error = MutationValueError(entry.value_type().to_string());
match entry {
Entry::Keywords(value) => Ok(value),
Entry::Localized(localized) => match &mut localized.value {
LocalizedValue::LocalizedKeywords(value) => Ok(value),
LocalizedValue::Localized(_) => Err(error),
},
_ => Err(error),
}
}
}
impl Extend<LocaleString> for LocaleStrings {
fn extend<I>(&mut self, iter: I)
where
I: IntoIterator<Item = LocaleString>,
{
self.0.extend(iter);
}
}
impl<'a> Extend<&'a LocaleString> for LocaleStrings {
fn extend<I>(&mut self, iter: I)
where
I: IntoIterator<Item = &'a LocaleString>,
{
self.0.extend(iter.into_iter().cloned());
}
}
impl<'a> IntoIterator for &'a LocaleStrings {
type Item = &'a LocaleString;
type IntoIter = std::slice::Iter<'a, LocaleString>;
fn into_iter(self) -> Self::IntoIter {
self.0.iter()
}
}
impl IntoIterator for LocaleStrings {
type Item = LocaleString;
type IntoIter = std::vec::IntoIter<LocaleString>;
fn into_iter(self) -> Self::IntoIter {
self.0.into_iter()
}
}
impl std::ops::Index<usize> for LocaleStrings {
type Output = LocaleString;
fn index(&self, index: usize) -> &Self::Output {
&self.0[index]
}
}
impl std::ops::IndexMut<usize> for LocaleStrings {
fn index_mut(&mut self, index: usize) -> &mut Self::Output {
&mut self.0[index]
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum LocalizedValue {
Localized(LocaleString),
LocalizedKeywords(LocaleStrings),
}
impl fmt::Display for LocalizedValue {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Localized(value) => write!(f, "{value}"),
Self::LocalizedKeywords(value) => write!(f, "{value}"),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Default, Hash)]
pub struct ExtensionValue(String);
impl ExtensionValue {
#[inline]
#[must_use]
pub fn as_str(&self) -> &str {
&self.0
}
#[inline]
#[must_use]
pub fn into_string(self) -> String {
self.0
}
}
impl AsRef<str> for ExtensionValue {
fn as_ref(&self) -> &str {
&self.0
}
}
impl std::ops::Deref for ExtensionValue {
type Target = str;
fn deref(&self) -> &str {
&self.0
}
}
impl fmt::Display for ExtensionValue {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.0)
}
}
impl From<ExtensionValue> for String {
fn from(value: ExtensionValue) -> Self {
value.0
}
}
impl std::str::FromStr for ExtensionValue {
type Err = ParseEntryValueError;
fn from_str(value: &str) -> Result<Self, Self::Err> {
Self::try_from(value.to_owned())
}
}
impl TryFrom<&str> for ExtensionValue {
type Error = ParseEntryValueError;
#[inline]
fn try_from(value: &str) -> Result<Self, Self::Error> {
Self::try_from(value.to_owned())
}
}
impl TryFrom<String> for ExtensionValue {
type Error = ParseEntryValueError;
fn try_from(value: String) -> Result<Self, Self::Error> {
if value.chars().any(char::is_control) {
return Err(ParseEntryValueError::ParseExtensionString);
}
Ok(Self(value))
}
}
impl<'a> TryFrom<&'a Entry> for &'a ExtensionValue {
type Error = ValueError;
fn try_from(entry: &'a Entry) -> Result<Self, Self::Error> {
match entry {
Entry::Extension(extension) => Ok(&extension.value),
entry => Err(ValueError(entry.value_type().to_string())),
}
}
}
impl<'a> TryFrom<&'a mut Entry> for &'a mut ExtensionValue {
type Error = MutationValueError;
fn try_from(entry: &'a mut Entry) -> Result<Self, Self::Error> {
match entry {
Entry::Extension(extension) => Ok(&mut extension.value),
entry => Err(MutationValueError(entry.value_type().to_string())),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct LocalizedEntry {
key: EntryKeys,
locale: Locale,
pub(crate) value: LocalizedValue,
}
impl LocalizedEntry {
pub fn try_new(
key: EntryKeys,
locale: Locale,
value: LocalizedValue,
) -> Result<Self, ParseEntryError> {
if key.localizable_key().is_none() {
return Err(ParseEntryError::ParseKey(ParseKeyError::NotLocalizable));
}
match (key, &value) {
(EntryKeys::Keywords, LocalizedValue::LocalizedKeywords(_))
| (
EntryKeys::Name | EntryKeys::GenericName | EntryKeys::Comment | EntryKeys::Icon,
LocalizedValue::Localized(_),
) => {}
(EntryKeys::Keywords, _) => {
return Err(ParseEntryError::ParseValue(
ParseEntryValueError::ParseLocaleStrings,
));
}
_ => {
return Err(ParseEntryError::ParseValue(
ParseEntryValueError::ParseLocaleString,
));
}
}
Ok(Self { key, locale, value })
}
#[inline]
#[must_use]
pub fn key(&self) -> EntryKeys {
self.key
}
#[inline]
#[must_use]
pub fn locale(&self) -> &Locale {
&self.locale
}
#[inline]
#[must_use]
pub fn value(&self) -> &LocalizedValue {
&self.value
}
}
impl TryFrom<(&str, &str)> for LocalizedEntry {
type Error = ParseEntryError;
fn try_from((key, value): (&str, &str)) -> Result<Self, Self::Error> {
let (base_key, locale) = split_localized_key(key)?;
let value = match base_key {
EntryKeys::Keywords => LocalizedValue::LocalizedKeywords(
value.parse().map_err(ParseEntryError::ParseValue)?,
),
_ => LocalizedValue::Localized(value.parse().map_err(ParseEntryError::ParseValue)?),
};
LocalizedEntry::try_new(base_key, locale.parse()?, value)
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ExtensionEntry {
key: String,
pub(crate) value: ExtensionValue,
}
impl ExtensionEntry {
#[inline]
#[must_use]
pub fn key(&self) -> &str {
&self.key
}
#[inline]
#[must_use]
pub fn value(&self) -> &str {
&self.value
}
}
impl TryFrom<(&str, &str)> for ExtensionEntry {
type Error = ParseEntryError;
fn try_from((key, value): (&str, &str)) -> Result<Self, Self::Error> {
if !is_valid_extension_key(key) {
return Err(ParseEntryError::ParseKey(
ParseKeyError::InvalidExtensionKey,
));
}
Ok(Self {
key: key.to_owned(),
value: ExtensionValue::try_from(value)?,
})
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Locale(String);
impl Locale {
#[inline]
pub fn try_new(locale: impl AsRef<str>) -> Result<Self, ParseKeyError> {
locale.as_ref().parse()
}
#[inline]
#[must_use]
pub fn as_str(&self) -> &str {
&self.0
}
}
impl FromStr for Locale {
type Err = ParseKeyError;
fn from_str(locale: &str) -> Result<Self, Self::Err> {
if !is_valid_locale_suffix(locale) {
return Err(ParseKeyError::InvalidLocale);
}
Ok(Self(locale.to_owned()))
}
}
impl AsRef<str> for Locale {
#[inline]
fn as_ref(&self) -> &str {
self.as_str()
}
}
impl fmt::Display for Locale {
#[inline]
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.0)
}
}
fn validate_string(
s: &str,
validate_characters: fn(&str, ParseEntryValueError) -> Result<(), ParseEntryValueError>,
error: ParseEntryValueError,
) -> Result<(), ParseEntryValueError> {
validate_characters(s, error)?;
validate_escape_sequences_string(s, error)
}
fn validate_ascii_no_control(
s: &str,
error: ParseEntryValueError,
) -> Result<(), ParseEntryValueError> {
if s.chars().all(|c| c.is_ascii() && !c.is_ascii_control()) {
Ok(())
} else {
Err(error)
}
}
fn validate_no_control(s: &str, error: ParseEntryValueError) -> Result<(), ParseEntryValueError> {
if s.chars().any(char::is_control) {
Err(error)
} else {
Ok(())
}
}
fn validate_escape_sequences_string(
s: &str,
error: ParseEntryValueError,
) -> Result<(), ParseEntryValueError> {
let mut chars = s.chars();
while let Some(c) = chars.next() {
if c != '\\' {
continue;
}
match chars.next() {
Some('s' | 'n' | 't' | 'r' | '\\') => {}
_ => return Err(error),
}
}
Ok(())
}
pub fn split_semicolon_list<T>(
s: &str,
error: ParseEntryValueError,
) -> Result<Vec<T>, ParseEntryValueError>
where
T: TryFrom<String, Error = ParseEntryValueError>,
{
if s.is_empty() {
return Ok(Vec::new());
}
let mut values = Vec::new();
let mut current = String::new();
let mut chars = s.chars();
while let Some(c) = chars.next() {
match c {
'\\' => match chars.next() {
Some(c) => {
if c != ';' {
current.push('\\');
}
current.push(c);
}
None => return Err(error),
},
';' => {
values.push(T::try_from(std::mem::take(&mut current))?);
}
_ => current.push(c),
}
}
if !current.is_empty() {
values.push(T::try_from(current)?);
}
Ok(values)
}
fn is_valid_key_token(value: &str) -> bool {
!value.is_empty()
&& value
.bytes()
.all(|byte| byte.is_ascii_alphanumeric() || byte == b'-')
}
pub(crate) fn is_valid_extension_key(key: &str) -> bool {
let Some(token) = key.strip_prefix("X-") else {
return false;
};
if !is_valid_key_token(token) {
return false;
}
!token.ends_with('-')
}
fn is_valid_locale_component(locale: &str, start: usize, end: usize, dot_ok: bool) -> bool {
if start == end {
return false;
}
locale[start..end]
.bytes()
.all(|byte| byte.is_ascii_alphanumeric() || byte == b'-' || (!dot_ok && byte == b'_'))
}
pub(crate) fn is_valid_locale_suffix(locale: &str) -> bool {
if locale.is_empty() {
return false;
}
let bytes = locale.as_bytes();
let len = bytes.len();
let mut idx = 0usize;
while idx < len && bytes[idx].is_ascii_alphabetic() {
idx += 1;
}
if idx == 0 {
return false;
}
if idx < len && bytes[idx] == b'_' {
let start = idx + 1;
idx = start;
while idx < len
&& bytes[idx] != b'.'
&& bytes[idx] != b'@'
&& bytes[idx] != b'_'
&& bytes[idx] != b']'
{
idx += 1;
}
if !is_valid_locale_component(locale, start, idx, false) {
return false;
}
}
if idx < len && bytes[idx] == b'.' {
let start = idx + 1;
idx = start;
while idx < len && bytes[idx] != b'@' && bytes[idx] != b'.' {
idx += 1;
}
if !is_valid_locale_component(locale, start, idx, true) {
return false;
}
}
if idx < len && bytes[idx] == b'@' {
let start = idx + 1;
idx = len;
if !is_valid_locale_component(locale, start, len, true) {
return false;
}
}
idx == len
}
pub(crate) fn split_localized_key(key: &str) -> Result<(EntryKeys, &str), ParseKeyError> {
let open = key.find('[').ok_or(ParseKeyError::InvalidLocale)?;
let close = key.rfind(']').ok_or(ParseKeyError::InvalidLocale)?;
if !key.ends_with(']') || close <= open {
return Err(ParseKeyError::InvalidLocale);
}
let base =
EntryKeys::parse_localizable_key(&key[..open]).ok_or(ParseKeyError::NotLocalizable)?;
let locale = &key[open + 1..close];
if !is_valid_locale_suffix(locale) {
return Err(ParseKeyError::InvalidLocale);
}
Ok((base, locale))
}
#[cfg(test)]
mod tests {
use super::*;
mod escaped {
use super::*;
mod string {
use super::*;
#[test]
fn construct_wrapper_type_ok() {
assert!(EscapedString::try_from("Firefox\\n browser").is_ok());
assert_eq!(
EscapedString::try_from("Firefox\\s").unwrap(),
EscapedString("Firefox\\s".to_string())
);
assert_eq!(
EscapedString::try_from("Firefox\\n").unwrap(),
EscapedString("Firefox\\n".to_string())
);
assert_eq!(
EscapedString::try_from("Firefox\\t").unwrap(),
EscapedString("Firefox\\t".to_string())
);
assert_eq!(
EscapedString::try_from("Firefox\\r").unwrap(),
EscapedString("Firefox\\r".to_string())
);
assert_eq!(
EscapedString::try_from("Firefox\\\\").unwrap(),
EscapedString("Firefox\\\\".to_string())
);
}
#[test]
fn construct_wrapper_type_err() {
assert!(EscapedString::try_from("Müller").is_err());
assert!(EscapedString::try_from("Firefox\\").is_err());
assert!(EscapedString::try_from("A\\q").is_err());
}
}
mod strings {
use super::*;
#[test]
fn construct_wrapper_type_ok() {
let original = r"Edit\;value;Clone;Copy;";
let parsed = EscapedStrings::try_from(original).unwrap();
assert_eq!(parsed.to_string(), original);
let parsed = EscapedStrings::try_from(r"Edit\;Test;Copy;Clone");
assert_eq!(
parsed,
EscapedStrings::try_from(parsed.clone().unwrap().to_string())
);
assert_eq!(
EscapedStrings::try_from(r"Edit\;Test;Copy;Clone;"),
Ok(EscapedStrings(vec![
EscapedString(r"Edit;Test".to_string()),
EscapedString("Copy".to_string()),
EscapedString("Clone".to_string())
])),
);
assert_eq!(
EscapedStrings::try_from(
"application/x-cambalache-project;application/x-gtk-builder;application/x-glade;",
),
Ok(EscapedStrings(vec![
EscapedString("application/x-cambalache-project".to_string()),
EscapedString("application/x-gtk-builder".to_string()),
EscapedString("application/x-glade".to_string())
])),
);
}
}
mod helper {
use super::*;
fn split_semicolon_list_escaped(
value: &str,
) -> Result<Vec<EscapedString>, ParseEntryValueError> {
split_semicolon_list::<EscapedString>(
value,
ParseEntryValueError::ParseEscapedStrings,
)
}
#[test]
fn split_semicolon_list_ok() {
assert_eq!(split_semicolon_list_escaped(""), Ok(vec![]));
assert_eq!(
split_semicolon_list_escaped("Edit\\;value;Clone;Copy"),
Ok(vec![
EscapedString("Edit;value".to_string()),
EscapedString("Clone".to_string()),
EscapedString("Copy".to_string())
]),
);
assert_eq!(
split_semicolon_list_escaped("GTK;Utility;"),
Ok(vec![
EscapedString("GTK".to_string()),
EscapedString("Utility".to_string())
]),
);
assert_eq!(
split_semicolon_list_escaped("\\;;Copy"),
Ok(vec![
EscapedString(";".to_string()),
EscapedString("Copy".to_string())
]),
);
assert_eq!(
split_semicolon_list_escaped("\\;;"),
Ok(vec![EscapedString(";".to_string())]),
);
assert_eq!(
split_semicolon_list_escaped("\\;"),
Ok(vec![EscapedString(";".to_string())]),
);
assert_eq!(
split_semicolon_list_escaped(";"),
Ok(vec![EscapedString("".to_string())]),
);
assert_eq!(
split_semicolon_list_escaped(";;"),
Ok(vec![
EscapedString("".to_string()),
EscapedString("".to_string())
]),
);
assert_eq!(
split_semicolon_list_escaped("A\\;B\\;C;D"),
Ok(vec![
EscapedString("A;B;C".into()),
EscapedString("D".into()),
]),
);
assert_eq!(
split_semicolon_list_escaped("A;;B"),
Ok(vec![
EscapedString("A".into()),
EscapedString("".into()),
EscapedString("B".into()),
]),
);
assert_eq!(
split_semicolon_list_escaped(";A"),
Ok(vec![EscapedString("".into()), EscapedString("A".into()),]),
);
}
#[test]
fn split_semicolon_list_err() {
assert!(split_semicolon_list_escaped("Café").is_err());
assert!(split_semicolon_list_escaped("Edit\\q").is_err());
assert!(split_semicolon_list_escaped("Edit\\").is_err());
assert!(split_semicolon_list_escaped("Edit\\x;Copy").is_err());
assert!(split_semicolon_list_escaped("Café").is_err());
}
}
}
mod locale {
use super::*;
mod string {}
mod strings {
use super::*;
#[test]
fn construct_wrapper_type() {
assert!(LocaleString::try_from("Café").is_ok());
assert_eq!(
LocaleString::try_from("Café"),
Ok(LocaleString("Café".to_string()))
);
}
}
mod helper {
use super::*;
fn split_semicolon_list_locale(
value: &str,
) -> Result<Vec<LocaleString>, ParseEntryValueError> {
split_semicolon_list::<LocaleString>(
value,
ParseEntryValueError::ParseLocaleStrings,
)
}
#[test]
fn split_semicolon_list_ok() {
assert_eq!(
split_semicolon_list_locale("Café"),
Ok(vec![LocaleString("Café".to_string())]),
);
let list = split_semicolon_list_locale("Café").unwrap();
assert_eq!(list.len(), 1);
assert_eq!(list[0].to_string(), "Café");
let result = split_semicolon_list_locale("Müller\\;Spiele;Unterhaltung;");
assert!(result.is_ok());
let vec = result.unwrap();
assert_eq!(vec.len(), 2);
assert_eq!(vec[0].as_str(), "Müller;Spiele");
assert_eq!(vec[1].as_str(), "Unterhaltung");
}
}
}
mod key {
use super::*;
#[test]
fn from_str_empty_string_returns_parse_key_error_with_original() {
assert_eq!(EntryKeys::from_str(""), Err(ParseKeyError::NonStandardKey));
}
#[test]
fn from_str_unknown_key_returns_parse_key_error_with_original() {
let result = EntryKeys::from_str("UnknownKey");
assert_eq!(result, Err(ParseKeyError::NonStandardKey));
}
#[test]
fn split_localized() {
assert_eq!(split_localized_key("Name[de]"), Ok((EntryKeys::Name, "de")));
assert_eq!(
split_localized_key("Name"),
Err(ParseKeyError::InvalidLocale)
);
assert_eq!(
split_localized_key("Exec[de]"),
Err(ParseKeyError::NotLocalizable)
); }
#[test]
fn extension_key_validation_accepts_valid_examples() {
assert!(is_valid_extension_key("X-Test"));
assert!(is_valid_extension_key("X-GNOME-FullName"));
assert!(is_valid_extension_key("X-KDE-Submenu"));
assert!(is_valid_extension_key("X-MyCompany-Feature"));
}
#[test]
fn extension_key_validation_rejects_invalid_examples() {
assert!(!is_valid_extension_key("X-"));
assert!(!is_valid_extension_key("X-foo bar"));
assert!(!is_valid_extension_key("X-!!!"));
assert!(is_valid_extension_key("X-abc"));
}
#[test]
fn locale_suffix_validation_accepts_valid_examples() {
assert!(is_valid_locale_suffix("de"));
assert!(is_valid_locale_suffix("de_DE"));
assert!(is_valid_locale_suffix("de_DE.UTF-8"));
assert!(is_valid_locale_suffix("de_DE@euro"));
assert!(is_valid_locale_suffix("de_DE.UTF-8@euro"));
}
#[test]
fn locale_suffix_validation_rejects_invalid_examples() {
assert!(!is_valid_locale_suffix(""));
assert!(!is_valid_locale_suffix("!!!"));
assert!(!is_valid_locale_suffix("de DE"));
assert!(!is_valid_locale_suffix("de][bad"));
assert!(!is_valid_locale_suffix("de@"));
assert!(!is_valid_locale_suffix("_DE"));
assert!(!is_valid_locale_suffix("de."));
assert!(!is_valid_locale_suffix("de.UTF-8.UTF-16"));
}
#[test]
fn split_localized_key_accepts_valid_localized_examples() {
assert_eq!(
split_localized_key("Name[de_DE.UTF-8@euro]"),
Ok((EntryKeys::Name, "de_DE.UTF-8@euro"))
);
assert_eq!(
split_localized_key("Comment[de_DE]"),
Ok((EntryKeys::Comment, "de_DE"))
);
}
#[test]
fn split_localized_key_rejects_invalid_localized_examples() {
assert_eq!(
split_localized_key("Name[]"),
Err(ParseKeyError::InvalidLocale)
);
assert_eq!(
split_localized_key("Name[!!!]"),
Err(ParseKeyError::InvalidLocale)
);
assert_eq!(
split_localized_key("Name[de DE]"),
Err(ParseKeyError::InvalidLocale)
);
assert_eq!(
split_localized_key("Name[de][bad]"),
Err(ParseKeyError::InvalidLocale)
);
assert_eq!(
split_localized_key("Name[de@]"),
Err(ParseKeyError::InvalidLocale)
);
assert_eq!(
split_localized_key("Name[_DE]"),
Err(ParseKeyError::InvalidLocale)
);
assert_eq!(
split_localized_key("Name[de.]"),
Err(ParseKeyError::InvalidLocale)
);
assert_eq!(
split_localized_key("Name[de.UTF-8.UTF-16]"),
Err(ParseKeyError::InvalidLocale)
);
}
#[test]
fn locale_suffix_validation_rejects_duplicate_or_misordered_sections() {
assert!(!is_valid_locale_suffix("de__DE"));
assert!(!is_valid_locale_suffix("de@euro.UTF-8"));
assert!(!is_valid_locale_suffix("de.UTF-8_DE"));
assert!(!is_valid_locale_suffix("de_DE@euro@x"));
assert!(!is_valid_locale_suffix("de..UTF-8"));
}
}
mod version {
use super::*;
use std::collections::HashSet;
#[test]
fn test_version_excludes_contains_expected_keys() {
assert_eq!(VERSION_EXCLUDES.len(), 6);
assert!(VERSION_EXCLUDES.contains(&"DBusActivatable"));
assert!(VERSION_EXCLUDES.contains(&"Actions"));
assert!(VERSION_EXCLUDES.contains(&"Keywords"));
assert!(VERSION_EXCLUDES.contains(&"Implements"));
assert!(VERSION_EXCLUDES.contains(&"PrefersNonDefaultGPU"));
assert!(VERSION_EXCLUDES.contains(&"SingleMainWindow"));
}
#[test]
fn test_version_excludes_does_not_contain_v1_0_keys() {
let base_keys = [
"Type",
"Version",
"Name",
"GenericName",
"NoDisplay",
"Comment",
"Icon",
"Hidden",
"OnlyShowIn",
"NotShowIn",
"TryExec",
"Exec",
"Path",
"Terminal",
"MimeType",
"Categories",
"StartupNotify",
"StartupWMClass",
"URL",
];
for k in &base_keys {
assert!(
!VERSION_EXCLUDES.contains(k),
"{k} should not be in VERSION_EXCLUDES"
);
}
}
#[test]
fn test_entry_keys_display_all() {
for key_str in EntryKeys::KEYS {
let variant = EntryKeys::from_str(key_str).unwrap();
assert_eq!(format!("{variant}"), *key_str);
}
}
#[test]
fn test_entry_keys_from_str_roundtrip() {
for key_str in EntryKeys::KEYS {
let parsed = EntryKeys::from_str(key_str).unwrap();
assert_eq!(parsed.key(), *key_str);
}
}
#[test]
fn test_entry_keys_key_matches_keys_constant() {
let variants: [(EntryKeys, usize); 25] = [
(EntryKeys::Type, 0),
(EntryKeys::Version, 1),
(EntryKeys::Name, 2),
(EntryKeys::GenericName, 3),
(EntryKeys::NoDisplay, 4),
(EntryKeys::Comment, 5),
(EntryKeys::Icon, 6),
(EntryKeys::Hidden, 7),
(EntryKeys::OnlyShowIn, 8),
(EntryKeys::NotShowIn, 9),
(EntryKeys::DBusActivatable, 10),
(EntryKeys::TryExec, 11),
(EntryKeys::Exec, 12),
(EntryKeys::Path, 13),
(EntryKeys::Terminal, 14),
(EntryKeys::Actions, 15),
(EntryKeys::MimeType, 16),
(EntryKeys::Categories, 17),
(EntryKeys::Implements, 18),
(EntryKeys::Keywords, 19),
(EntryKeys::StartupNotify, 20),
(EntryKeys::StartupWMClass, 21),
(EntryKeys::URL, 22),
(EntryKeys::PrefersNonDefaultGPU, 23),
(EntryKeys::SingleMainWindow, 24),
];
for (variant, idx) in variants {
assert_eq!(variant.key(), EntryKeys::KEYS[idx]);
}
}
#[test]
fn test_entry_keys_constant_has_25_elements() {
assert_eq!(EntryKeys::KEYS.len(), 25);
}
#[test]
fn test_entry_keys_uniqueness_in_keys_constant() {
let set: HashSet<&str> = EntryKeys::KEYS.iter().copied().collect();
assert_eq!(set.len(), EntryKeys::KEYS.len());
}
#[test]
fn test_entry_keys_constant_first_and_last() {
assert_eq!(EntryKeys::KEYS[0], "Type");
assert_eq!(EntryKeys::KEYS[24], "SingleMainWindow");
}
#[test]
fn test_entry_keys_iter_len() {
let entry_keys = EntryKeys::all_keys();
assert_eq!(entry_keys.len(), 25);
}
#[test]
fn test_entry_keys_iter_next_len() {
let mut entry_keys = EntryKeys::all_keys();
let _ = entry_keys.next();
assert_eq!(entry_keys.len(), 24);
}
#[test]
fn test_entry_keys_test_iter_rev_collect() {
assert_eq!(
EntryKeys::all_keys().rev().collect::<Vec<_>>(),
EntryKeys::KEYS.iter().cloned().rev().collect::<Vec<_>>()
);
}
#[test]
fn test_entry_keys_test_iter_collect() {
assert_eq!(EntryKeys::all_keys().collect::<Vec<_>>(), EntryKeys::KEYS);
}
}
}