sometimes the usb4java high-level API returns strings which exceed past the null terminator
168399
private static String trimAtNull(final String s)
	{
		final int end = s.indexOf((char) 0);
		return end > -1 ? s.substring(0, end) : s;
	}
172228
def get_string_u_at_rva(self, rva, max_length = 2**16, encoding=None):
        """"""

        # If the RVA is invalid let the exception reach the callers. All
        # call-sites of get_string_u_at_rva() will handle it.
        data = self.get_data(rva, 2)
        # max_length is the maximum count of 16bit characters needs to be
        # doubled to get size in bytes
        max_length <<= 1

        requested = min(max_length, 256)
        data = self.get_data(rva, requested)
        # try to find null-termination
        null_index = -1
        while True:
            null_index = data.find(b'\x00\x00', null_index + 1)
            if null_index == -1:
                data_length = len(data)
                if data_length < requested or data_length == max_length:
                    null_index = len(data) >> 1
                    break
                else:
                    # Request remaining part of data limited by max_length
                    data += self.get_data(rva + data_length, max_length - data_length)
                    null_index = requested - 1
                    requested = max_length

            elif null_index % 2 == 0:
                null_index >>= 1
                break

        # convert selected part of the string to unicode
        uchrs = struct.unpack('<{:d}H'.format(null_index), data[:null_index * 2])
        s = u''.join(map(chr, uchrs))

        if encoding:
            return b(s.encode(encoding, 'backslashreplace_'))

        return b(s.encode('utf-8', 'backslashreplace_'))
768303
@Override public String getMessage() {
    String errnoName = OsConstants.errnoName(errno);
    if (errnoName == null) {
      errnoName = "errno " + errno;
    }
    String description = Libcore.os.strerror(errno);
    return functionName + " failed: " + errnoName + " (" + description + ")";
  }
1131824
public static final String asString(WsByteBuffer buff, int position, int limit) {
        byte[] data = asByteArray(buff, position, limit);
        return (null != data) ? new String(data) : null;
    }
1243692
function () {
                // Simple things first
                if(this._from.substr(this._at, 4) === 'null') {
                    this._at += 4;
                    return null;
                } else if(this._from.substr(this._at, 9) === 'undefined') {
                    this._at += 9;
                    return undefined;
                } else if(this._from.substr(this._at, 4) === 'true') {
                    this._at += 4;
                    return true;
                } else if(this._from.substr(this._at, 5) === 'false') {
                    this._at += 5;
                    return false;
                } else if(this._from.substr(this._at, 3) === 'NaN') {
                    this._at += 3;
                    return NaN;
                } else if(this._from.substr(this._at, 8) === 'Infinity') {
                    this._at += 8;
                    return Infinity;
                } else if(this._from.substr(this._at, 9) === '-Infinity') {
                    this._at += 9;
                    return -Infinity;
                }
                // JSON escaped string?
                if(this._from.charAt(this._at) === '"') {
                    var end = this._at + 1;
                    while(end < this._from.length) {
                        if(this._from.charAt(end) === '\\') {
                            end += 1;
                        } else if(this._from.charAt(end) === '"') {
                            break;
                        }
                        end += 1;
                    }
                    if(end < this._from.length) {
                        var s = this._from.substr(this._at, end - this._at + 1);
                        this._at = end + 1;
                        return JSON.parse(s);
                    }
                }
                // Reference?
                if(this._from.charAt(this._at) === '<' && this._from.charAt(this._at + 1 + shared.utils.uidStringLength) === '>') {
                    var id = this._from.substr(this._at + 1, shared.utils.uidStringLength);
                    this._at += (2 + shared.utils.uidStringLength);
                    return new Reference(shared.utils.makeUID(id));
                }
                // Maybe a number
                var l = this.numberLength();
                if(l) {
                    var n = parseFloat(this._from.substr(this._at));
                    shared.utils.dassert(!isNaN(n));
                    this._at += l;
                    return n;
                }
                shared.utils.defaultLogger().fatal('Unexpected value encoding: %s', this._from.substr(this._at));
            }
499589
def null_term(str):
    ''''''
    if sys.version_info.major < 3:
        return str
    if isinstance(str, bytes):
        str = str.decode("utf-8")
    idx = str.find("\0")
    if idx != -1:
        str = str[:idx]
    return str
