/*
 * Copyright 2007-2017 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package net.ymate.platform.core.support;

import java.io.Serializable;
import java.util.AbstractSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author 刘镇 (suninformation@163.com) on 2017/9/25 下午3:47
 * @version 1.0
 */
public class ConcurrentHashSet<E> extends AbstractSet<E> implements Set<E>, Serializable {

    private static final Object __element = new Object();

    private final ConcurrentHashMap<E, Object> __target;

    public ConcurrentHashSet() {
        __target = new ConcurrentHashMap<E, Object>();
    }

    public ConcurrentHashSet(int capacity) {
        __target = new ConcurrentHashMap<E, Object>(capacity);
    }

    @Override
    public int size() {
        return __target.size();
    }

    @Override
    public boolean isEmpty() {
        return __target.isEmpty();
    }

    @Override
    public boolean contains(Object o) {
        return __target.containsKey(o);
    }

    @Override
    public Iterator<E> iterator() {
        final Iterator<Map.Entry<E, Object>> _iterator = __target.entrySet().iterator();
        return new Iterator<E>() {

            @Override
            public boolean hasNext() {
                return _iterator.hasNext();
            }

            @Override
            public E next() {
                return _iterator.next().getKey();
            }

            @Override
            public void remove() {
                _iterator.remove();
            }
        };
    }

    @Override
    public boolean add(E e) {
        return __target.put(e, __element) == null;
    }

    @Override
    public boolean remove(Object o) {
        return __target.remove(o) == __element;
    }

    @Override
    public void clear() {
        __target.clear();
    }
}
