Split Binary Frames With bytes.Split
Slice one buffer into NUL separated records with bytes.Split and rebuild with bytes.Join, then prove the framing lossless with bytes.Equal.
Page 15 of 50
Slice one buffer into NUL separated records with bytes.Split and rebuild with bytes.Join, then prove the framing lossless with bytes.Equal.
Collect channel events into batches that flush when full or when a resettable timer deadline expires, so bursts neither pile up unbounded nor drop.
Return functions that capture outer variables: each counter keeps independent state, and assignments inside a closure mutate the captured variable itself.
Test whether a string contains any rune from a class with strings.ContainsAny, then contrast it with IndexAny which reports the matching byte offset.
time.Duration is an int64, so json.Marshal emits integer nanoseconds by default; a custom MarshalJSON emits the 1h30m0s string instead.
cmd.Output takes only stdout, so stderr needs its own buffer: non-zero exits wrap in *exec.ExitError whose ExitCode reports the concrete status.
Read fixed-size records at offsets with File.ReadAt, whose pread semantics let parallel goroutines share one file handle without seeking.
Append each record with File.Sync so the durability contract is explicit: bytes reach stable storage before the call returns, surviving a crash.
Split file paths into directory, base name, and extension with filepath.Dir, filepath.Base, and filepath.Ext so CLI tools can name outputs predictably.
Resolve the process working directory with os.Getwd and join it with filepath.Join so relative config paths become absolute without string concatenation.
Drive an http.HandlerFunc with httptest.NewRequest and a response recorder so handler logic, headers, and error paths run without opening a listener.
Locate substrings with strings.Index and strings.LastIndex, treat the -1 result as not-found, and restart the search after a match to find later occurrences.
Assert at compile time that a concrete type satisfies an interface with var _ Iface = (*T)(nil), so missing methods fail the build before deployment.
json.NewEncoder plus SetIndent streams each value pretty-printed to any writer, appending a newline per Encode without assembling the whole document.
json.Marshal fails on chan and func fields: errors.As recovers *json.UnsupportedTypeError naming the exact Go type, so the wire keeps only encodable data.
Decode only the known fields via map[string]json.RawMessage and pass every other key through untouched, so unfamiliar payloads survive the round trip.
Decode timestamps arriving in several formats by trying layouts from strictest to loosest inside UnmarshalJSON and rejecting unknown shapes.
Extend json decoding without recursion: an alias type keeps the default decode while UnmarshalJSON normalizes fields on the way in.
log.New builds a logger with a prefix and flags; SetOutput swaps the sink to io.Discard to silence or a bytes.Buffer to capture in tests.
MarshalJSON on a pointer receiver is skipped when marshaling the bare value, so the JSON falls back to reflection; pass the pointer to engage it.
Compute square roots, powers, and logarithms with math.Sqrt, math.Pow, math.Log2, and math.Exp, and confirm invalid inputs propagate as NaN.
Create a whole nested directory chain in one call with os.MkdirAll, rely on its idempotence for repeat calls, and clean up the tree with os.RemoveAll.
Keep JSON and multi-line SQL readable in Go source with backtick raw string literals, where backslashes and quotes stay literal and newlines are preserved.
Compute rolling window totals with a running sum: add the entering element and subtract the leaving one instead of rescanning every window position.
Distribute work cyclically over one channel per worker with round-robin indexing, so each goroutine owns a private queue instead of contending on one.
Adapt slices into iter.Seq with slices.Values, then rebuild with slices.Collect, slices.AppendSeq, and maps.Collect so consumers stay decoupled from storage.
Convert a slice to a fixed-size array by value or to a shared array pointer, length-checking first so short frames never panic.
Merge adjacent case-variant duplicates with slices.CompactFunc, using strings.EqualFold as the comparator so GET, get and Get collapse.
Resolve expensive values only when a record is emitted: implement slog.LogValuer so the handler calls LogValue lazily instead of eagerly at call time.
Split log lines and paths with strings.SplitAfter so each returned segment retains its delimiter, making it easy to re-emit the original text exactly.
net.SplitHostPort splits host from port: bracketed IPv6 parses cleanly, a missing port or bare IPv6 returns a *net.AddrError with the reason.
Split a connection string or key-value pair with strings.SplitN so the remainder stays intact as one field instead of being shredded into extra segments.
CutPrefix and CutSuffix split once and report whether the prefix matched, distinguishing an empty value from a completely different token.
Delete from the middle of a slice without shifting: overwrite the slot with the last element and truncate, trading order for constant-time removal.
net.Listen plus an Accept loop gives each connection a goroutine that echoes bytes; SetReadDeadline bounds hung clients and errors.Is(io.EOF) detects closes.
Render the same instant in UTC, a plus-eight zone, and a minus-five-thirty zone without an IANA database, then format a parsed offset back with Z07:00.
Bucket days into report weeks with ISOWeek, where Monday starts the week and year boundaries follow the ISO 8601 ownership rule.
DialUDP pins a UDP peer so Write and Read address the same endpoint; a listener echoes by source address and SetReadDeadline bounds possible drops.
Derive the remaining time budget from a context deadline with time.Until, and report a negative duration once the deadline has already passed.
Printing a credential-bearing URL leaks the password; url.URL.Redacted swaps it for xxxx while User stays usable inside the process.
Turn relative links into absolute ones by resolving each against a base URL: path-only, root-relative, fragment-only, and dot-segment forms all resolve.
Cut a string to a rune limit without splitting multibyte characters: range walks rune boundaries so slicing always lands between characters.
Take an io.Writer parameter instead of writing to os.Stdout directly, so the same report code runs against a buffer in tests and stdout in main.
Compare nested arrays with Arrays.deepEquals and print them with deepToString, because equals and toString stop at the outer array reference.
Break a paragraph into directional runs with java.text.Bidi so renders can lay out LTR and RTL segments with correct bounds.
BreakIterator.getLineInstance exposes legal wrap positions at word boundaries so greedy wrapping never splits a word mid-line.
Heap buffers expose a backing array while direct buffers throw from array(), yet both share identical get/put APIs for the same byte-level reads.
Choose between REPORT and REPLACE on CharsetEncoder so unmappable characters either stop the encode with an exception or become a placeholder byte.
Walk a ConcurrentHashMap with forEach entry actions and keySet views, relying on weakly consistent iteration instead of snapshots.
RemoveIf deletes every element matching a predicate in one pass and reports whether anything changed, unlike manual iterator removal loops.
Merge two independent futures with thenCombine: the callback fires only once both stages complete, then ordinary thenApply chains continue downstream.
Observe the outcome of async work with whenComplete: the callback sees the success value or the failure exception without altering either path.
A custom Gatherer with ofSequential and Integrator.ofGreedy collapses consecutive repeats, showing state, downstream.push, and the boolean contract.
Confirm that Charset.defaultCharset is UTF-8 since JDK 18 regardless of platform, so charset-less getBytes and new String behave identically everywhere.
Call shutdownNow on a busy single-thread executor to interrupt the running task and drain the queue: it returns the runnables that never commenced.
Truncate a file in place with FileChannel.truncate, which only takes effect below the current size and is a documented no-op at or above it.
Files.createDirectory throws NoSuchFileException when a parent is missing, while createDirectories fills each level and is safe to call twice.
exists() and notExists() are both false when accessibility is unknown, so pair them to distinguish definitely missing from cannot tell.
Split a ForkJoinTask at a sequential threshold with invokeAll so the work-stealing pool stops forking once segments are small enough.
Bucket instants with truncatedTo for exact-duration units, fall back to epoch-second arithmetic for 15-minute windows, and learn where MONTHS throws.
JapaneseDate and ThaiBuddhistDate express the same LocalDate in era-based calendars, and convert straight back through getChronology.
Compose multi-key ordering with two sorts: pass one orders the tiebreak key, pass two sorts by the primary, and stable TimSort keeps that tiebreak order.
Declare a record inside a method to model intermediate results with methods and sorting, without widening the class-level API surface.
Sort map entries by value with Map.Entry.comparingByValue, then chain thenComparing(comparingByKey) so tied values keep a stable order.
Putting into a HashMap while iterating throws ConcurrentModificationException, while ConcurrentHashMap iterates weakly consistent without failing.
Distinguish "no match" from "not enough input yet" with hitEnd so streaming validators can wait for more data instead of rejecting early.
Show that Math.round sends ties toward positive infinity while RoundingMode.HALF_UP rounds away from zero, so -2.5 lands on -2 versus -3.
Compare MACs and hashes with MessageDigest.isEqual, whose constant-time scan avoids the early-exit leak that Arrays.equals has.
MonthDay.of(2, 29) maps to Feb 29 on leap years and Feb 28 otherwise, so recurring annual dates survive the calendar edge case.
Open a temp file channel with StandardOpenOption.DELETE_ON_CLOSE so the scratch file disappears when the channel closes, even on failure paths.
One thread watches accept and read readiness for many sockets with Selector and SelectionKey, including the manual selectedKeys removal loop.
startsWith and endsWith on Path compare whole path elements instead of characters, which keeps route matching honest when names share prefixes.
Persist small settings with the Preferences API: type-aware putters, safe getters with defaults, and an explicit flush to force the backing store.
Construct ReentrantLock(true) so blocked workers are granted the lock in arrival order instead of letting later threads barge ahead.
lockInterruptibly lets a blocked waiter be cancelled by interrupt, unlike lock(), so stuck lock waits cannot pin threads forever.
regionMatches compares character regions with an offset and an ignoreCase flag, giving allocation-free case-insensitive prefix and infix checks.
A monotonic deque keeps window candidates ordered so each index enters and leaves at most once, streaming maxima for sensors and rate windows.
Walk an XML document with the StAX XMLStreamReader cursor, dispatching on START_ELEMENT, CHARACTERS, and END_ELEMENT events as you pull them.
Deduplicate a stream by a chosen key with a seen-set filter, since distinct() only compares whole records by equals.
Slide a fixed-size window across a stream with Gatherers.windowSliding so every adjacent pair shares a window, unlike windowFixed non-overlapping batches.
Feed possibly-null values through Stream.ofNullable and flatMap so nulls vanish at the source instead of triggering NPE mid-pipeline.
Turn a string into an IntStream of chars, sort it, and compare signatures so anagram detection stays allocation-light on primitive streams.
Aa and BB share hashCode 2112 yet stay two entries in a HashMap, showing why equals must back every hash-based lookup.
String.replace treats the target as literal text while replaceAll compiles a regex, so a plain dot replaces itself or swallows every character.
Tell the two interrupt probes apart: static Thread.interrupted reads and clears the flag, instance isInterrupted only reads, and blocking calls clear it too.
Calling run() directly stays on the current thread; only start() creates a worker thread, shown by printing each execution thread name.
Classify characters with Character.UnicodeBlock so a validator can reject unexpected scripts instead of matching ad-hoc code point ranges.
Character.isDigit accepts every Unicode decimal digit while regex \d stays ASCII-only until UNICODE_CHARACTER_CLASS upgrades the character classes.
Character.UnicodeScript.of maps each code point to its writing script, letting validation route Latin, Han, or Hiragana input by script.
Parse, divide, and compare ints in the unsigned domain so values beyond Integer.MAX_VALUE keep their meaning across parseUnsignedInt and compareUnsigned.
Java UTF-8 decoding does not strip the BOM, so Files.readString on an Excel-style export starts with U+FEFF and header matches silently fail.
Evaluate XPath expressions against a DOM document: compile once for reuse, read scalars as strings, counts as NUMBER, node sets as NODESET.
Mount a ZIP via the zipfs provider with a jar: URI and create=true, create parent directories explicitly, then read and write entries with the Files API.
Convert time zones with withZoneSameInstant to keep the same moment, or withZoneSameLocal to keep the wall clock and knowingly change the instant.
Ask the zone rule table for the offset in force at an instant, whether daylight savings applies, and when the next clock change lands.
Wait for animationend instead of guessing durations, then remove the element with removeEventListener so CSS drives timing and JS only reacts.
Assert sync throws with assert.throws and async rejections with assert.rejects, matching error classes and message patterns exactly.
Buffer.alloc zero-fills every byte while allocUnsafe reuses pooled memory, so uninitialized bytes must be overwritten before leaving your code.
Measure the wire size of strings and buffers with Buffer.byteLength, because .length counts UTF-16 code units and diverges for CJK and emoji.
Adapt promise-returning functions to the classic Node error-first callback shape with util.callbackify, rejections included.