836751
public @CheckForNull T get(String key) throws IOException {
        return get(key,false,null);
    }
1167904
private static String validString(Object data) throws IOException {
        // Null is ok
        if (data == null) {
            return "";
        }
        if (!(data instanceof String)) {
            throw new IOException("Invalid non-String value found!");
        }
        return (String) data;
    }
492692
public static void dumpNonNull(String name, Object obj) {
		dumpNonNull(name, obj, StringPrinter.systemOut());
	}
164930
private JdbcConnectionDescriptor deepCopyOfFirstFound(String jcdAlias)
    {
        Iterator it = jcdMap.values().iterator();
        JdbcConnectionDescriptor jcd;
        while (it.hasNext())
        {
            jcd = (JdbcConnectionDescriptor) it.next();
            if (jcdAlias.equals(jcd.getJcdAlias()))
            {
                return (JdbcConnectionDescriptor) SerializationUtils.clone(jcd);
            }
        }
        return null;
    }
404563
long getCharIntervalMicro(double chars) {
        // Make use we have a gap of 3.5 characters between adjacent requests
        // We have to do the calculations here because it is possible that the caller may have changed
        // the connection characteristics if they provided the connection instance
        return (long) chars * NS_IN_A_MS * (1 + commPort.getNumDataBits() + commPort.getNumStopBits() + (commPort.getParity() == AbstractSerialConnection.NO_PARITY ? 0 : 1)) / commPort.getBaudRate();
    }
975113
public static String extractToString(final DeviceData deviceDataArgout) throws DevFailed {
	final Object[] values = CommandHelper.extractArray(deviceDataArgout);
	Object value = null;
	String argout = "";
	if (values.length == 1) {
	    value = values[0];
	    if (value instanceof DevState) {
		argout = StateUtilities.getNameForState((DevState) value);
	    } else if (value instanceof DevVarLongStringArray) {
		final int[] intValues = ((DevVarLongStringArray) value).lvalue;
		final String[] stringValues = ((DevVarLongStringArray) value).svalue;
		for (int i = 0; i < stringValues.length; i++) {
		    argout = argout + "DevVarLongStringArray[" + i + "]=(" + intValues[i] + ","
			    + stringValues[i] + ")\n";
		}
	    } else if (value instanceof DevVarDoubleStringArray) {
		final double[] doubleValues = ((DevVarDoubleStringArray) value).dvalue;
		final String[] stringValues = ((DevVarDoubleStringArray) value).svalue;
		for (int i = 0; i < stringValues.length; i++) {
		    argout = argout + "DevVarDoubleStringArray[" + i + "]=(" + doubleValues[i]
			    + "," + stringValues[i] + ")\n";
		}
	    } else {
		argout = value.toString();
	    }
	} else if (values.length > 1) {
	    for (int i = 0; i < values.length; i++) {
		if (values[i] instanceof DevState) {
		    argout = argout + values[i].getClass().getSimpleName() + "[" + i + "]="
			    + StateUtilities.getNameForState((DevState) values[i]) + "\n";
		} else {
		    argout = argout + values[i].getClass().getSimpleName() + "[" + i + "]="
			    + values[i].toString() + "\n";
		}
	    }
	} else {
	    Except.throw_exception("TANGO_WRONG_DATA_ERROR", "output type " + value.getClass()
		    + " not supported",
		    "CommandHelper.extractToString(Object value,deviceDataArgin)");
	}

	return argout;
    }
