1/********************************************************************
2 * Copyright (c) 2013 - 2014, Pivotal Inc.
3 * All rights reserved.
4 *
5 * Author: Zhanwei Wang
6 ********************************************************************/
7/********************************************************************
8 * 2014 -
9 * open source under Apache License Version 2.0
10 ********************************************************************/
11/**
12 * Licensed to the Apache Software Foundation (ASF) under one
13 * or more contributor license agreements. See the NOTICE file
14 * distributed with this work for additional information
15 * regarding copyright ownership. The ASF licenses this file
16 * to you under the Apache License, Version 2.0 (the
17 * "License"); you may not use this file except in compliance
18 * with the License. You may obtain a copy of the License at
19 *
20 * http://www.apache.org/licenses/LICENSE-2.0
21 *
22 * Unless required by applicable law or agreed to in writing, software
23 * distributed under the License is distributed on an "AS IS" BASIS,
24 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
25 * See the License for the specific language governing permissions and
26 * limitations under the License.
27 */
28#include "Exception.h"
29#include "ExceptionInternal.h"
30#include "LocatedBlock.h"
31#include "LocatedBlocks.h"
32
33#include <algorithm>
34#include <cassert>
35#include <iostream>
36
37namespace Hdfs {
38namespace Internal {
39
40const LocatedBlock * LocatedBlocksImpl::findBlock(int64_t position) {
41 if (position < fileLength) {
42 LocatedBlock target(position);
43 std::vector<LocatedBlock>::iterator bound;
44
45 if (blocks.empty() || position < blocks.begin()->getOffset()) {
46 return NULL;
47 }
48
49 /*
50 * bound is first block which start offset is larger than
51 * or equal to position
52 */
53 bound = std::lower_bound(blocks.begin(), blocks.end(), target,
54 std::less<LocatedBlock>());
55 assert(bound == blocks.end() || bound->getOffset() >= position);
56 LocatedBlock * retval = NULL;
57
58 if (bound == blocks.end()) {
59 retval = &blocks.back();
60 } else if (bound->getOffset() > position) {
61 assert(bound != blocks.begin());
62 --bound;
63 retval = &(*bound);
64 } else {
65 retval = &(*bound);
66 }
67
68 if (position < retval->getOffset()
69 || position >= retval->getOffset() + retval->getNumBytes()) {
70 return NULL;
71 }
72
73 return retval;
74 } else {
75 return lastBlock.get();
76 }
77}
78
79}
80}
81