1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
// Copyright (c) 2018-2023, agnos.ai UK Ltd, all rights reserved.
//---------------------------------------------------------------

#[cfg(feature = "serde")]
use serde::{de::Visitor, Deserialize, Deserializer, Serialize, Serializer};
use {
    crate::{
        DataType,
        LiteralIdUrlDisplay,
        LiteralUrlDisplay,
        LiteralValue,
        RDFStoreError::{self, Unknown},
        Term,
    },
    iref::{Iri, IriBuf, IriRef},
    std::{
        fmt::{Debug, Display, Formatter},
        mem::ManuallyDrop,
        str::FromStr,
    },
};

/// Literals are used for values such as strings, numbers, and dates.
/// It consists of a [`DataType`] and a [`LiteralValue`].
///
/// (See also [RDF 1.1 Concepts and Abstract Syntax](https://www.w3.org/TR/rdf11-concepts/#section-Graph-Literal)).
///
/// A literal in an RDF graph consists of two or three elements:
///
/// 1. a lexical form, being a Unicode string, which SHOULD be in
///    [Normal Form C](http://www.unicode.org/reports/tr15/)
///
/// 2. a datatype IRI, being an IRI identifying a datatype that determines
///    how the lexical form maps to a literal value,
///
/// 3. and if and only if the datatype IRI is <http://www.w3.org/1999/02/22-rdf-syntax-ns#langString>,
///    a non-empty language tag as defined by [BCP47](https://www.rfc-editor.org/info/bcp47).
///    The language tag MUST be well-formed according to
///    section 2.2.9 of [BCP47](https://www.rfc-editor.org/info/bcp47).
#[derive(Default)]
pub struct Literal {
    pub data_type: DataType,
    literal_value: LiteralValue,
}

impl PartialEq for Literal {
    fn eq(&self, other: &Self) -> bool {
        let data_type = self.data_type;
        if data_type != other.data_type {
            return false
        }
        unsafe {
            if data_type.is_iri() {
                self.literal_value.iri == other.literal_value.iri
            } else if data_type.is_string() {
                self.literal_value.string == other.literal_value.string
            } else if data_type.is_boolean() {
                self.literal_value.boolean == other.literal_value.boolean
            } else if data_type.is_signed_integer() {
                self.literal_value.signed_integer == other.literal_value.signed_integer
            } else if data_type.is_unsigned_integer() {
                self.literal_value.unsigned_integer == other.literal_value.unsigned_integer
            } else if data_type.is_blank_node() {
                self.literal_value.blank_node == other.literal_value.blank_node
            } else if data_type.is_decimal() {
                self.literal_value.string == other.literal_value.string
            } else if data_type.is_date() {
                self.literal_value.date == other.literal_value.date
            } else if data_type.is_date_time() {
                self.literal_value.date_time == other.literal_value.date_time
            } else {
                panic!("Cannot compare, unimplemented datatype {data_type:?}")
            }
        }
    }
}

impl Eq for Literal {}

impl std::hash::Hash for Literal {
    fn hash<H>(&self, state: &mut H)
    where H: std::hash::Hasher {
        let data_type = self.data_type;
        data_type.hash(state);
        unsafe {
            #[allow(clippy::if_same_then_else)]
            if data_type.is_iri() {
                self.literal_value.iri.hash(state)
            } else if data_type.is_string() {
                self.literal_value.string.hash(state)
            } else if data_type.is_blank_node() {
                self.literal_value.blank_node.hash(state)
            } else if data_type.is_boolean() {
                self.literal_value.boolean.hash(state)
            } else if data_type.is_signed_integer() {
                self.literal_value.signed_integer.hash(state)
            } else if data_type.is_unsigned_integer() {
                self.literal_value.unsigned_integer.hash(state)
            } else if data_type.is_decimal() {
                self.literal_value.string.hash(state)
            } else if data_type.is_duration() {
                self.literal_value.string.hash(state)
            } else if data_type.is_date() {
                self.literal_value.date.hash(state)
            } else if data_type.is_date_time() {
                self.literal_value.date_time.hash(state)
            } else {
                panic!("Cannot hash, unimplemented datatype {data_type:?}")
            }
        }
    }
}