757263
@Nullable
    public static String readUTF(@NotNull final InputStream stream) throws IOException {
        final DataInputStream dataInput = new DataInputStream(stream);
        if (stream instanceof ByteArraySizedInputStream) {
            final ByteArraySizedInputStream sizedStream = (ByteArraySizedInputStream) stream;
            final int streamSize = sizedStream.size();
            if (streamSize >= 2) {
                sizedStream.mark(Integer.MAX_VALUE);
                final int utfLen = dataInput.readUnsignedShort();
                if (utfLen == streamSize - 2) {
                    boolean isAscii = true;
                    final byte[] bytes = sizedStream.toByteArray();
                    for (int i = 0; i < utfLen; ++i) {
                        if ((bytes[i + 2] & 0xff) > 127) {
                            isAscii = false;
                            break;
                        }
                    }
                    if (isAscii) {
                        return fromAsciiByteArray(bytes, 2, utfLen);
                    }
                }
                sizedStream.reset();
            }
        }
        try {
            String result = null;
            StringBuilder builder = null;
            for (; ; ) {
                final String temp;
                try {
                    temp = dataInput.readUTF();
                    if (result != null && result.length() == 0 &&
                        builder != null && builder.length() == 0 && temp.length() == 0) {
                        break;
                    }
                } catch (EOFException e) {
                    break;
                }
                if (result == null) {
                    result = temp;
                } else {
                    if (builder == null) {
                        builder = new StringBuilder();
                        builder.append(result);
                    }
                    builder.append(temp);
                }
            }
            return (builder != null) ? builder.toString() : result;
        } finally {
            dataInput.close();
        }
    }
1232669
@Override
    public boolean parseBinaryFirstLine(WsByteBuffer buff) throws MalformedMessageException {
        if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
            Tr.debug(tc, "parseBinaryFirstLine for " + this);
            Tr.debug(tc, "Buffer: " + buff);
        }
        if (getBinaryParseState() == HttpInternalConstants.PARSING_BINARY_VERSION) {
            if (!buff.hasRemaining()) {
                return false;
            }
            byte version = buff.get();
            if (version != HttpInternalConstants.BINARY_TRANSPORT_V1) {
                if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                    Tr.debug(tc, "Unsupported binary version in message: " + version);
                }
                throw new MalformedMessageException("Invalid binary message");
            }
            setBinaryParseState(HttpInternalConstants.PARSING_METHOD_ID_OR_LEN);
            resetCacheToken(4);
        }

        boolean complete = false;
        int value;
        while (!complete) {
            // at this point, the parsed token array is always set up, so we
            // can try to fill it now
            if (!fillCacheToken(buff)) {
                return false;
            }
            switch (getBinaryParseState()) {
                case HttpInternalConstants.PARSING_METHOD_ID_OR_LEN:
                    value = GenericUtils.asInt(getParsedToken());
                    if (0 == (value & GenericConstants.KNOWN_MASK)) {
                        setMethod(MethodValues.getByOrdinal(value));
                        setBinaryParseState(HttpInternalConstants.PARSING_URI_LEN);
                        resetCacheToken(4);
                    } else {
                        setBinaryParseState(HttpInternalConstants.PARSING_UNKNOWN_METHOD);
                        resetCacheToken(value & GenericConstants.UNKNOWN_MASK);
                    }
                    break;
                case HttpInternalConstants.PARSING_UNKNOWN_METHOD:
                    setMethod(MethodValues.find(getParsedToken()));
                    setBinaryParseState(HttpInternalConstants.PARSING_URI_LEN);
                    createCacheToken(4);
                    break;

                case HttpInternalConstants.PARSING_URI_LEN:
                    setBinaryParseState(HttpInternalConstants.PARSING_URI);
                    resetCacheToken(GenericUtils.asInt(getParsedToken()));
                    break;

                case HttpInternalConstants.PARSING_URI:
                    setRequestURL(getParsedToken());
                    setBinaryParseState(HttpInternalConstants.PARSING_VERSION_ID_OR_LEN);
                    createCacheToken(4);
                    break;

                case HttpInternalConstants.PARSING_VERSION_ID_OR_LEN:
                    value = GenericUtils.asInt(getParsedToken());
                    if (0 == (value & GenericConstants.KNOWN_MASK)) {
                        setVersion(VersionValues.getByOrdinal(value));
                        setBinaryParseState(GenericConstants.PARSING_HDR_FLAG);
                        resetCacheToken(4);
                        complete = true;
                    } else {
                        setBinaryParseState(HttpInternalConstants.PARSING_UNKNOWN_VERSION);
                        resetCacheToken(value & GenericConstants.UNKNOWN_MASK);
                    }
                    break;

                case HttpInternalConstants.PARSING_UNKNOWN_VERSION:
                    setVersion(VersionValues.find(getParsedToken()));
                    setBinaryParseState(GenericConstants.PARSING_HDR_FLAG);
                    createCacheToken(4);
                    complete = true;
                    break;

                default:
                    throw new MalformedMessageException("Invalid state in first line: " + getBinaryParseState());
            } // end of switch block

        } // end of while loop

        setFirstLineComplete(true);
        return true;
    }
