So far as I know, in the most if not all states in the US it's legal. The laws may specify "as far to the right as safely possible" or something like that, but they generally leave it up to you to evaluate what's safe.
Minnesota law, eg, states:
Subd. 4.Riding on roadway or shoulder.
(a) Every person operating a bicycle upon a roadway shall ride as close as practicable to the right-hand curb or edge of the roadway except under any of the following situations:
(1) when overtaking and passing another vehicle proceeding in the same direction;
(2) when preparing for a left turn at an intersection or into a private road or driveway;
(3) when reasonably necessary to avoid conditions, including fixed or moving objects, vehicles, pedestrians, animals, surface hazards, or narrow width lanes, that make it unsafe to continue along the right-hand curb or edge.
The problem, of course, is that you may encounter others (both drivers and law enforcement people) who do not interpret the law this way (mostly because they've never read it), but that's a problem for all cycling-related laws.