impl Debug for Literal {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        let data_type = self.data_type;
        write!(f, "Literal({:?},", data_type)?;
        unsafe {
            #[allow(clippy::if_same_then_else)]
            if data_type.is_iri() {
                write!(f, "<{}>)", self.literal_value.iri.as_str())?
            } else if data_type.is_string() {
                write!(f, "\"{}\"", self.literal_value.string.as_str())?
            } else if data_type.is_blank_node() {
                write!(f, "_:{}", self.literal_value.blank_node.as_str())?
            } else if data_type.is_boolean() {
                write!(f, "{}", self.literal_value.boolean)?
            } else if data_type.is_signed_integer() {
                write!(f, "{}", self.literal_value.signed_integer)?
            } else if data_type.is_unsigned_integer() {
                write!(f, "{}", self.literal_value.unsigned_integer)?
            } else if data_type.is_decimal() {
                write!(f, "{}", self.literal_value.string.as_str())?
            } else if data_type.is_duration() || data_type.is_date_time_stamp() {
                write!(f, "{}", self.literal_value.string.as_str())?
            } else if data_type.is_date() {
                write!(
                    f,
                    "{}",
                    self.literal_value.date.format("%Y-%m-%d")
                )?
            } else if data_type.is_date_time() {
                write!(f, "{:}", self.literal_value.date_time)?
            } else {
                panic!("Cannot format, unimplemented datatype {data_type:?}")
            }
        }
        write!(f, ")")
    }
}

impl Display for Literal {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        if self.data_type.is_iri() {
            write!(f, "<{}>", self.as_iri().unwrap().as_str())
        } else if self.data_type.is_blank_node() {
            write!(f, "_:{}", self.as_string().unwrap().as_str())
        } else if self.data_type.is_string() {
            if let Some(strng) = self.as_string() {
                write!(f, "\"{}\"", strng.as_str())
            } else {
                write!(f, "ERROR, could not convert to String")
            }
        } else if self.data_type.is_boolean() {
            write!(f, "{}", self.as_boolean().unwrap())
        } else if self.data_type.is_date() {
            write!(f, "{}", self.as_date().unwrap())
        } else if self.data_type.is_date_time() {
            write!(f, "{}", self.as_date_time().unwrap())
        } else if let Some(strng) = self.as_string() {
            write!(f, "{} ({:?})", strng.as_str(), self.data_type)
        } else {
            write!(
                f,
                "ERROR, could not convert to String ({:?})",
                self.data_type
            )
        }
    }
}

impl Clone for Literal {
    // noinspection RsUnreachableCode
    fn clone(&self) -> Self {
        if self.data_type.is_iri() {
            if let Some(ref iri) = self.as_iri() {
                Literal {
                    data_type:     self.data_type,
                    literal_value: LiteralValue::new_iri(iri),
                }
            } else {
                todo!("the situation where the iri in a lexical value is empty")
            }
        } else if self.data_type.is_blank_node() {
            if let Some(blank_node) = self.as_str() {
                Literal::new_blank_node_with_datatype(blank_node, self.data_type).unwrap()
            } else {
                todo!("the situation where the blank_node in a lexical value is empty")
            }
        } else if self.data_type.is_string() {
            if let Some(str) = self.as_str() {
                Literal::new_string_with_datatype(str, self.data_type).unwrap()
            } else {
                todo!("the situation where the string in a lexical value is empty")
            }
        } else if self.data_type.is_boolean() {
            if let Some(boolean) = self.as_boolean() {
                Literal::new_boolean_with_datatype(boolean, self.data_type).unwrap()
            } else {
                todo!("the situation where the boolean in a lexical value is not a boolean")
            }
        } else if self.data_type.is_date() {
            if let Some(date) = self.as_date() {
                Literal::new_date_with_datatype(date, self.data_type).unwrap()
            } else {
                todo!("the situation where the naive date in a lexical value is not a naive date")
            }
        } else if self.data_type.is_date_time() {
            if let Some(date_time) = self.as_date_time() {
                Literal::new_date_time_with_datatype(*date_time, self.data_type).unwrap()
            } else {
                todo!("the situation where the boolean in a lexical value is not a boolean")
            }
        } else if self.data_type.is_signed_integer() {
            if let Some(long) = self.as_signed_long() {
                Literal::new_signed_integer_with_datatype(long, self.data_type).unwrap()
            } else {
                todo!("the situation where the signed integer value is not a long")
            }
        } else if self.data_type.is_unsigned_integer() {
            if let Some(long) = self.as_unsigned_long() {
                Literal::new_unsigned_integer_with_datatype(long, self.data_type).unwrap()
            } else {
                todo!("the situation where the unsigned integer value is not a long")
            }
        } else if self.data_type.is_decimal() {
            if let Some(decimal) = self.as_decimal() {
                Literal::new_decimal_with_datatype(decimal, self.data_type).unwrap()
            } else {
                todo!("the situation where the decimal value is not a decimal")
            }
        } else if self.data_type.is_duration() {
            if let Some(duration) = self.as_duration() {
                Literal::new_duration_with_datatype(duration, self.data_type).unwrap()
            } else {
                todo!("the situation where the duration value is not a duration")
            }
        } else {
            todo!(
                "dealing with other datatypes: {:?}",
                self.data_type
            )
        }
    }
}

