JDK代码的一个小bug

今天看了一点JDK的代码,不巧居然看到了 JDK 的一个小 bug, 呵呵。且看 javax.sql.rowset.serial 包下的 SerialBlob 类,其中有段代码如下
    /** 	
* Returns the position in this <code>SerialBlob</code> object where
* the given pattern of bytes begins, starting the search at the
* specified position.
*
* @param pattern the pattern of bytes for which to search
* @param start the position of the byte in this
* <code>SerialBlob</code> object from which to begin
* the search; the first position is <code>1</code>;
* must not be less than <code>1</code> nor greater than
* the length of this <code>SerialBlob</code> object
* @return the position in this <code>SerialBlob</code> object
* where the given pattern begins, starting at the specified
* position; <code>-1</code> if the pattern is not found
* or the given starting position is out of bounds; position
* numbering for the return value starts at <code>1</code>
* @throws SerialException if an error occurs when serializing the blob
* @throws SQLException if there is an error accessing the <code>BLOB</code>
* value from the database
*/
public long position(byte[] pattern, long start)
throws SerialException, SQLException {
if (start < 1 || start > len) {
return -1;
}

int pos = (int)start-1; // internally Blobs are stored as arrays.
int i = 0;
long patlen = pattern.length;

while (pos < len) {
if (pattern[i] == buf[pos]) {
if (i + 1 == patlen) {
return (pos + 1) - (patlen - 1);
}
i++; pos++; // increment pos, and i
} else if (pattern[i] != buf[pos]) {
pos++; // increment pos only
}
}
return -1; // not found
}

这个方法用于查找 blob 中是否存在 pattern 的字符数组,细看之下发现一个小 bug, 且看这段代码
        int pos = (int)start-1; // internally Blobs are stored as arrays. 
int i = 0;
long patlen = pattern.length;

while (pos < len) {
if (pattern[i] == buf[pos]) {
if (i + 1 == patlen) {
return (pos + 1) - (patlen - 1);
}
i++; pos++; // increment pos, and i
} else if (pattern[i] != buf[pos]) {
pos++; // increment pos only
}
}

当发现字符不匹配的情况下,应该将 i 置零,否则匹配结果是不正确的。当改为
        int pos = (int)start-1; // internally Blobs are stored as arrays. 
int i = 0;
long patlen = pattern.length;

while (pos < len) {
if (pattern[i] == buf[pos]) {
if (i + 1 == patlen) {
return (pos + 1) - (patlen - 1);
}
i++; pos++; // increment pos, and i
} else if (pattern[i] != buf[pos]) { // 其实这个判断也没有必要
pos++;
i = 0; // 在此处将 i 置 0
}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值