www.digitalmars.com         C & C++   DMDScript  

digitalmars.D - D is so awesome

I can't believe how awesome intuitive and fast D is. I make a struct

	struct CacheItem(T)
		if (isPointer!T)
	{
		size_t ID;
		size_t Key;
		T Value;
		long Size; // of value
		long LastAccess = Clock.currStdTime;
	
		 disable this(this);
	}

and then I create a container
	alias T = string;
	alias TItem = CacheItem!T;
	alias CacheItemArray = Array!TItem;
	private CacheItemArray m_DATA;

and then I fetch or insert elements

	get(id, key):

	TItem ndl = {ID: id.toHash, Key: key.toHash}; //just like json!
	Range elmt = m_DATA[].find!("a.ID == b.ID && a.Key == b.Key")(ndl); // 
sexy predicate

	set(id, key, value):

	TItem itm = {	ID: id.toHash,
			Key: key.toHash,
			Value: &value,
			Size: s.length,
			LastAccess: Clock.currStdTime
		}; // how lovely is that?
	m_DATA.insert(itm);

with this lovely universal toHash to fallback on in UFCS
	size_t toHash(T)(T a) {
		return (&(typeid(T).getHash))(a);
	}

and if I want to add some manual allocations
	char[] val = cast(char[])manualAllocator().alloc(value.length);
	val[] = value[];

or deallocations

	void[] s = (cast(void*)elmt.front.Value)[0..(*elmt.front.Value).length];
	manualAllocator().free(s);

and then clean it up

	void cleanup(size_t count){
		auto heap = BinaryHeap!(CacheItemArray, "a.LastAccess < 
b.LastAccess")(m_DATA);
		foreach(i ; 0..count)
			heap.removeFront();
		m_DATA = heap.release();
	}

This makes a nice draft for LRU cache in machine code. Using removeAny() 
in cleanup makes it a RR cache. I'd love to see how quick this is in LDC 
once it's compatible with vibe.d subprojects
Jan 17 2014