#[cfg(feature = "serde")]
impl Serialize for Literal {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where S: Serializer {
        let data_type = self.data_type;
        unsafe {
            if data_type.is_iri() {
                serializer.serialize_str(self.literal_value.iri.as_str())
            } else if data_type.is_string() {
                serializer.serialize_str(self.literal_value.string.as_str())
            } else if data_type.is_blank_node() {
                serializer.serialize_str(self.literal_value.blank_node.as_str())
            } else if data_type.is_boolean() {
                serializer.serialize_bool(self.literal_value.boolean)
            } else if data_type.is_signed_integer() {
                serializer.serialize_i64(self.literal_value.signed_integer)
            } else if data_type.is_unsigned_integer() {
                serializer.serialize_u64(self.literal_value.unsigned_integer)
            } else if data_type.is_decimal() {
                serializer.serialize_str(self.literal_value.string.as_str())
            } else if data_type.is_duration() || data_type.is_date_time_stamp() {
                serializer.serialize_str(self.literal_value.string.as_str())
            } else if data_type.is_date() {
                serializer.serialize_str(self.literal_value.date.to_string().as_str())
            } else if data_type.is_date_time() {
                serializer.serialize_str(self.literal_value.date_time.to_string().as_str())
            } else {
                panic!("Cannot serialize, unimplemented datatype {data_type:?}")
            }
        }
    }
}

#[cfg(feature = "serde")]
impl<'a> Deserialize<'a> for Literal {
    fn deserialize<D: Deserializer<'a>>(deserializer: D) -> Result<Self, D::Error> {
        deserializer.deserialize_str(LiteralDeserializeVisitor)
    }
}

impl FromStr for Literal {
    type Err = RDFStoreError;

    fn from_str(str: &str) -> Result<Self, Self::Err> { Self::new_plain_literal_string(str) }
}

#[cfg(feature = "oxigraph")]
impl From<oxrdf::Literal> for Literal {
    fn from(value: oxrdf::Literal) -> Self {
        // TODO: Temporary simplistic implementation
        Self::from_str(value.value()).unwrap()
    }
}

impl From<&str> for Literal {
    fn from(value: &str) -> Self { Literal::from_str(value).unwrap() }
}

impl Literal {
    pub fn as_term(&self) -> Term {
        match self.data_type {
            DataType::IriReference | DataType::AnyUri => Term::Iri(self.clone()),
            DataType::BlankNode => Term::BlankNode(self.clone()),
            _ => Term::Literal(self.clone()),
        }
    }

    pub fn as_iri(&self) -> Option<Iri> {
        if self.data_type.is_iri() {
            Some(unsafe { self.literal_value.iri.as_iri() })
        } else {
            None
        }
    }

    pub fn as_local_name(&self) -> Option<String> {
        self.as_iri().as_ref().and_then(|iri| {
            let iri_str = iri.as_str();
            match fancy_regex::Regex::new(r#"(?:.*)[#/](.*)"#) {
                Ok(re) => {
                    if let Ok(Some(captures)) = re.captures(iri_str) {
                        captures.get(1).map(|mat| String::from(mat.as_str()))
                    } else {
                        None
                    }
                },
                Err(_err) => {
                    tracing::error!(
                        target: crate::consts::LOG_TARGET_DATABASE,
                        "Literal::as_local_name failed with iri: {iri_str}"
                    );
                    None
                },
            }
        })
    }