628950
private static List<String> getDeviceDescriptionsLowLevel()
	{
		final Context ctx = new Context();
		final int err = LibUsb.init(ctx);
		if (err != 0) {
			slogger.error("LibUsb initialization error {}: {}", -err, LibUsb.strError(err));
			return Collections.emptyList();
		}
		try {
			final DeviceList list = new DeviceList();
			final int res = LibUsb.getDeviceList(ctx, list);
			if (res < 0) {
				slogger.error("LibUsb device list error {}: {}", -res, LibUsb.strError(res));
				return Collections.emptyList();
			}
			try {
				return StreamSupport.stream(list.spliterator(), false).map(UsbConnection::printInfo)
						.collect(Collectors.toList());
			}
			finally {
				LibUsb.freeDeviceList(list, true);
			}
		}
		finally {
			LibUsb.exit(ctx);
		}
	}
411702
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
        in.defaultReadObject();
        boolean isValid = maxOffset >= -1
                && formats.length > maxOffset
                && offsets.length > maxOffset
                && argumentNumbers.length > maxOffset;
        if (isValid) {
            int lastOffset = pattern.length() + 1;
            for (int i = maxOffset; i >= 0; --i) {
                if ((offsets[i] < 0) || (offsets[i] > lastOffset)) {
                    isValid = false;
                    break;
                } else {
                    lastOffset = offsets[i];
                }
            }
        }
        if (!isValid) {
            throw new InvalidObjectException("Could not reconstruct MessageFormat from corrupt stream.");
        }
    }
1135945
@SuppressWarnings("unchecked")
	@Override
	protected StringBuffer doPostProcessBundle(BundleProcessingStatus status, StringBuffer bundleData)
			throws IOException {

		if (LOGGER.isInfoEnabled()) {
			LOGGER.info("Base64 encoding resources - '" + status.getLastPathAdded() + "'");
		}

		Map<String, Base64EncodedResource> encodedResources = (Map<String, Base64EncodedResource>) status
				.getData(JawrConstant.BASE64_ENCODED_RESOURCES);
		if (encodedResources == null) {
			encodedResources = new HashMap<>();
			status.putData(JawrConstant.BASE64_ENCODED_RESOURCES, encodedResources);
		}

		StringBuffer sb = bundleData;
		if (status.getProcessingType().equals(BundleProcessingStatus.FILE_PROCESSING_TYPE)) {
			sb = super.doPostProcessBundle(status, bundleData);
		}

		if (!encodedResources.isEmpty() && status.isSearchingPostProcessorVariants()) {
			VariantSet variantSet = new VariantSet(JawrConstant.BROWSER_VARIANT_TYPE, "",
					new String[] { "", JawrConstant.BROWSER_IE6, JawrConstant.BROWSER_IE7 });
			status.addPostProcessVariant(JawrConstant.BROWSER_VARIANT_TYPE, variantSet);
			variantSet = new VariantSet(JawrConstant.CONNECTION_TYPE_VARIANT_TYPE, "",
					new String[] { "", JawrConstant.SSL });
			status.addPostProcessVariant(JawrConstant.CONNECTION_TYPE_VARIANT_TYPE, variantSet);
		}

		if (!status.isSearchingPostProcessorVariants()
				&& status.getProcessingType().equals(BundleProcessingStatus.BUNDLE_PROCESSING_TYPE)) {

			Map<String, String> bundleVariants = status.getBundleVariants();
			if (bundleVariants != null) {
				String browser = bundleVariants.get(JawrConstant.BROWSER_VARIANT_TYPE);
				if (StringUtils.isNotEmpty(browser)
						&& (JawrConstant.BROWSER_IE6.equals(browser) || JawrConstant.BROWSER_IE7.equals(browser))) {
					prependBase64EncodedResources(sb, encodedResources);
				}
			}
		}

		if (LOGGER.isInfoEnabled()) {
			LOGGER.info("Base64 Postprocessing done");
		}
		return sb;
	}