1 use serde
::{Serialize, Serializer}
;
3 use std
::borrow
::Borrow
;
4 use std
::cmp
::Ordering
;
5 use std
::collections
::HashSet
;
7 use std
::hash
::{Hash, Hasher}
;
13 pub fn leak(s
: String
) -> &'
static str {
14 Box
::leak(s
.into_boxed_str())
17 lazy_static
::lazy_static
! {
18 static ref STRING_CACHE
: Mutex
<HashSet
<&'
static str>> = Mutex
::new(HashSet
::new());
21 #[derive(Clone, Copy)]
22 pub struct InternedString
{
26 impl PartialEq
for InternedString
{
27 fn eq(&self, other
: &InternedString
) -> bool
{
28 ptr
::eq(self.as_str(), other
.as_str())
32 impl Eq
for InternedString {}
35 pub fn new(str: &str) -> InternedString
{
36 let mut cache
= STRING_CACHE
.lock().unwrap();
37 let s
= cache
.get(str).cloned().unwrap_or_else(|| {
38 let s
= leak(str.to_string());
43 InternedString { inner: s }
46 pub fn as_str(&self) -> &'
static str {
51 impl Deref
for InternedString
{
54 fn deref(&self) -> &'
static str {
59 impl Hash
for InternedString
{
60 // NB: we can't implement this as `identity(self).hash(state)`,
61 // because we use this for on-disk fingerprints and so need
62 // stability across Cargo invocations.
63 fn hash
<H
: Hasher
>(&self, state
: &mut H
) {
64 self.as_str().hash(state
);
68 impl Borrow
<str> for InternedString
{
69 // if we implement Hash as `identity(self).hash(state)`,
70 // then this will nead to be removed.
71 fn borrow(&self) -> &str {
76 impl fmt
::Debug
for InternedString
{
77 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
78 fmt
::Debug
::fmt(self.as_str(), f
)
82 impl fmt
::Display
for InternedString
{
83 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
84 fmt
::Display
::fmt(self.as_str(), f
)
88 impl Ord
for InternedString
{
89 fn cmp(&self, other
: &InternedString
) -> Ordering
{
90 self.as_str().cmp(other
.as_str())
94 impl PartialOrd
for InternedString
{
95 fn partial_cmp(&self, other
: &InternedString
) -> Option
<Ordering
> {
100 impl Serialize
for InternedString
{
101 fn serialize
<S
>(&self, serializer
: S
) -> Result
<S
::Ok
, S
::Error
>
105 serializer
.serialize_str(self.inner
)