    pub fn as_str(&self) -> Option<&str> {
        #[allow(clippy::if_same_then_else)]
        if self.data_type.is_iri() {
            unsafe { Some(self.literal_value.iri.as_str()) }
        } else if self.data_type.is_string() {
            unsafe { Some(self.literal_value.string.as_str()) }
        } else if self.data_type.is_signed_integer() {
            None
        } else if self.data_type.is_unsigned_integer() {
            None
        } else if self.data_type.is_blank_node() {
            unsafe { Some(self.literal_value.blank_node.as_str()) }
        } else if self.data_type.is_boolean() {
            unsafe {
                if self.literal_value.boolean {
                    Some("true")
                } else {
                    Some("false")
                }
            }
        } else if self.data_type.is_decimal() {
            unsafe { Some(self.literal_value.string.as_str()) }
        } else if self.data_type.is_duration() {
            unsafe { Some(self.literal_value.string.as_str()) }
        } else if self.data_type.is_date_time() {
            unsafe { Some(self.literal_value.string.as_str()) }
        } else {
            panic!("Data type {:?} not yet supported", self.data_type);
        }
    }

    pub fn as_string(&self) -> Option<String> { self.as_str().map(|v| v.to_owned()) }

    pub fn as_boolean(&self) -> Option<bool> {
        match self.data_type {
            DataType::Boolean => Some(unsafe { self.literal_value.boolean }),
            _ => None,
        }
    }

    pub fn as_signed_long(&self) -> Option<i64> {
        if self.data_type.is_signed_integer() {
            Some(unsafe { self.literal_value.signed_integer })
        } else {
            None
        }
    }

    pub fn as_unsigned_long(&self) -> Option<u64> {
        if self.data_type.is_unsigned_integer() {
            Some(unsafe { self.literal_value.unsigned_integer })
        } else {
            None
        }
    }

    pub fn as_date(&self) -> Option<chrono::NaiveDate> {
        match self.data_type {
            DataType::Date => Some(unsafe { *self.literal_value.date }),
            DataType::DateTime => self.as_date_time().map(|dt| dt.naive_utc().date()),
            _ => None,
        }
    }

    pub fn as_date_time(&self) -> Option<&chrono::DateTime<chrono::Utc>> {
        match self.data_type {
            DataType::DateTime => Some(unsafe { &self.literal_value.date_time }),
            _ => None,
        }
    }

    pub fn as_decimal(&self) -> Option<&str> {
        match self.data_type {
            DataType::Decimal => Some(unsafe { &self.literal_value.string }),
            _ => None,
        }
    }

    pub fn as_duration(&self) -> Option<&str> {
        match self.data_type {
            DataType::Duration => Some(unsafe { &self.literal_value.string }),
            _ => None,
        }
    }

    pub fn from_type_and_c_buffer(
        data_type: DataType,
        buffer: &[u8],
    ) -> Result<Option<Literal>, RDFStoreError> {
        let str_buffer = std::ffi::CStr::from_bytes_until_nul(buffer)
            .map_err(|err| {
                tracing::error!(
                    target: crate::consts::LOG_TARGET_DATABASE,
                    "Cannot read buffer: {err:?}"
                );
                Unknown // TODO
            })?
            .to_str()
            .map_err(|err| {
                tracing::error!(
                    target: crate::consts::LOG_TARGET_DATABASE,
                    "Cannot convert buffer to string: {err:?}"
                );
                Unknown // TODO
            })?;
        Self::from_type_and_buffer(data_type, str_buffer, None)
    }

