1// Copyright 2014 The Chromium Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#ifndef MEDIA_CAST_COMMON_MOD_UTIL_H_
6#define MEDIA_CAST_COMMON_MOD_UTIL_H_
7
8#include <map>
9#include "base/logging.h"
10
11namespace media {
12namespace cast {
13
14// MAP is a map<uint??, ...> where the unsigned integer is
15// assumed to wrap around, but only a small range is used at a time.
16// Return the oldest entry in the map.
17template<class MAP>
18typename MAP::iterator ModMapOldest(MAP* map) {
19  typename MAP::iterator ret = map->begin();
20  if (ret != map->end()) {
21    typename MAP::key_type lower_quarter = 0;
22    lower_quarter--;
23    lower_quarter >>= 1;
24    if (ret->first < lower_quarter) {
25      typename MAP::iterator tmp = map->upper_bound(lower_quarter * 3);
26      if (tmp != map->end())
27        ret = tmp;
28    }
29  }
30  return ret;
31}
32
33// MAP is a map<uint??, ...> where the unsigned integer is
34// assumed to wrap around, but only a small range is used at a time.
35// Returns the previous entry in the map.
36template<class MAP>
37typename MAP::iterator ModMapPrevious(MAP* map, typename MAP::iterator i) {
38  DCHECK(!map->empty());
39  typename MAP::iterator ret = i;
40  if (i == map->begin()) {
41    ret = map->end();
42  }
43  ret--;
44  if (i == ret)
45    return map->end();
46  if ((i->first - ret->first) > ((typename MAP::key_type(0) - 1)) >> 1)
47    return map->end();
48  return ret;
49}
50
51}  // namespace cast
52}  // namespace media
53
54#endif
55