opsview/config/
fontawesomeicon.rs

1use crate::error::OpsviewConfigError;
2use serde::de::{self, MapAccess, Visitor};
3use serde::ser::SerializeStruct;
4use serde::{Deserialize, Deserializer, Serialize, Serializer};
5use std::fmt;
6use strum::IntoEnumIterator;
7use strum_macros::{AsRefStr, Display, EnumIter, EnumString, VariantNames};
8
9/// Represents a [FontAwesome](https://fontawesome.com/) icon in Opsview.
10///
11/// The `FontAwesomeIcon` enum is used to define FontAwesome icons in the Opsview system.
12/// It encapsulates the necessary information to identify and describe an FontAwesome icon.
13/// There is no API endpoint for managing FontAwesome icons, so this struct is only used as a
14/// component of other entities.
15///
16/// Icons are taken from the 4.5 version of the FontAwesome library.
17
18#[allow(missing_docs)]
19#[non_exhaustive] // More icons might be added in future releases of Opsview.
20#[derive(Clone, Debug, PartialEq, Eq, EnumString, VariantNames, AsRefStr, EnumIter, Display)]
21#[strum(serialize_all = "kebab-case")]
22pub enum FontAwesomeIcon {
23    #[strum(serialize = "500px")]
24    FiveHundredPx,
25    Adjust,
26    Adn,
27    AlignCenter,
28    AlignJustify,
29    AlignLeft,
30    AlignRight,
31    Amazon,
32    Ambulance,
33    Anchor,
34    Android,
35    Angellist,
36    AngleDoubleDown,
37    AngleDoubleLeft,
38    AngleDoubleRight,
39    AngleDoubleUp,
40    AngleDown,
41    AngleLeft,
42    AngleRight,
43    AngleUp,
44    Apple,
45    Archive,
46    AreaChart,
47    ArrowCircleDown,
48    ArrowCircleLeft,
49    ArrowCircleODown,
50    ArrowCircleOLeft,
51    ArrowCircleORight,
52    ArrowCircleOUp,
53    ArrowCircleRight,
54    ArrowCircleUp,
55    ArrowDown,
56    ArrowLeft,
57    ArrowRight,
58    ArrowUp,
59    Arrows,
60    ArrowsAlt,
61    ArrowsH,
62    ArrowsV,
63    Asterisk,
64    At,
65    Automobile,
66    Backward,
67    BalanceScale,
68    Ban,
69    Bank,
70    BarChart,
71    BarChartO,
72    Barcode,
73    Bars,
74    Battery0,
75    Battery1,
76    Battery2,
77    Battery3,
78    Battery4,
79    BatteryEmpty,
80    BatteryFull,
81    BatteryHalf,
82    BatteryQuarter,
83    BatteryThreeQuarters,
84    Bed,
85    Beer,
86    Behance,
87    BehanceSquare,
88    Bell,
89    BellO,
90    BellSlash,
91    BellSlashO,
92    Bicycle,
93    Binoculars,
94    BirthdayCake,
95    Bitbucket,
96    BitbucketSquare,
97    Bitcoin,
98    BlackTie,
99    Bluetooth,
100    BluetoothB,
101    Bold,
102    Bolt,
103    Bomb,
104    Book,
105    Bookmark,
106    BookmarkO,
107    Briefcase,
108    Btc,
109    Bug,
110    Building,
111    BuildingO,
112    Bullhorn,
113    Bullseye,
114    Bus,
115    Buysellads,
116    Cab,
117    Calculator,
118    Calendar,
119    CalendarCheckO,
120    CalendarMinusO,
121    CalendarO,
122    CalendarPlusO,
123    CalendarTimesO,
124    Camera,
125    CameraRetro,
126    Car,
127    CaretDown,
128    CaretLeft,
129    CaretRight,
130    CaretSquareODown,
131    CaretSquareOLeft,
132    CaretSquareORight,
133    CaretSquareOUp,
134    CaretUp,
135    CartArrowDown,
136    CartPlus,
137    Cc,
138    CcAmex,
139    CcDinersClub,
140    CcDiscover,
141    CcJcb,
142    CcMastercard,
143    CcPaypal,
144    CcStripe,
145    CcVisa,
146    Certificate,
147    Chain,
148    ChainBroken,
149    Check,
150    CheckCircle,
151    CheckCircleO,
152    CheckSquare,
153    CheckSquareO,
154    ChevronCircleDown,
155    ChevronCircleLeft,
156    ChevronCircleRight,
157    ChevronCircleUp,
158    ChevronDown,
159    ChevronLeft,
160    ChevronRight,
161    ChevronUp,
162    Child,
163    Chrome,
164    Circle,
165    CircleO,
166    CircleONotch,
167    CircleThin,
168    Clipboard,
169    ClockO,
170    Clone,
171    Close,
172    Cloud,
173    CloudDownload,
174    CloudUpload,
175    Cny,
176    Code,
177    CodeFork,
178    Codepen,
179    Codiepie,
180    Coffee,
181    Cog,
182    Cogs,
183    Columns,
184    Comment,
185    CommentO,
186    Commenting,
187    CommentingO,
188    Comments,
189    CommentsO,
190    Compass,
191    Compress,
192    Connectdevelop,
193    Contao,
194    Copy,
195    Copyright,
196    CreativeCommons,
197    CreditCard,
198    CreditCardAlt,
199    Crop,
200    Crosshairs,
201    Css3,
202    Cube,
203    Cubes,
204    Cut,
205    Cutlery,
206    Dashboard,
207    Dashcube,
208    Database,
209    Dedent,
210    Delicious,
211    Desktop,
212    Deviantart,
213    Diamond,
214    Digg,
215    Dollar,
216    DotCircleO,
217    Download,
218    Dribbble,
219    Dropbox,
220    Drupal,
221    Edge,
222    Edit,
223    Eject,
224    EllipsisH,
225    EllipsisV,
226    Empire,
227    Envelope,
228    EnvelopeO,
229    EnvelopeSquare,
230    Eraser,
231    Eur,
232    Euro,
233    Exchange,
234    Exclamation,
235    ExclamationCircle,
236    ExclamationTriangle,
237    Expand,
238    Expeditedssl,
239    ExternalLink,
240    ExternalLinkSquare,
241    Eye,
242    EyeSlash,
243    Eyedropper,
244    Facebook,
245    FacebookF,
246    FacebookOfficial,
247    FacebookSquare,
248    FastBackward,
249    FastForward,
250    Fax,
251    Feed,
252    Female,
253    FighterJet,
254    File,
255    FileArchiveO,
256    FileAudioO,
257    FileCodeO,
258    FileExcelO,
259    FileImageO,
260    FileMovieO,
261    FileO,
262    FilePdfO,
263    FilePhotoO,
264    FilePictureO,
265    FilePowerpointO,
266    FileSoundO,
267    FileText,
268    FileTextO,
269    FileVideoO,
270    FileWordO,
271    FileZipO,
272    FilesO,
273    Film,
274    Filter,
275    Fire,
276    FireExtinguisher,
277    Firefox,
278    Flag,
279    FlagCheckered,
280    FlagO,
281    Flash,
282    Flask,
283    Flickr,
284    FloppyO,
285    Folder,
286    FolderO,
287    FolderOpen,
288    FolderOpenO,
289    Font,
290    Fonticons,
291    FortAwesome,
292    Forumbee,
293    Forward,
294    Foursquare,
295    FrownO,
296    FutbolO,
297    Gamepad,
298    Gavel,
299    Gbp,
300    Ge,
301    Gear,
302    Gears,
303    Genderless,
304    GetPocket,
305    Gg,
306    GgCircle,
307    Gift,
308    Git,
309    GitSquare,
310    Github,
311    GithubAlt,
312    GithubSquare,
313    Gittip,
314    Glass,
315    Globe,
316    Google,
317    GooglePlus,
318    GooglePlusSquare,
319    GoogleWallet,
320    GraduationCap,
321    Gratipay,
322    Group,
323    HSquare,
324    HackerNews,
325    HandGrabO,
326    HandLizardO,
327    HandODown,
328    HandOLeft,
329    HandORight,
330    HandOUp,
331    HandPaperO,
332    HandPeaceO,
333    HandPointerO,
334    HandRockO,
335    HandScissorsO,
336    HandSpockO,
337    HandStopO,
338    Hashtag,
339    HddO,
340    Header,
341    Headphones,
342    Heart,
343    HeartO,
344    Heartbeat,
345    History,
346    Home,
347    HospitalO,
348    Hotel,
349    Hourglass,
350    Hourglass1,
351    Hourglass2,
352    Hourglass3,
353    HourglassEnd,
354    HourglassHalf,
355    HourglassO,
356    HourglassStart,
357    Houzz,
358    Html5,
359    ICursor,
360    Ils,
361    Image,
362    Inbox,
363    Indent,
364    Industry,
365    Info,
366    InfoCircle,
367    Inr,
368    Instagram,
369    Institution,
370    InternetExplorer,
371    Intersex,
372    Ioxhost,
373    Italic,
374    Joomla,
375    Jpy,
376    Jsfiddle,
377    Key,
378    KeyboardO,
379    Krw,
380    Language,
381    Laptop,
382    Lastfm,
383    LastfmSquare,
384    Leaf,
385    Leanpub,
386    Legal,
387    LemonO,
388    LevelDown,
389    LevelUp,
390    LifeBouy,
391    LifeBuoy,
392    LifeRing,
393    LifeSaver,
394    LightbulbO,
395    LineChart,
396    Link,
397    Linkedin,
398    LinkedinSquare,
399    Linux,
400    List,
401    ListAlt,
402    ListOl,
403    ListUl,
404    LocationArrow,
405    Lock,
406    LongArrowDown,
407    LongArrowLeft,
408    LongArrowRight,
409    LongArrowUp,
410    Magic,
411    Magnet,
412    MailForward,
413    MailReply,
414    MailReplyAll,
415    Male,
416    Map,
417    MapMarker,
418    MapO,
419    MapPin,
420    MapSigns,
421    Mars,
422    MarsDouble,
423    MarsStroke,
424    MarsStrokeH,
425    MarsStrokeV,
426    Maxcdn,
427    Meanpath,
428    Medium,
429    Medkit,
430    MehO,
431    Mercury,
432    Microphone,
433    MicrophoneSlash,
434    Minus,
435    MinusCircle,
436    MinusSquare,
437    MinusSquareO,
438    Mixcloud,
439    Mobile,
440    MobilePhone,
441    Modx,
442    Money,
443    MoonO,
444    MortarBoard,
445    Motorcycle,
446    MousePointer,
447    Music,
448    Navicon,
449    Neuter,
450    NewspaperO,
451    ObjectGroup,
452    ObjectUngroup,
453    Odnoklassniki,
454    OdnoklassnikiSquare,
455    Opencart,
456    Openid,
457    Opera,
458    OptinMonster,
459    Outdent,
460    Pagelines,
461    PaintBrush,
462    PaperPlane,
463    PaperPlaneO,
464    Paperclip,
465    Paragraph,
466    Paste,
467    Pause,
468    PauseCircle,
469    PauseCircleO,
470    Paw,
471    Paypal,
472    Pencil,
473    PencilSquare,
474    PencilSquareO,
475    Percent,
476    Phone,
477    PhoneSquare,
478    Photo,
479    PictureO,
480    PieChart,
481    PiedPiper,
482    PiedPiperAlt,
483    Pinterest,
484    PinterestP,
485    PinterestSquare,
486    Plane,
487    Play,
488    PlayCircle,
489    PlayCircleO,
490    Plug,
491    Plus,
492    PlusCircle,
493    PlusSquare,
494    PlusSquareO,
495    PowerOff,
496    Print,
497    ProductHunt,
498    PuzzlePiece,
499    Qq,
500    Qrcode,
501    Question,
502    QuestionCircle,
503    QuoteLeft,
504    QuoteRight,
505    Ra,
506    Random,
507    Rebel,
508    Recycle,
509    Reddit,
510    RedditAlien,
511    RedditSquare,
512    Refresh,
513    Registered,
514    Remove,
515    Renren,
516    Reorder,
517    Repeat,
518    Reply,
519    ReplyAll,
520    Retweet,
521    Rmb,
522    Road,
523    Rocket,
524    RotateLeft,
525    RotateRight,
526    Rouble,
527    Rss,
528    RssSquare,
529    Rub,
530    Ruble,
531    Rupee,
532    Safari,
533    Save,
534    Scissors,
535    Scribd,
536    Search,
537    SearchMinus,
538    SearchPlus,
539    Sellsy,
540    Send,
541    SendO,
542    Server,
543    Share,
544    ShareAlt,
545    ShareAltSquare,
546    ShareSquare,
547    ShareSquareO,
548    Shekel,
549    Sheqel,
550    Shield,
551    Ship,
552    Shirtsinbulk,
553    ShoppingBag,
554    ShoppingBasket,
555    ShoppingCart,
556    SignIn,
557    SignOut,
558    Signal,
559    Simplybuilt,
560    Sitemap,
561    Skyatlas,
562    Skype,
563    Slack,
564    Sliders,
565    Slideshare,
566    SmileO,
567    SoccerBallO,
568    Sort,
569    SortAlphaAsc,
570    SortAlphaDesc,
571    SortAmountAsc,
572    SortAmountDesc,
573    SortAsc,
574    SortDesc,
575    SortDown,
576    SortNumericAsc,
577    SortNumericDesc,
578    SortUp,
579    Soundcloud,
580    SpaceShuttle,
581    Spinner,
582    Spoon,
583    Spotify,
584    Square,
585    SquareO,
586    StackExchange,
587    StackOverflow,
588    Star,
589    StarHalf,
590    StarHalfEmpty,
591    StarHalfFull,
592    StarHalfO,
593    StarO,
594    Steam,
595    SteamSquare,
596    StepBackward,
597    StepForward,
598    Stethoscope,
599    StickyNote,
600    StickyNoteO,
601    Stop,
602    StopCircle,
603    StopCircleO,
604    StreetView,
605    Strikethrough,
606    Stumbleupon,
607    StumbleuponCircle,
608    Subscript,
609    Subway,
610    Suitcase,
611    SunO,
612    Superscript,
613    Support,
614    Table,
615    Tablet,
616    Tachometer,
617    Tag,
618    Tags,
619    Tasks,
620    Taxi,
621    Television,
622    TencentWeibo,
623    Terminal,
624    TextHeight,
625    TextWidth,
626    Th,
627    ThLarge,
628    ThList,
629    ThumbTack,
630    ThumbsDown,
631    ThumbsODown,
632    ThumbsOUp,
633    ThumbsUp,
634    Ticket,
635    Times,
636    TimesCircle,
637    TimesCircleO,
638    Tint,
639    ToggleDown,
640    ToggleLeft,
641    ToggleOff,
642    ToggleOn,
643    ToggleRight,
644    ToggleUp,
645    Trademark,
646    Train,
647    Transgender,
648    TransgenderAlt,
649    Trash,
650    TrashO,
651    Tree,
652    Trello,
653    Tripadvisor,
654    Trophy,
655    Truck,
656    Try,
657    Tty,
658    Tumblr,
659    TumblrSquare,
660    TurkishLira,
661    Tv,
662    Twitch,
663    Twitter,
664    TwitterSquare,
665    Umbrella,
666    Underline,
667    Undo,
668    University,
669    Unlink,
670    Unlock,
671    UnlockAlt,
672    Unsorted,
673    Upload,
674    Usb,
675    Usd,
676    User,
677    UserMd,
678    UserPlus,
679    UserSecret,
680    UserTimes,
681    Users,
682    Venus,
683    VenusDouble,
684    VenusMars,
685    Viacoin,
686    VideoCamera,
687    Vimeo,
688    VimeoSquare,
689    Vine,
690    Vk,
691    VolumeDown,
692    VolumeOff,
693    VolumeUp,
694    Warning,
695    Wechat,
696    Weibo,
697    Weixin,
698    Whatsapp,
699    Wheelchair,
700    Wifi,
701    WikipediaW,
702    Windows,
703    Won,
704    Wordpress,
705    Wrench,
706    Xing,
707    XingSquare,
708    YCombinator,
709    YCombinatorSquare,
710    Yahoo,
711    Yc,
712    YcSquare,
713    Yelp,
714    Yen,
715    Youtube,
716    YoutubePlay,
717    YoutubeSquare,
718}
719
720struct FontAwesomeIconApi {
721    name: String,
722    ref_: String,
723}
724
725impl FontAwesomeIcon {
726    fn to_api(&self) -> FontAwesomeIconApi {
727        FontAwesomeIconApi {
728            name: self.to_string(),
729            ref_: format!("/rest/config/fontawesomeicon/{}", self.variant_index() + 1),
730        }
731    }
732
733    fn from_kebab_case(name: &str) -> Result<Self, OpsviewConfigError> {
734        FontAwesomeIcon::iter()
735            .find(|variant| variant.as_ref() == name)
736            .ok_or(OpsviewConfigError::UnknownFontAwesomeIcon(name.to_string()))
737    }
738
739    fn variant_index(&self) -> usize {
740        FontAwesomeIcon::iter()
741            .position(|variant| variant == *self)
742            .unwrap()
743    }
744}
745
746impl Serialize for FontAwesomeIcon {
747    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
748    where
749        S: Serializer,
750    {
751        let icon_api = self.to_api();
752        let mut state = serializer.serialize_struct("FontAwesomeIconApi", 2)?;
753        state.serialize_field("name", &icon_api.name)?;
754        state.serialize_field("ref", &icon_api.ref_)?;
755        state.end()
756    }
757}
758
759impl<'de> Deserialize<'de> for FontAwesomeIcon {
760    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
761    where
762        D: Deserializer<'de>,
763    {
764        #[derive(Deserialize)]
765        #[serde(field_identifier, rename_all = "lowercase")]
766        enum Field {
767            Name,
768            Ref,
769        }
770
771        struct FontAwesomeIconVisitor;
772
773        impl<'de> Visitor<'de> for FontAwesomeIconVisitor {
774            type Value = FontAwesomeIcon;
775
776            fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
777                formatter.write_str("struct FontAwesomeIconApi")
778            }
779
780            fn visit_map<V>(self, mut map: V) -> Result<FontAwesomeIcon, V::Error>
781            where
782                V: MapAccess<'de>,
783            {
784                let mut name = None;
785                let mut ref_ = None;
786                while let Some(key) = map.next_key()? {
787                    match key {
788                        Field::Name => {
789                            if name.is_some() {
790                                return Err(de::Error::duplicate_field("name"));
791                            }
792                            name = Some(map.next_value()?);
793                        }
794                        Field::Ref => {
795                            if ref_.is_some() {
796                                return Err(de::Error::duplicate_field("ref"));
797                            }
798                            ref_ = Some(map.next_value()?);
799                        }
800                    }
801                }
802                let name: String = name.ok_or_else(|| de::Error::missing_field("name"))?;
803                let _ref: String = ref_.ok_or_else(|| de::Error::missing_field("ref"))?;
804
805                FontAwesomeIcon::from_kebab_case(&name)
806                    .map_err(|_| de::Error::custom("Unknown FontAwesomeIcon name"))
807            }
808        }
809
810        const FIELDS: &[&str] = &["name", "ref"];
811        deserializer.deserialize_struct("FontAwesomeIconApi", FIELDS, FontAwesomeIconVisitor)
812    }
813}
814
815#[cfg(test)]
816mod tests {
817    use super::*;
818
819    #[test]
820    fn test_to_api() {
821        let api = FontAwesomeIcon::Adjust.to_api();
822        assert_eq!(api.name, "adjust");
823        assert_eq!(api.ref_, "/rest/config/fontawesomeicon/2");
824    }
825
826    #[test]
827    fn test_from_kebab_case() {
828        let icon = FontAwesomeIcon::from_kebab_case("adjust").unwrap();
829        assert!(matches!(icon, FontAwesomeIcon::Adjust));
830
831        let unknown_icon = FontAwesomeIcon::from_kebab_case("unknown");
832        assert!(unknown_icon.is_err());
833    }
834
835    #[test]
836    fn test_display() {
837        assert_eq!(FontAwesomeIcon::Adjust.to_string(), "adjust");
838        assert_eq!(FontAwesomeIcon::YoutubeSquare.to_string(), "youtube-square");
839        assert_eq!(FontAwesomeIcon::FiveHundredPx.to_string(), "500px");
840    }
841
842    #[test]
843    fn test_deserialize_and_serialize() {
844        let test_icons = [
845            r#"{"name":"500px","ref":"/rest/config/fontawesomeicon/1"}"#,
846            r#"{"name":"adjust","ref":"/rest/config/fontawesomeicon/2"}"#,
847            r#"{"name":"youtube-square","ref":"/rest/config/fontawesomeicon/694"}"#,
848        ];
849
850        for json in test_icons {
851            let deserialized_icon: FontAwesomeIcon = serde_json::from_str(json).unwrap();
852            println!("deserialized_icon: {:?}", deserialized_icon);
853
854            let serialized_icon = serde_json::to_string(&deserialized_icon).unwrap();
855            println!("serialized_icon: {:?}", serialized_icon);
856
857            assert_eq!(&serialized_icon, json);
858        }
859    }
860}