    pub fn from_type_and_buffer(
        data_type: DataType,
        buffer: &str,
        id_base_iri: Option<&IriBuf>,
    ) -> Result<Option<Literal>, RDFStoreError> {
        match data_type {
            DataType::AnyUri | DataType::IriReference => {
                if buffer.starts_with('<') && buffer.ends_with('>') {
                    return Self::from_type_and_buffer(
                        data_type,
                        &buffer[1..buffer.len() - 1],
                        id_base_iri,
                    )
                }
                if let Ok(iri) = IriBuf::from_str(buffer) {
                    Ok(Some(Literal::new_iri_with_datatype(
                        &iri.as_iri(),
                        data_type,
                    )?))
                } else if id_base_iri.is_some() {
                    Ok(Some(Literal::new_iri_from_string_with_datatype(
                        buffer,
                        data_type,
                        id_base_iri,
                    )?))
                } else {
                    match IriRef::from_str(buffer) {
                        Ok(iri) => {
                            tracing::error!(
                                target: crate::consts::LOG_TARGET_DATABASE,
                                "Cannot convert [{:?}] to a valid IRI",
                                iri
                            );
                            return Err(RDFStoreError::UnknownValueForDataType {
                                data_type,
                                value: buffer.to_string(),
                            })
                        },
                        Err(error) => {
                            tracing::error!(
                                target: crate::consts::LOG_TARGET_DATABASE,
                                "Cannot convert [{buffer}] to an IRI"
                            );
                            return Err(RDFStoreError::IriParseError(error))
                        },
                    }
                }
            },
            DataType::BlankNode => {
                Ok(Some(Literal::new_blank_node_with_datatype(
                    buffer, data_type,
                )?))
            },
            DataType::Boolean => {
                match buffer {
                    "true" | "false" => {
                        Ok(Some(Literal::new_boolean_with_datatype(
                            buffer.starts_with("true"),
                            data_type,
                        )?))
                    },
                    _ => Err(RDFStoreError::UnknownNTriplesValue { value: buffer.to_string() }),
                }
            },
            DataType::String | DataType::PlainLiteral => {
                Ok(Some(Literal::new_string_with_datatype(
                    buffer, data_type,
                )?))
            },
            DataType::Date | DataType::DateTime => Self::date_from_str(buffer),
            DataType::Int |
            DataType::Integer |
            DataType::NegativeInteger |
            DataType::NonPositiveInteger |
            DataType::Long |
            DataType::Short => {
                let signed_integer: i64 = buffer.parse()?; // TODO: Remove unwrap
                Ok(Some(Literal::new_signed_integer_with_datatype(
                    signed_integer,
                    data_type,
                )?))
            },
            DataType::PositiveInteger |
            DataType::NonNegativeInteger |
            DataType::UnsignedByte |
            DataType::UnsignedInt |
            DataType::UnsignedShort |
            DataType::UnsignedLong => {
                let unsigned_integer: u64 = buffer.parse().unwrap(); // TODO: Remove unwrap
                Ok(Some(Literal::new_unsigned_integer_with_datatype(
                    unsigned_integer,
                    data_type,
                )?))
            },
            DataType::Decimal => {
                Ok(Some(Literal::new_decimal_with_datatype(
                    buffer, data_type,
                )?))
            },
            DataType::Duration => {
                Ok(Some(Literal::new_duration_with_datatype(
                    buffer, data_type,
                )?))
            },
            DataType::UnboundValue => Ok(None),
            _ => {
                tracing::warn!(
                    target: crate::consts::LOG_TARGET_DATABASE,
                    "Unsupported datatype: {data_type:?} value={buffer}"
                );
                Err(Unknown)
            },
        }
    }

    fn date_from_str(buffer: &str) -> Result<Option<Literal>, RDFStoreError> {
        if let Ok(date_time) = chrono::DateTime::parse_from_rfc2822(buffer) {
            return Ok(Some(Literal::new_date_time_with_datatype(
                chrono::DateTime::from(date_time),
                DataType::DateTime,
            )?))
        }
        if let Ok(date_time) = chrono::DateTime::parse_from_rfc3339(buffer) {
            return Ok(Some(Literal::new_date_time_with_datatype(
                chrono::DateTime::from(date_time),
                DataType::DateTime,
            )?))
        }
        if let Ok(date_time) = chrono::DateTime::parse_from_str(buffer, "%Y-%m-%d %H:%M:%S %z") {
            return Ok(Some(Literal::new_date_time_with_datatype(
                chrono::DateTime::from(date_time),
                DataType::DateTime,
            )?))
        }
        if let Ok(date_time) = chrono::NaiveDateTime::parse_from_str(buffer, "%Y-%m-%d %H:%M:%S") {
            return Ok(Some(Literal::new_date_time_with_datatype(
                chrono::DateTime::from_utc(date_time, chrono::Utc),
                DataType::DateTime,
            )?))
        }
        if let Ok(date_time) = chrono::NaiveDateTime::parse_from_str(buffer, "%Y-%m-%d %H:%M") {
            return Ok(Some(Literal::new_date_time_with_datatype(
                chrono::DateTime::from_utc(date_time, chrono::Utc),
                DataType::DateTime,
            )?))
        }
        if let Ok(date) = chrono::NaiveDate::parse_from_str(buffer, "%Y-%m-%d") {
            return Ok(Some(Literal::new_date_with_datatype(
                date,
                DataType::Date,
            )?))
        }
        if let Ok(date) = chrono::NaiveDate::parse_from_str(buffer, "%Y/%m/%d") {
            return Ok(Some(Literal::new_date_with_datatype(
                date,
                DataType::Date,
            )?))
        }
        if let Ok(date) = chrono::NaiveDate::parse_from_str(buffer, "%m/%d/%Y") {
            return Ok(Some(Literal::new_date_with_datatype(
                date,
                DataType::Date,
            )?))
        }

        #[cfg(feature = "serde")]
        match serde_json::from_str::<chrono::DateTime<chrono::Utc>>(buffer) {
            Ok(date_time) => {
                Ok(Some(Literal::new_date_time_with_datatype(
                    date_time,
                    DataType::DateTime,
                )?))
            },
            Err(error) => {
                tracing::error!(
                    target: crate::consts::LOG_TARGET_DATABASE,
                    "Could not convert [{buffer}] to a DateTime Literal"
                );
                Err(RDFStoreError::SerdeJsonError(error))
            },
        }
        #[cfg(not(feature = "serde"))]
        Err(Unknown) // TODO
    }

