title: How do I safely and sensibly determine whether a pointer points somewhere into a specified buffer?
body: <p>I'm looking to implement a function that determines whether a given pointer points into a given buffer. The specification:</p>
  
  <hr>
  
  <pre><code>template &lt;typename T&gt;
  bool points_into_buffer (T *p, T *buf, std::size_t len);
  </code></pre>
  
  <p>If there is some <code>n</code>, <code>0 &lt;= n &amp;&amp; n &lt; len</code>, for which <code>p == buf + n</code>, returns <code>true</code>.</p>
  
  <p>Otherwise, if there is some <code>n</code>, <code>0 &lt;= n &amp;&amp; n &lt; len * sizeof(T)</code>, for which <code>reinterpret_cast&lt;char *&gt;(p) == reinterpret_cast&lt;char *&gt;(buf) + n</code>, the behaviour is undefined.</p>
  
  <p>Otherwise, returns <code>false</code>.</p>
  
  <hr>
  
  <p>The obvious implementation would look something like</p>
  
  <pre><code>template &lt;typename T&gt;
  bool points_into_buffer (T *p, T *buf, std::size_t len) {
      return p &gt;= buf &amp;&amp; p &lt; buf + len;
  }
  </code></pre>
  
  <p>but that has undefined behaviour in standard C++: relational comparisons of pointers are only defined for pointers into the same array.</p>
  
  <p>An alternative would be to use the standard library's comparer objects:</p>
  
  <pre><code>template &lt;typename T&gt;
  bool points_into_buffer (T *p, T *buf, std::size_t len) {
      return std::greater_equal&lt;T *&gt;()(p, buf) &amp;&amp; std::less&lt;T *&gt;()(p, buf + len);
  }
  </code></pre>
  
  <p>which is guaranteed to return <code>true</code> when I want it to return <code>true</code>, and avoids undefined behaviour, but allows for false positives: given <code>int a; int b;</code>, it allows a result of <code>true</code> for <code>points_into_buffer(&amp;a, &amp;b, 1)</code>.</p>
  
  <p>It can be implemented as a loop:</p>
  
  <pre><code>template &lt;typename T&gt;
  bool points_into_buffer (T *p, T *buf, std::size_t len) {
      for (std::size_t i = 0; i != len; i++)
          if (p == buf + i)
              return true;
      return false;
  }
  </code></pre>
  
  <p>However, compilers have trouble optimising away that loop.</p>
  
  <p>Is there a valid way of writing this, where with current compilers and optimisations enabled, the result is determined in constant time?</p>