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
//
// util.rs
// The PHiLe Compiler
//
// Created by Arpad Goretity (H2CO3)
// on 02/05/2017
//

use std::rc::{ Rc, Weak };
use std::cell::{ RefCell, Ref, RefMut };
use std::hash::{ Hash, Hasher };
use std::fmt::{ self, Display, Formatter };
use error::{ Error, Result };
use unicode_segmentation::UnicodeSegmentation;


// Generic macro for building an associated container literal
macro_rules! assoc_map {
    ($t: ident, $($k: expr => $v: expr),*) => ({
        let mut _tmp = ::std::collections::$t::new();
        $({
            let key = $k;
            let val = $v;
            _tmp.insert(key.into(), val.into()).map(
                |_| panic!("duplicate value for key {:#?}", key)
            );
        })*
        _tmp
    })
}

macro_rules! hash_map {
    ($($k: expr => $v: expr),*) => {
        assoc_map!(HashMap, $($k => $v),*)
    };
    ($($k: expr => $v: expr),+,) => { hash_map!($($k => $v),+) };
}

macro_rules! btree_map {
    ($($k: expr => $v: expr),*) => {
        assoc_map!(BTreeMap, $($k => $v),*)
    };
    ($($k: expr => $v: expr),+,) => { btree_map!($($k => $v),+) };
}

#[derive(Debug, Clone, Copy)]
pub struct PackageInfo {
    pub name:        &'static str,
    pub version:     &'static str,
    pub authors:     &'static str,
    pub description: &'static str,
    pub home_page:   &'static str,
}

#[derive(Debug, Clone, Copy)]
pub struct Color {
    pub reset:     &'static str,
    pub info:      &'static str,
    pub highlight: &'static str,
    pub success:   &'static str,
    pub error:     &'static str,
}

#[derive(Debug)]
pub struct RcCell<T: ?Sized> {
    ptr: Rc<RefCell<T>>,
}

#[derive(Debug)]
pub struct WkCell<T: ?Sized> {
    ptr: Weak<RefCell<T>>,
}

#[derive(Debug)]
pub struct WeakDisplay<'a, T: 'a>(pub &'a WkCell<T>);

pub static PACKAGE_INFO: PackageInfo = PackageInfo {
    name:        env!["CARGO_PKG_NAME"],
    version:     env!["CARGO_PKG_VERSION"],
    authors:     env!["CARGO_PKG_AUTHORS"],
    description: env!["CARGO_PKG_DESCRIPTION"],
    home_page:   env!["CARGO_PKG_HOMEPAGE"],
};

pub static COLOR: Color = Color {
    reset:     "\x1b[0m",
    info:      "\x1b[1;33m",
    highlight: "\x1b[1;36m",
    success:   "\x1b[1;32m",
    error:     "\x1b[1;31m",
};


pub fn grapheme_count(string: &str) -> usize {
    string.graphemes(true).count()
}

pub fn unescape_string_literal(string: &str) -> Result<String> {
    if string.contains('\\') {
        unimplemented!() // TODO(H2CO3): unescape string literals
    } else {
        Ok(string.to_owned())
    }
}


impl<T> RcCell<T> {
    pub fn new(value: T) -> RcCell<T> {
        RcCell {
            ptr: Rc::new(RefCell::new(value))
        }
    }

    pub fn borrow(&self) -> Result<Ref<T>> {
        self.ptr.try_borrow().map_err(From::from)
    }

    pub fn borrow_mut(&self) -> Result<RefMut<T>> {
        self.ptr.try_borrow_mut().map_err(From::from)
    }

    pub fn as_weak(&self) -> WkCell<T> {
        WkCell {
            ptr: Rc::downgrade(&self.ptr)
        }
    }
}

impl<T> Clone for RcCell<T> {
    fn clone(&self) -> RcCell<T> {
        RcCell {
            ptr: self.ptr.clone()
        }
    }
}

// TODO(H2CO3): implement this once { Unsize, CoerceUnsized } are stable
// impl<T: ?Sized + Unsize<U>, U: ?Sized> CoerceUnsized<RcCell<U>> for RcCell<T> {}

// Tests equality based on pointer identity
impl<T> PartialEq for RcCell<T> {
    fn eq(&self, other: &Self) -> bool {
        self.ptr.as_ptr() == other.ptr.as_ptr()
    }
}

impl<T> Eq for RcCell<T> {}

// Hashes the pointer address itself
impl<T> Hash for RcCell<T> {
    fn hash<H: Hasher>(&self, hasher: &mut H) {
        self.ptr.as_ptr().hash(hasher)
    }
}

impl<T> WkCell<T> {
    pub fn new() -> WkCell<T> {
        WkCell {
            ptr: Weak::new()
        }
    }

    pub fn as_rc(&self) -> Result<RcCell<T>> {
        self.ptr.upgrade().map(|rc| RcCell { ptr: rc }).ok_or(Error::Strongify)
    }
}

impl<T> Clone for WkCell<T> {
    fn clone(&self) -> WkCell<T> {
        WkCell {
            ptr: self.ptr.clone()
        }
    }
}

impl<'a, T> Display for WeakDisplay<'a, T> where T: Display {
    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
        let rc = match self.0.as_rc() {
            Ok(rc) => rc,
            Err(_) => return f.write_str("<cannot strongify>"),
        };
        let ptr = match rc.borrow() {
            Ok(ptr) => ptr,
            Err(_)  => return f.write_str("<cannot borrow>"),
        };

        Display::fmt(&*ptr, f)
    }
}