    pub fn from_iri(iri: &Iri) -> Result<Self, RDFStoreError> {
        Ok(Literal {
            data_type:     DataType::IriReference,
            literal_value: LiteralValue { iri: ManuallyDrop::new(IriBuf::from(iri)) },
        })
    }

    pub fn new_plain_literal_string(str: &str) -> Result<Self, RDFStoreError> {
        Self::new_string_with_datatype(str, DataType::PlainLiteral)
    }

    pub fn new_plain_literal_boolean(boolean: bool) -> Result<Self, RDFStoreError> {
        Self::new_string_with_datatype(
            boolean.to_string().as_str(),
            DataType::PlainLiteral,
        )
    }

    pub fn new_string_with_datatype(str: &str, data_type: DataType) -> Result<Self, RDFStoreError> {
        assert!(
            &data_type.is_string(),
            "{data_type:?} is not a string type"
        );
        Ok(Literal {
            data_type,
            literal_value: LiteralValue::new_string(str),
        })
    }

    /// Use this only for naive dates
    /// (see <https://docs.rs/chrono/latest/chrono/naive/struct.NaiveDate.html>)
    pub fn new_date_with_datatype(
        date: chrono::NaiveDate,
        data_type: DataType,
    ) -> Result<Self, RDFStoreError> {
        assert!(
            &data_type.is_date(),
            "{data_type:?} is not a Date"
        );
        Ok(Literal {
            data_type,
            literal_value: LiteralValue::new_date(date),
        })
    }

    pub fn new_date_time_with_datatype(
        date_time: chrono::DateTime<chrono::Utc>,
        data_type: DataType,
    ) -> Result<Self, RDFStoreError> {
        assert!(
            &data_type.is_date_time(),
            "{data_type:?} is not a dateTime"
        );
        Ok(Literal {
            data_type,
            literal_value: LiteralValue::new_date_time(date_time),
        })
    }

    pub fn new_decimal_with_datatype(
        str: &str,
        data_type: DataType,
    ) -> Result<Self, RDFStoreError> {
        assert!(
            &data_type.is_decimal(),
            "{data_type:?} is not a decimal"
        );
        Ok(Literal {
            data_type,
            literal_value: LiteralValue::new_string(str),
        })
    }

    pub fn new_duration_with_datatype(
        str: &str,
        data_type: DataType,
    ) -> Result<Self, RDFStoreError> {
        assert!(
            &data_type.is_duration(),
            "{data_type:?} is not a duration"
        );
        Ok(Literal {
            data_type,
            literal_value: LiteralValue::new_string(str),
        })
    }

    pub fn new_iri_from_string_with_datatype(
        iri_string: &str,
        data_type: DataType,
        id_base_iri: Option<&IriBuf>,
    ) -> Result<Self, RDFStoreError> {
        match IriBuf::from_str(iri_string) {
            Ok(iri) => Self::new_iri_with_datatype(&iri.as_iri(), data_type),
            Err(error) => {
                if let Ok(iri_ref) = IriRef::from_str(iri_string) {
                    if let Some(id_base_iri) = id_base_iri {
                        // If we passed a base IRI and the given IRI string is just an identifier,
                        // the stick the base IRI in front of it
                        if iri_ref.scheme().is_none() || iri_ref.authority().is_none() {
                            return Self::from_iri(&iri_ref.resolved(id_base_iri).as_iri())
                        }
                    }
                }
                Err(RDFStoreError::IriParseError(error))
            },
        }
    }

    pub fn new_iri_reference_from_str(iri: &str) -> Result<Self, RDFStoreError> {
        let iri = IriBuf::from_str(iri)?;
        Self::new_iri_with_datatype(&iri.as_iri(), DataType::IriReference)
    }

    pub fn new_iri_with_datatype(iri: &Iri, data_type: DataType) -> Result<Self, RDFStoreError> {
        assert!(
            &data_type.is_iri(),
            "{data_type:?} is not an IRI type"
        );
        Ok(Literal {
            data_type,
            literal_value: LiteralValue::new_iri(iri),
        })
    }

    pub fn new_blank_node_with_datatype(
        id: &str,
        data_type: DataType,
    ) -> Result<Self, RDFStoreError> {
        assert!(
            &data_type.is_blank_node(),
            "{data_type:?} is not a blank node type"
        );
        Ok(Literal {
            data_type,
            literal_value: LiteralValue::new_blank_node(id),
        })
    }

    pub fn new_boolean(boolean: bool) -> Result<Self, RDFStoreError> {
        Self::new_boolean_with_datatype(boolean, DataType::Boolean)
    }

    pub fn new_boolean_from_string(boolean_string: &str) -> Result<Self, RDFStoreError> {
        Self::new_boolean_from_string_with_datatype(boolean_string, DataType::Boolean)
    }

    pub fn new_boolean_from_string_with_datatype(
        boolean_string: &str,
        data_type: DataType,
    ) -> Result<Self, RDFStoreError> {
        match boolean_string {
            "true" => Self::new_boolean_with_datatype(true, data_type),
            "false" => Self::new_boolean_with_datatype(false, data_type),
            &_ => {
                Err(RDFStoreError::UnknownValueForDataType {
                    data_type,
                    value: boolean_string.to_string(),
                })
            },
        }
    }

    pub fn new_boolean_with_datatype(
        boolean: bool,
        data_type: DataType,
    ) -> Result<Self, RDFStoreError> {
        assert!(
            &data_type.is_boolean(),
            "{data_type:?} is not a boolean type"
        );
        Ok(Literal {
            data_type,
            literal_value: LiteralValue::new_boolean(boolean),
        })
    }

    pub fn new_signed_integer(signed_integer: i64) -> Result<Self, RDFStoreError> {
        if signed_integer >= 0 {
            Self::new_unsigned_integer(signed_integer as u64)
        } else {
            Self::new_signed_integer_with_datatype(signed_integer, DataType::NegativeInteger)
        }
    }

    pub fn new_signed_integer_with_datatype(
        signed_integer: i64,
        data_type: DataType,
    ) -> Result<Self, RDFStoreError> {
        assert!(
            &data_type.is_signed_integer(),
            "{data_type:?} is not an signed integer type"
        );
        Ok(Literal {
            data_type,
            literal_value: LiteralValue::new_signed_integer(signed_integer),
        })
    }

    pub fn new_unsigned_integer(unsigned_integer: u64) -> Result<Self, RDFStoreError> {
        Self::new_unsigned_integer_with_datatype(unsigned_integer, DataType::PositiveInteger)
    }

    pub fn new_unsigned_integer_with_datatype(
        unsigned_integer: u64,
        data_type: DataType,
    ) -> Result<Self, RDFStoreError> {
        assert!(
            &data_type.is_unsigned_integer(),
            "{data_type:?} is not an unsigned integer type"
        );
        Ok(Literal {
            data_type,
            literal_value: LiteralValue::new_unsigned_integer(unsigned_integer),
        })
    }

    pub fn display_turtle<'a, 'b>(&'a self) -> impl std::fmt::Display + 'a + 'b
    where 'a: 'b {
        struct TurtleLexVal<'b>(&'b Literal);
        impl<'b> std::fmt::Display for TurtleLexVal<'b> {
            fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
                let data_type = self.0.data_type;
                unsafe {
                    if data_type.is_iri() {
                        write!(f, "<{}>", self.0.literal_value.iri.as_str())?
                    } else if data_type.is_string() {
                        write!(f, "\"{}\"", self.0.literal_value.string.as_str())?
                    } else if data_type.is_blank_node() {
                        write!(
                            f,
                            "_:{}",
                            self.0.literal_value.blank_node.as_str()
                        )?
                    } else if data_type.is_boolean() {
                        write!(f, "{}", self.0.literal_value.boolean)?
                    } else if data_type.is_signed_integer() {
                        write!(f, "{}", self.0.literal_value.signed_integer)?
                    } else if data_type.is_unsigned_integer() {
                        write!(f, "{}", self.0.literal_value.unsigned_integer)?
                    } else if data_type.is_date_time() {
                        write!(
                            f,
                            "\"{}\"^^xsd:dateTime",
                            self.0.literal_value.string.as_str()
                        )?
                    } else if data_type.is_decimal() {
                        write!(f, "{}", self.0.literal_value.string.as_str())?
                    } else if data_type.is_duration() {
                        write!(
                            f,
                            "\"{}\"^^xsd:duration",
                            self.0.literal_value.string.as_str()
                        )?
                    } else {
                        panic!("Cannot format for turtle, unimplemented datatype {data_type:?}")
                    }
                }
                Ok(())
            }
        }
        TurtleLexVal(self)
    }

    pub fn display_json<'a, 'b>(&'a self) -> impl std::fmt::Display + 'a + 'b
    where 'a: 'b {
        struct JsonLexVal<'b>(&'b Literal);
        impl<'b> Display for JsonLexVal<'b> {
            fn fmt(&self, f: &mut Formatter) -> std::fmt::Result {
                let data_type = self.0.data_type;
                unsafe {
                    if data_type.is_iri() {
                        write!(f, "\"{}\"", self.0.literal_value.iri.as_str())?
                    } else if data_type.is_string() {
                        write!(
                            f,
                            "\"{}\"",
                            self.0.literal_value.string.replace('\"', "\\\"").as_str()
                        )?
                    } else if data_type.is_blank_node() {
                        write!(
                            f,
                            "\"_:{}\"",
                            self.0.literal_value.blank_node.as_str()
                        )?
                    } else if data_type.is_boolean() {
                        write!(f, "{}", self.0.literal_value.boolean)?
                    } else if data_type.is_signed_integer() {
                        write!(f, "{}", self.0.literal_value.signed_integer)?
                    } else if data_type.is_unsigned_integer() {
                        write!(f, "{}", self.0.literal_value.unsigned_integer)?
                    } else if data_type.is_date_time() {
                        write!(f, "\"{}\"", self.0.literal_value.string.as_str())?
                    } else if data_type.is_decimal() {
                        write!(f, "{}", self.0.literal_value.string.as_str())?
                    } else if data_type.is_duration() {
                        write!(f, "\"{}\"", self.0.literal_value.string.as_str())?
                    } else {
                        panic!("Cannot format for JSON, unimplemented datatype {data_type:?}")
                    }
                }
                Ok(())
            }
        }
        JsonLexVal(self)
    }

    pub fn as_url_display(&self) -> LiteralUrlDisplay { LiteralUrlDisplay { literal: self } }

    pub fn as_id_url_display<'a>(&'a self, id_base_iri: &'a IriBuf) -> LiteralIdUrlDisplay {
        LiteralIdUrlDisplay { literal: self, id_base_iri }
    }

    /// Is the given Literal an IRI whose base is the given IRI?
    pub fn is_id_iri(&self, id_base_iri: &IriBuf) -> bool {
        match self.data_type {
            DataType::AnyUri | DataType::IriReference => unsafe {
                self.literal_value
                    .iri
                    .as_str()
                    .starts_with(id_base_iri.as_str())
            },
            _ => false,
        }
    }

    pub fn as_id(&self, id_base_iri: &IriBuf) -> &str {
        match self.data_type {
            DataType::AnyUri | DataType::IriReference => unsafe {
                let len = id_base_iri.as_str().len();
                let (_first, last) = self.literal_value.iri.as_str().split_at(len);
                last
            },
            _ => "",
        }
    }
}

#[cfg(feature = "serde")]
struct LiteralDeserializeVisitor;

#[cfg(feature = "serde")]
impl<'de> Visitor<'de> for LiteralDeserializeVisitor {
    type Value = Literal;

    fn expecting(&self, formatter: &mut Formatter) -> std::fmt::Result {
        formatter.write_str("a correct literal value")
    }

    fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
    where E: serde::de::Error {
        if let Ok(Some(iri)) = Literal::from_type_and_buffer(DataType::AnyUri, v, None) {
            return Ok(iri)
        }
        if let Ok(Some(integer)) = Literal::from_type_and_buffer(DataType::Integer, v, None) {
            return Ok(integer)
        }
        if let Ok(Some(date_time)) = Literal::from_type_and_buffer(DataType::DateTime, v, None) {
            return Ok(date_time)
        }
        if let Ok(Some(decimal)) = Literal::from_type_and_buffer(DataType::Decimal, v, None) {
            return Ok(decimal)
        }
        match Literal::from_str(v) {
            Ok(literal) => Ok(literal),
            Err(rdf_store_error) => Err(E::custom(rdf_store_error.to_string())),
        }
    }
}